From n/a Mon May 24 20:33:15 2004 From: n/a (Oten) Date: Mon, 24 May 2004 17:33:15 -0700 Subject: Jython Issues Message-ID: <10b552jje92ka66@corp.supernews.com> Ok I have looked all over the internet and I can't find what I am doing wrong or how I can do it right I am using windows xp Jython 2.1 I am trying to invoke the jython interpreter I have set my Path in my environment variables to D:\jython-2.1; everything has installed fine but when I try to run the command jython from dos a list of other commands appear that go with the interpreter so I tried jython -? and jython -help and the same thing Python and Java are both installed with latest stable versions of both any help is always appreciated thanks in advance From nuffsaid at phreaker.net Sat May 1 15:12:14 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Sat, 01 May 2004 21:12:14 +0200 Subject: web start References: Message-ID: On Fri, 30 Apr 2004 18:49:57 +0000, John Fabiani wrote: > In the Java world they have a way to start and update programs using web > start. Is there something like web start for Python? If you feel comfortable in the Java world (?), then you might consider to use Jython. (Google for *Jython "web start"* and you will find some information this approach.) HTH, Nuff. From winexpert at hotmail.com Thu May 27 14:55:24 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 18:55:24 +0000 Subject: an example of DC OCILobWrite Message-ID: Does anyone have an example of how the DCOracle driver from python does a blob write? I haven't been able to find much of anything so far on this topic. I did find out that the function might be called OCILobWrite. But I would like to see an example so I can figure out how to make it work. I found a reference to Large Objects at http://zope.org/Products/DCOracle/DCOracle.txt/document_view Thanks in advance, David ------- cell phone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From danu_milis at yahoo.com Tue May 25 12:28:24 2004 From: danu_milis at yahoo.com (danu kusmana) Date: Tue, 25 May 2004 09:28:24 -0700 (PDT) Subject: SimpleXMLRPCServer performance issue in MSWin Message-ID: <20040525162824.78925.qmail@web60604.mail.yahoo.com> Hi Im trying to figure out why the same server script I use is running slower in Windows than in Linux. ServerTest.py: #! /usr/bin/env python import SocketServer from SimpleXMLRPCServer import * import xmlrpclib class Metode: def __init__(self): self.nilai = 0 def ambil(self): self.nilai += 1 return self.nilai def terima(self, NilaiBaru): return xmlrpclib.True class ServerTest(SocketServer.ThreadingMixIn, SimpleXMLRPCServer): pass server = ServerTest(('192.168.1.108', 7777)) server.register_instance(Metode()) server.serve_forever() I also notice that the threading in Windows only the MainThread even when multiple clients are accessing the server. So I assume only 1 thread is being processed. ClientTest.py: #! /usr/bin/env python import xmlrpclib BilPrima = 0 conn = xmlrpclib.Server("http://192.168.1.108:7777") def prima(x): global BilPrima for TestFactor in range(2, x): if (x % TestFactor == 0): break elif (TestFactor != x - 1): continue else: BilPrima = x return BilPrima while(1): nilai = conn.ambil() if nilai <= 1000000: temp = prima(nilai) if temp == None: continue else: print temp conn.terima(temp) else: break thanks danu __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From heikowu at ceosg.de Sun May 30 04:46:44 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 30 May 2004 10:46:44 +0200 Subject: Creating a new object of your own type in a C extension. Message-ID: <200405301046.44767.heikowu@ceosg.de> Hi all! Just a small question concerning type creation in a C object: If I create a class which is overridable, I'd like to have that class create objects of it's overridden type, e.g. I have a class X which is implemented in C, which is wrapped in Python by a class Y, now I initialize a Y class, and call a member of X on that class, and I'd like the member of X to return an object of class Y. What is a correct way of doing this? I've not found any nice implementation hints in the documentation... 1) PyObject_New(Xstruct, self->ob_type (which should point to the type of Y)) 2) self->ob_type->tp_new(self->ob_type,NULL,NULL) 3) anything else? I don't see any of this being used in the Python object classes (e.g. overridden classes of int return int when e.g. __add__ is called, etc.). Thanks for any help! Heiko. From Romans.Krjukovs at lattelekom.lv Thu May 13 08:55:53 2004 From: Romans.Krjukovs at lattelekom.lv (Romans Krjukovs) Date: Thu, 13 May 2004 15:55:53 +0300 Subject: Python - open forever ? Message-ID: <593D8B10B2409E468D3E916CA156C84D0326C930@mail02.ad.telekom.lv> Hi ! Our company is going to start use Python widely. To make this reality we have to include Python in our strategy plans for at least 3 nearest years. This would be a green light to our developers to start new projects on Python. At the presentation of Python and its usage posiibilities in our home environment to the members of the project managers board, we got such questions: - There is a risk that Python can become closed and unsupported in the future. (Remember RedHat ?) - Who can guarantee that Python will be usable and available to us if it is develeped and maintained by the hackers from all over the world without any obligations and guarantees ? - How we can minimize such risk ? (Become a member of some club, buy licenses, support etc.) Python is very fast in development, stable and fast code, easy to learn, but never the less big and business critical project can't be started without mentioned risk analyses. It would be nice to know what Python society members think about this. Thank You ! BRG Romans Krjukovs From mark at prothon.org Sun May 30 00:54:33 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 30 May 2004 00:54:33 -0400 Subject: Prothon vs. Python integers References: <%WRsc.18276$bF3.9891@fed1read01> Message-ID: Marcin 'Qrczak' Kowalczyk wrote: > On Tue, 25 May 2004 17:59:20 -0700, Mark Hahn wrote: > >> I've agreed to adding longs. I'm thinking of only having longs. > > It's more efficient if ints which fit in a machine word (or a machine > word minus one or two bits used for tagging them as ints) are > represented as such, rather than using a generic big int > representation. > > It doesn't mean they should be treated differently in the language. > It can be a hidden implementation detail, visible only for those who > write extensions in C. I've already implemented the new ints in Prothon. They behave as normal ints until an overflow occurs and then they are treated as a bigint. There is no performance penalty at all because I have to check for overflow anyway. C extension coders see no difference unless they want to deal with bigints. Macros provide access to the ints and if they ask for a normal size int that is actually a bigint it just throws an excepton. From peter at designtheory.org Sat May 1 16:30:30 2004 From: peter at designtheory.org (Peter Dobcsanyi) Date: 1 May 2004 20:30:30 GMT Subject: bags in collections - PEP 320 References: Message-ID: Aahz wrote: > Given the lack of response to your post, I'd suggest that you send your > comments directly to the PEP author. Thanks for your suggestion. I already sent my comments to Raymond Hettinger and we are being engaged in a discussion. Peter From smcg4191 at frii.RemoveThisToReply.com Wed May 26 18:13:38 2004 From: smcg4191 at frii.RemoveThisToReply.com (Stuart McGraw) Date: Wed, 26 May 2004 16:13:38 -0600 Subject: popen and unicode References: <40b382d2$0$206$75868355@news.frii.net> Message-ID: <40b516a0$0$205$75868355@news.frii.net> Thanks for the info, Neil. I tried using spawnv too, with slightly different but still unsuccessful results. With spawn, the spawned program is receiving unicode characters, but non-ascii range characters have been converted to unicode "?" before the spawned program receives them. . I looked into calling the Windows API using Ctypes but how to convert a C *File pointer returned by Windows' popen() to something that Python could use, was not at all clear to me. I guess it would be fairly simple with a C extension, but that is a bit beyond me at this point. So, to my surprise, I conclude that it is not currently feasible to work with the process stuff and unicode file names on a Windows machine with Python. I would still love to find out I am wrong though. And I think this info should be in the documentation. It would have saved me a couple day's work. "Neil Hodgson" wrote in message news:X6Psc.10837$L.2358 at news-server.bigpond.net.au... > Stuart McGraw: > > > Does os.popen() work with unicode strings containing characters outside > > the ASCII range? (I think I answered my own question, above.) > > There is no Unicode support in the current implementation of popen. This > could be added in a similar way to the Unicode file name support but it is > more work than I currently have time for. If you are interested in fixing > this, the code is in dist/src/Modules/posixmodule.c _PyPopenCreateProcess. > > > How can I call popen to process non-ascii filenames on a Windows box? > > Is there anything else I could use (e.g. spawn) that will work with > unicode > > filnames? > > You can use ctypes to call the underlying platform APIs. > > Neil > > From matthiasverniers at mail15.com Tue May 18 17:27:02 2004 From: matthiasverniers at mail15.com (Matthias) Date: Tue, 18 May 2004 23:27:02 +0200 Subject: installing modules compiled with visual studio Message-ID: Hello I am a programming newbie, trying to install the "Twisted" package from source, on a Windows computer with Python 2.3 installed. But when I try to build the sources it gives an error: "Python was built with version 6 Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed". It seems there are some C or C++ libs included in the package, but Python can't install them because I don't have Visual Studio installed. Is there a way I can build the extensions without using Visual Studio ? I have another C++ compiler installed on my pc. Help would really be appreciated as I need the package, now I run an older version that came with an installer, but I really need the newer package. Regards Matthias From pballard at ozemail.com.au Wed May 26 08:39:07 2004 From: pballard at ozemail.com.au (Peter Ballard) Date: 26 May 2004 05:39:07 -0700 Subject: modifying mutable list elements in a for loop Message-ID: <9d5509fa.0405260439.175797e@posting.google.com> Whew. I hope that title is descriptive! Hi all, The python tutorial tells me "It is not safe to modify the sequence being iterated over in the loop". But what if my list elements are mutable, such as lists or objects, e.g. a = [[1,2], [3,4], [5,6], [7,8]] for coord in a: coord.append(10) print str(a) When I tried it, it gave the "expected" answer, i.e. [[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]] It worked, but is it safe? I can't see why it wouldn't be, but technically I have broken the rules because I have modified the sequence which is being looped over. [It seems to me that the list elements are pointers (in C-speak), so I can safely modify the data they are pointing to, because I am not modifying the list elements themselves. Or is that an implementation detail (i.e. not safe)?] Actually the more I think about it the more I think it must be OK, because how else can one perform an operation on a list of objects? But that phrase "It is not safe to modify the sequence being iterated over in the loop" in the tutorial has me slightly worried. -- Regards, Peter Ballard Adelaide, AUSTRALIA pballard at ozemail.com.au http://members.ozemail.com.au/~pballard/ From P at draigBrady.com Thu May 20 08:06:41 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 20 May 2004 13:06:41 +0100 Subject: GTK or TKinter (or what else?) In-Reply-To: References: Message-ID: Marco Terzuoli wrote: > Hi, > I use python under linux and would like to create some GUI applications. I > have seen that Python can be used together woth some different graphic > libraries and would like to have a suggestion about which one to use. > I feel like GTK is better documented bud would not like to create programs > which are not fully portable. Moreover, I know you can use wxWindows as > well... I have tried it in my C program and didn't like the way events were > handled. Are there any differences in Python? > Thanks > Marco I would definitely recommend GTK. It has huge support being it now and it's supported on windows now also. I've some example apps here: http://www.pixelbeat.org/talks/pygtk/ P?draig. From bignose-hates-spam at and-benfinney-does-too.id.au Tue May 25 20:09:01 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 26 May 2004 09:59:01 +0950 Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: On Tue, 25 May 2004 15:44:25 GMT, Dennis Lee Bieber wrote: > On 25 May 2004 16:35:29 +0950, Ben Finney wrote: >> The usage of "i" was promulgated by the FORTRAN language, which >> allowed only single-letter variable names (and was all upper case, > > That must have been a really old version of FORTRAN -- all versions > I've encountered allowed for, at least, 6 significant characters in > variable names. (This goes back to F-IV/F-66). BASIC was limited to > one or two characters. Yes, I've since been corrected; FORTRAN allowed at least 6 characters for variable names. I was confused by my memory of the "I through N" rule of FORTRAN's integer/real split; for some reason that translated into erroneously thinking the variables were only one character in length. I'm in agreement with others that FORTRAN was, in this regard, influeced by the existing mathematical formula convention of 'i', 'j', 'k' etc. for vector subscripts. Since FORTRAN, as the language name indicates, was initially used for mathematical formula algorithms, the use of a FOR loop to iterate through a vector (or array) was common, and thus using the variable I for the index would seem natural to a mathematically-oriented programmer. -- \ "There is no reason anyone would want a computer in their | `\ home." -- Ken Olson, president, chairman and founder of | _o__) Digital Equipment Corp., 1977 | Ben Finney From me at privacy.net Fri May 28 08:12:33 2004 From: me at privacy.net (Duncan Booth) Date: 28 May 2004 12:12:33 GMT Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> <40b72a41$0$128$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote in news:40b72a41$0$128$3a628fcd at reader3.nntp.hccnet.nl: > d = ['0891931243\n', '0325443777\n', '0933477028\n', > '0699624617\n', '0922210996\n'] > > #swap rows and columns, with the side effect of turning > #strings into lists, strings must be of equal length or > #else some information will be lost: > > d1 = zip(*d) > > #remove a row (corresponds to a *column* in the old view) > #this is an elementary operation now: > > del d1[-1] > > #swapping again restores the old row and column view: > > d1 = zip(*d1) > > #join the elements of the sublists in order to produce strings: > > d1 = map(''.join,d1) > > print d1 > > #output is: > #['0891931243', '0325443777', '0933477028', '0699624617', > #'0922210996'] This, of course, only works when the strings are all exactly the same length. If they are different lengths it truncates all the strings to the length of the shortest. From SeeBelow at SeeBelow.Nut Wed May 26 00:42:43 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 26 May 2004 04:42:43 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <40B3F448.EB711333@shaw.ca> Message-ID: <40B4205D.8C5B643B@shaw.ca> Roy Smith wrote: > > In article <40B3F448.EB711333 at shaw.ca>, SeeBelow at SeeBelow.Nut wrote: > > > > More than that, most times I've decided to not bother making something a > > > class because it was too simple, I've eventually added enough > > > functionality to it to change my mind and have to re-do things. That's > > > real cost. Much simplier and cheaper to just make it a class from the > > > get-go. > > > > Why does greater functionality make a class desireable, if there won't > > be multiple instances created? > > For me, it's more about encapsulation than code re-use. If I've got a > bunch of functions which operate on a collection of data, to me that > says "object", which in Python (and most OOPL's) implies "class". OK, that makes some sense - to associate certain data and code items and separate them from other code and data. Wouldn't that purpose be served even better by putting them into a different file, and not bother with a class? > Bundling it up into a class lets me think about it as a unit. Each > class is a convenient thought unit for design and testing, and also for > understanding somebody else's code. > > I don't think there's a need to be dogmatic about it. It's just what I > find is a natural way to break a program down into smaller pieces you > can get your brain around one piece at a time. -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From segphault at sbcglobal.net Tue May 25 21:09:38 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 26 May 2004 01:09:38 GMT Subject: Embedding Python at the OS level - build problems References: Message-ID: On Tue, 25 May 2004 20:34:14 -0400, Phil Frost wrote: > Greetings all. I'm attempting to embed a python interpreter at a very > low level in an OS I am writing. Currently I'm stuck with build issues. > Firstly, as there is no working C compiler in our OS, I must cross > compile Python. I encountered errors when building Parser/pgen; I got > around this by building it nativly and copying it. Hopefully this won't > get me later... > > My current problem (and there are sure to be more ;) ) is when building > Modules/posixmodule.c. I've already done a great deal of hacking; I > manually commented the inclusion of stropts.h as it was getting it from > /usr/include which is not part of the target machine's include files. > That was probably not a good idea, but hey... > > Now, I get: > > /home/indigo/dev/uuu/uuu/lib/c/bin-i386/diet gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o > Modules/posixmodule.c: In function `posix_openpty': > Modules/posixmodule.c:2623: warning: implicit declaration of function `ioctl' > Modules/posixmodule.c:2623: error: `I_PUSH' undeclared (first use in this function) > Modules/posixmodule.c:2623: error: (Each undeclared identifier is reported only once > Modules/posixmodule.c:2623: error: for each function it appears in.) > Modules/posixmodule.c: In function `posix_setgroups': > Modules/posixmodule.c:4527: error: `MAX_GROUPS' undeclared (first use in this function) > > I really have a swarm of questions. Among them are: > > - is there a better way to cross compile python? > - is there anything I can do about the above error? > > But most importantly: > > - is the posix module really required? At the moment, I'm interested in > only getting a minimal Python working, so anything that can be > disabled, should be. What things can I do to eliminate all features, > modules, and whatever that isn't required to build libpython2.3.a? interesting project. what are the benefits of integrating python into an operating system? I could understand making kernel modules for services that you would otherwise run as a daemon, but what is the motivation for such low level integration of a high level interpreter? From greg at cosc.canterbury.ac.nz Tue May 11 23:42:56 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 12 May 2004 15:42:56 +1200 Subject: Unification of Methods and Functions In-Reply-To: References: Message-ID: <2gdkq6F1lkamU1@uni-berlin.de> David MacQuigg wrote: > Prothon is trying to make binding explicit, That's not entirely true. Prothon currently has cat1.meth() doing binding just as implicitly as Python. What it doesn't do is bind implicitly when you're not going to call the method right away, which from a Python perspective is decidedly odd, not to mention rather inconsistent. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mark at prothon.org Tue May 25 23:18:04 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 25 May 2004 20:18:04 -0700 Subject: Prothon vs. Python integers References: <40b3111d$0$7727$afc38c87@news.easynet.co.uk> <2hifh1Fdk1c3U1@uni-berlin.de> Message-ID: <2ZTsc.18494$bF3.7137@fed1read01> Greg Ewing wrote: >> Surely >> once you get to 3.7e19 you are in floating point territory. > > Incorrect. You're only ever in floating point territory > if you can tolerate inexact results. Some applications > can't. > > Even if you don't support arbitrary-size integers, you > should *not* automatically overflow from ints to floats. > You should raise an exception instead. That way, people > won't be bitten by unexpected loss of precision. I've agreed to support longs and I'm thinking of only having longs. From jdhunter at ace.bsd.uchicago.edu Sun May 9 12:52:26 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 09 May 2004 11:52:26 -0500 Subject: pycxx and multiple new types Message-ID: I have been using pycxx 5.2.2 to write an extension module which defines two new types, Point and Bbox. The Bbox is constructed with 2 Point instances class Point: public Py::PythonExtension ... class Bbox: public Py::PythonExtension { public: Bbox(Point& ll, Point& ur) : _ll(ll), _ur(ur) {}; static void init_type(void); // return lower left point Py::Object ll(const Py::Tuple &args) { return Py::Object(&_ll); } // return upper right point Py::Object ur(const Py::Tuple &args) { return Py::Object(&_ur); } private: Point& _ll, _ur; }; The problem I am having is that if I instantiate a Bbox from 2 point instances, my python test code hangs after the last line of the script and doesn't return the shell prompt until I hit CTRL-C. ll = Point(10, 10) ur = Point(20, 20) bbox = Bbox(ll, ur) # this line causes the hang. I think this is because I am not handling the ref count of the Point objects properly. My new_bbox function looks like Py::Object _transforms_module::new_bbox (const Py::Tuple &args) { args.verify_length(2); Point::check(args[0]); Point::check(args[1]); Point* ll = (Point*)(args[0].ptr()); Point* ur = (Point*)(args[1].ptr()); return Py::asObject(new Bbox(*ll, *ur) ); } Do you have any thoughts on what I am doing wrong? Thanks, John Hunter From info at armand.it Wed May 19 10:41:09 2004 From: info at armand.it (Armand Federico - INFO) Date: Wed, 19 May 2004 16:41:09 +0200 Subject: BANALE ma utile Message-ID: Devo scoprire se un elemento esiste in una lista Se metto confini.index(nomeelemento) mi da errore nel caso non esista e mi da l'indice nel caso esista Il mio problema ?: se l'elemento non esiste, devo fare la stessa cosa con un altro elemento. Come posso evitare l'errore??? *** Avevo provato con if confini.index(nomeelemento): return qualcosa else: continue *** Oppure con if confini.index(nomeelemento)>-1: return qualcosa else: continue Ma nel caso non venga trovato l'elemento da errore From mark at prothon.org Tue May 25 20:59:20 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 25 May 2004 17:59:20 -0700 Subject: Prothon vs. Python integers References: Message-ID: <%WRsc.18276$bF3.9891@fed1read01> Sion Arrowsmith wrote: > Mark Hahn wrote: >> No economy is ever going to to have a gdp of 10**19 pennies. > > Turkey's is around 10**18 lira (obtained from 2002 GDP in $ and > current exchange rate). You could argue that by the time they > hit 10**19 they'll have got EU membership and gone over to the > Euro.... > > (Japan's GDP appears to be around 10**16Y, BTW.) > > Given the number of times we see newbies confused by Python's > handling of floating points, it strikes me that silent conversion > of overflowing ints to doubles is asking for trouble somewhere > down the line, and should be avoided if possible. I've agreed to adding longs. I'm thinking of only having longs. From axium at axiumcomputerservices.com Mon May 10 15:48:24 2004 From: axium at axiumcomputerservices.com (Axium Computer Services) Date: Mon, 10 May 2004 14:48:24 -0500 Subject: Class update detection Message-ID: <109vn4b8bhe98f4@corp.supernews.com> I have a relational database that has several tables each more or less translating to a python class and the fields of each table translating into attributes of the python class. I have no problem creating an instance of the class, running a query and filling the attributes. Then this information will be accessible from a UI. The problem I am running into is when the user is done working in the UI I need to determine if any of the class attributes have been changed to I can issue an update query to the database with the changes. Is there a generally accepted method to do this? Is there some way to create a checksum of the class attributes? Any help would be much appreciated. Thanks Steven Potter From kirk at strauser.com Wed May 12 14:55:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Wed, 12 May 2004 18:55:06 GMT Subject: if Request("something") == None: doesn't work References: Message-ID: <87sme5v5q5.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-05-12T17:12:00Z, "Sam Sungshik Kong" writes: > if Request("something") == None: Have you tried: if Request("something") is None: > if str(Request("something")) == "None": Well, right. repr(None) == 'None'. > if len(Request("something")) == 0: > works! That seems kinda strange, granted. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAonJC5sRg+Y0CpvERAvRPAJ0Uojjx9qMtOHKApnDMnt3TxsL5ngCgnKWG ejWI7Ycj5asnK9WsoWL11Eo= =bL+r -----END PGP SIGNATURE----- From newsgroups at jhrothjr.com Fri May 21 16:46:17 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 21 May 2004 16:46:17 -0400 Subject: terminological obscurity References: <4Zsrc.528320$Pk3.64397@pd7tw1no> Message-ID: <10asqll7hiq9l48@news.supernews.com> "Elaine Jackson" wrote in message news:4Zsrc.528320$Pk3.64397 at pd7tw1no... > "Michael Chermside" wrote in message > news:mailman.145.1085158045.6949.python-list at python.org... > | Elaine Jackson writes: > | > All tuple methods are also list methods, and most list methods are also > tuple > | > methods; among those that are NOT also tuple methods, there are exactly two > | > ('count' and 'index') that do not involve mutation. Is there any special > | reason > | > why they AREN'T also tuple methods? > | > | Yes. Both make sense only if you consider a tuple as a homogeneous > | sequence of items, and that's not what Guido intended it to be > | used for. > > #################################################### > This invites the question: What DID he intend it to be used for? > Also, like the other respondent, I don't understand what homogeneity has to do > with it. > #################################################### This is one of the longstanding issues. Guido intended lists for conceptually homogeneous cases: that is, part of a list is conceptually similar to the entire list. Tuples are intended for places where you want to simply gather up a bunch of objects into one object for convenience in passing them around. Assume, for example, that I've got a tuple that includes a name, address, postal code, telephone number, part number and order quantity. Half of that tuple is not conceptually the same as the entire tuple. That's what is meant by inhomogenaity. There are a number of places where this gets sticky, and other people regard other properties as more important. It is, however, Guido's language. He's the Benevolant Dictator for Life, so his intention is the official intention. John Roth From k2mdfg at aol.com Sat May 8 09:09:36 2004 From: k2mdfg at aol.com (use dmgass at hotmail dot com) Date: 08 May 2004 13:09:36 GMT Subject: How do you register cleanup code to be run after script execution? Message-ID: <20040508090936.21319.00000994@mb-m04.aol.com> I'm writing a module and when it is imported by a script I want some code automatically executed when the importing script is finished executing. I'd like it to execute before interactive mode is entered when executing the importing script from the command line. I don't want to have to impose that the importing script must call a function at it's end. Any help is greatly appreciated!! From peter at engcorp.com Tue May 18 08:51:49 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 May 2004 08:51:49 -0400 Subject: python threads reading material In-Reply-To: References: Message-ID: <58Odnbl0kvd4mzfd4p2dnA@powergate.ca> Tarandeep wrote: > can anybody point me to some good and *detailed* explaination of python threads. If you didn't find what you wanted with Google (e.g. http://www.google.com/search?q=python+threads+tutorial ) please explain how the explanations were lacking and in what areas you wanted more detail. -Peter From tjreedy at udel.edu Fri May 21 18:11:33 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 18:11:33 -0400 Subject: Command Prompt References: Message-ID: "EAS" wrote in message news:Cnurc.5$hi6.3519 at attbi_s53... > Is there any way of using Python to open a command prompt? You may need to be more specific. On various versions of Windows, in batch or interactive mode, os.system('command.com') might or might not do what you want. On Win XP, interactive mode, one is already in a command window and the above gives a command prompt 'C:/Python...' in the same window, where one can do dir, cd, type, etc, and finally exit to return to Python and its prompt (again in the same window). Terry J. Reedy From peter at engcorp.com Mon May 3 10:40:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 10:40:48 -0400 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: References: Message-ID: <0MudnVoTELDrxAvdRVn-gw@powergate.ca> rzed wrote: > I have a similar configuration on my system, except that I have a > glut32.dll, and I have no problems running the demo. There are > evidently several glut32.dll versions around. That is evidently my problem as well, since after following Mike's advice about numarray, the error changed to telling me that I don't have OpenGL installed... which is at least true as far as glut32.dll missing... -Peter From user at example.net Sun May 23 11:48:22 2004 From: user at example.net (Bertrand B) Date: Sun, 23 May 2004 17:48:22 +0200 Subject: w9xpopen.exe and Drive A: Message-ID: lo' When i use os.popen on my W98SE I can hear my drive A: working. Sby know what ? (I've not A: in PATH all my os.environ seems clean and if one w9xpopen is running the second don't give me the same problem) Thank for help. From imbosol at aerojockey.invalid Tue May 11 03:14:32 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Tue, 11 May 2004 07:14:32 GMT Subject: efficient list reduction References: Message-ID: A B Carter wrote: > > > I have two lists. The values of the second list can be viewed as keys > for the first. I want to create a newlist based on the implied > mapping. The straight Python code would be: > > newlist=[] > for key in keys: > newlist.append(oldlist[key]) > > What's the most efficient way of doing this? The best I could do was > the following list comprehension: > > [oldlist[key] for key in keys] > > Have I missed something? newlist = map(oldlist.__getitem__,keys) Quite a bit faster for me. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From jacek.generowicz at cern.ch Thu May 27 03:37:08 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 27 May 2004 09:37:08 +0200 Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: Michael Hudson writes: > Jacek Generowicz writes: > > > Could we now just all agree, once and for all, that compiling > > dynamic languages to native binary really can give significant > > speedups? > > Has anyone really been arguing that? Ryan Paul writes in this very thread: > I dont understand why everybody seems to want a machinecode compiler. It > wont make a high-level, dynamically typed language run any faster. I guess there are different ways of interpreting the plethora of contributions such as the above. Maybe my I'm misunderstanding them. From whitney at battestilli.net Thu May 20 23:56:12 2004 From: whitney at battestilli.net (Whitney Battestilli) Date: Thu, 20 May 2004 23:56:12 -0400 Subject: How do I create a dynamic wrapper for another language? Message-ID: <1085111772.6438.620.camel@stella.fnord.you> I'm trying to embed python into an application that already contains a scripting language. This scripting language contains thousands of commands and I have the ability to query the script engine and get syntax information regarding valid arguments and such. Rather than writing explicate wrappers for each command (which will be very time consuming), I would like to extend python by creating a module that allows any function name to be executed with any number of keyword arguments. I would then like to take the function name and keyword arguments and pass these to the apps script engine in the format required. Is there any way to do this or any way to do something like this? Thanks in advance for any suggestions that may be offered. --Whitney. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From j.ezequiel at spitech.com Mon May 3 06:26:15 2004 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Mon, 3 May 2004 18:26:15 +0800 Subject: Difficulty Finding Python Developers Message-ID: <2484E6467140254CB22A328F5E18A23501802707@SPI-MAIL2003.SPITECH.COM> From: Bill Anderson [mailto:banderson at hp.com] >foo = re.compile(regex) >foo.findall(stringtosearchon,0,50)[-1] Where can I find documentation on the optional arguments to findall()? Have gone to http://python.org/doc/current/lib/module-re.html and did not find any mention of these. PythonWin 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32. From kkulak at shaw.ca Thu May 6 12:26:32 2004 From: kkulak at shaw.ca (Kim Kulak) Date: Thu, 06 May 2004 16:26:32 GMT Subject: prefix for installed scripts In-Reply-To: <930ba99a.0405060516.7304bc98@posting.google.com> References: <8Vemc.384062$oR5.32412@pd7tw3no> <930ba99a.0405060516.7304bc98@posting.google.com> Message-ID: Sridhar R wrote: >>My question is: how do I find where _my_ program was installed? > > > You can write code in setup.py that creates a directory.py (say) > file in $prefix/youapp/, which contains the `prefix` > Then you import that module and use `directory.prefix` to get your > installatino prefix. Yes, I think this is the way to do it. I was looking at the setup.py for gaphor last night and noticed that it did this. Now I just have to look deeper into how :-). >>Is anybody working on: "python setup.py uninstall" ? > > > Again the same trick, you can code that in setup.py. But a better > option is to install also a `uninstall.py` script, so that source > tarball is never needed after installation. Thanks. I'll remember this too, but it's not a priority right now. > Actually I am working on an IDE with all such project management > stuffs. Now this sounds interesting!!! Is it available someplace where I can have a look at it? I'm working on an IDE too. Give me another week to complete some cleanup and documentation and I'd be happy to send you what I have. Kim From skip at pobox.com Mon May 31 13:21:52 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 May 2004 12:21:52 -0500 Subject: a python script which will parse an email message In-Reply-To: <40BB4DA3.7010908@ntlworld.com> References: <40B691CD.1050002@ntlworld.com> <16566.38362.377082.903075@montanaro.dyndns.org> <40B86565.3050604@ntlworld.com> <16568.33181.243288.651167@montanaro.dyndns.org> <40BB4DA3.7010908@ntlworld.com> Message-ID: <16571.27056.369825.807034@montanaro.dyndns.org> chuck> Thus I home to get the body of the email messages as well using chuck> print >> output, msg['body'] Thus the None will hopefully contain chuck> Body Message Data. Nope, that's not how you get the message body. Read the docs for the email package: http://www.python.org/doc/current/lib/module-email.html In particular, check out the get_payload method of the email.Message module. The dictionary-style access is only for getting header values and returns None for missing headers. Skip From __peter__ at web.de Sun May 2 08:22:49 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2004 14:22:49 +0200 Subject: Help with ConfigParser References: Message-ID: Stephen Boulet wrote: > I'm having a bit of trouble getting my head around the ConfigParser > module. I have a very simple configuration file; maybe the easiest thing > to do would be to show that: > > ============ > # Add a local directory to be backed up followed > # by the directory name on the FTP server. > # > # Example: /home/joe/digital photos = photos > > [Backups] > /home/stephen/photos/digital camera = photos > /home/stephen/documents/tax documents = taxes Just the other way round: photos=/home/... > ============ > > I just want to retrieve the information in the backups section. Thanks. > A minimal example: from ConfigParser import ConfigParser CONFIG_FILE = "boulet.ini" # generate sample data f = file(CONFIG_FILE, "w") f.write(""" [Backups] photos=/home/stephen/photos/digital camera taxes=/home/stephen/documents/tax documents """) f.close() # retrieve configuration p = ConfigParser() p.read(CONFIG_FILE) # a single value print "Photos:", p.get("Backups", "photos") # a complete section print "Backups:" for key, value in p.items("Backups"): print "\t%r --> %r" % (key, value) Peter From rupole at hotmail.com Thu May 27 20:15:23 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 27 May 2004 20:15:23 -0400 Subject: send event from extension? References: Message-ID: <40b680c4_1@127.0.0.1> You could use win32event.CreateEvent and pass the handle into your extension, call SetEvent in the c code, and use win32event.WaitForSingleObject to wait for the signal. Alternately, you could create a named event and call OpenEvent to get a handle instead of passing it around. hth Roger "Markus von Ehr" wrote in message news:c957po$qrd$1 at news2.rz.uni-karlsruhe.de... > Hi everybody, > > I'd like to create an event which I have to post/set > within an extension (new frame signal from a camera). > In python I would like to react on this event. > How could I create and post the event in c and > how could I receive it in a python event handler > routine done with the win32event module? > > Thanks for any answer, > > Markus From aahz at pythoncraft.com Thu May 13 23:01:31 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 May 2004 23:01:31 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 References: <40a39511$0$560$e4fe514c@news.xs4all.nl> <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> Message-ID: In article <40a3b2f6$0$568$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: >Aahz wrote: >>Irmen deleted his own attribution: >>> >>>SimpleHTTPServer reports a wrong content-length of text files on >>>windows The bug is still there in this release. Any change of getting >>>my patch applied? >> >> Not at this point, sorry. It's generally assumed that people who care >> about the progress of release schedules are subscribed to python-dev; >> perhaps that assumption should be challenged. > >P.S. I don't really see why you mentioned python-dev, are you saying >that bugs and patches have more chance of being included in a new >Python version if the submitter is subscribed to python-dev and also >announces the bugs/patches there? Partly that but more that the impending release of 2.3.4 was announced on python-dev, which gave people an opportunity to lobby for specific patches to get in. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From alloydflanagan at comcast.net Tue May 25 12:58:20 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 25 May 2004 09:58:20 -0700 Subject: Solving the Einstein's Riddle in Python References: <40B22B86.152586E4@alcyone.com> Message-ID: Erik Max Francis wrote in message news:<40B22B86.152586E4 at alcyone.com>... > Juha Haataja wrote: > > > I managed to implement a Python code for solving the > > so-called Einstein's Riddle, ... > > Note that this riddle actually has nothing to do with Einstein. Actually you're just confusing your Einsteins. Note that the problem page states it was published early in the 19th century. This is because it had nothing to do with Albert Einstein, the disoverer of relativity. Actually it was created by Al Einstein, and he was really quite famous for it, until that Albert guy came along a century later. So then this new guy has a little theory or two, and suddenly everybody forgets about Al. Kind of a sad story, actually. From peter at engcorp.com Sat May 15 22:54:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 22:54:30 -0400 Subject: Stackless python and microthreads In-Reply-To: <87oeopl44w.fsf@vercingetorix.caesar.org> References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> Message-ID: Valentino wrote: > Hi Michele :). > > If all you need is s-expr you maybe can look at Nevow (pronounced > 'nuevo'), which is the new web toolkit built on top of twisted.web. Which raises the question, how do you pronounce "nuevo"? (Perhaps noo-VOH, as in the French nouveau?) -Peter From richardjones at optushome.com.au Mon May 17 17:39:58 2004 From: richardjones at optushome.com.au (richard) Date: Tue, 18 May 2004 07:39:58 +1000 Subject: Web testing framework? References: Message-ID: <40a9312e$0$3037$afc38c87@news.optusnet.com.au> Robb Shecter wrote: > Anybody know about a Python library for testing websites? http://www.python.org/pypi?:action=display&name=webunit&version=1.3.8 ''' Webunit is a framework for unit testing websites: - Browser-like page fetching including fetching the images and stylesheets needed for a page and following redirects - Cookies stored and trackable (all automatically handled) - HTTP, HTTPS, GET, POST, basic auth all handled, control over expected status codes, ... - DOM parsing of pages to retrieve and analyse structure, including simple form re-posting - Two-line page-fetch followed by form-submit possible, with error checking - Ability to register error page content across multiple tests - Uses python's standard unittest module as the underlying framework - May also be used to regression-test sites, or ensure their ongoing operation once in production (testing login processes work, etc.) ''' Richard From peter at engcorp.com Thu May 13 15:34:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 15:34:42 -0400 Subject: make faster Richards benchmark In-Reply-To: References: <6748553f.0405122211.5be5a150@posting.google.com> <6748553f.0405130815.4a69cc84@posting.google.com> Message-ID: Jack Diederich wrote: > On Thu, May 13, 2004 at 09:15:58AM -0700, Duncan Lissett wrote: >>The pointless set/get methods are pointless in the other language >>implementations as well - that's the point. > > I would leave python and some other languages out of the comparison. > You can do near line-for-line translations for languages in the same class > - say C++ and Java, or Assembly and C. Requiring the python/perl/ruby > versions to look like a C++ program just measures how badly C++ maps to > Python, and not much else. > > I've even seen some line-for-line translations in production use that > use python list-of-strings where the orignal version used char arrarys. > You can imagine what that does for performance *shudder*. > > Writing benchmarks is just hard, if you allow people to solve the problem > in whatever way they like you end up measuring how good a coder the > language A guy is compared to the language B submitter. In the case of the Richards benchmark, it's better to say "specifying benchmarks is hard". The problem that I saw with it is that it describes the problem in terms that are inappropriate for many of the languages it has been translated to, effectively constraining the implementation in ways that are more suitable to certain languages than others. One key example is the requirement for "global registers" which act similarly to how the low-level registers in the CPU have to be handled, specifically by saving and restoring them in a task-local context whenever a task switch occurs. This is clearly what Richards really wanted, but I'd argue that the approach is ill-conceived, especially in this century... On the other hand, if the specification had been more thoroughly thought out, or perhaps modernized is a more appropriate way of looking at it, then it would describe the expected *use and behaviour* of the tasks in terms of black box testability... in other words, it shouldn't matter that "global registers" are used, but merely that the benchmark produces certain results. Without those tests, it's fairly open to interpretation just how much deviation from the original BCPL implementation is appropriate. Duncan L's ideas for a generator-based approach are interesting, though there are probably those who would argue that it wouldn't follow the benchmark specs exactly. (Especially if it showed performance much closer to C. ) -Peter From myles at geocities.com Tue May 25 21:49:09 2004 From: myles at geocities.com (Myles) Date: 25 May 2004 18:49:09 -0700 Subject: how to terminate a process on win32? References: Message-ID: "Joe Wong" wrote in message news:... > os.popen2() to start my daemon, I can't figure out a way to stop it > 'nicely'... Is there anything that I can do? Mark Hammond's Python for Windows extensions includes a demonstration of killing processes on Windows: On my PC: C:\Python23\Lib\site-packages\win32\scripts\killProcName.py Python for Windows extensions: http://starship.python.net/crew/mhammond/ https://sourceforge.net/projects/pywin32/ Regards, Myles. From coder5811 at yahoo.com Thu May 6 14:13:48 2004 From: coder5811 at yahoo.com (Coder Coder) Date: 6 May 2004 11:13:48 -0700 Subject: call scp from python Message-ID: Hi How can scp a file from one computer to another using python? Thanks. From vonehr at ipm.fhg.de Fri May 28 09:17:37 2004 From: vonehr at ipm.fhg.de (Markus von Ehr) Date: Fri, 28 May 2004 15:17:37 +0200 Subject: send event from extension? In-Reply-To: <40b680c4_1@127.0.0.1> References: <40b680c4_1@127.0.0.1> Message-ID: <40B73BF1.8060905@ipm.fhg.de> Roger Upole schrieb: > You could use win32event.CreateEvent and pass the handle into your > extension, > call SetEvent in the c code, and use win32event.WaitForSingleObject to wait > for > the signal. Alternately, you could create a named event and call OpenEvent > to > get a handle instead of passing it around. > hth > Roger > > "Markus von Ehr" wrote in message > news:c957po$qrd$1 at news2.rz.uni-karlsruhe.de... > >>Hi everybody, >> >>I'd like to create an event which I have to post/set >>within an extension (new frame signal from a camera). >>In python I would like to react on this event. >>How could I create and post the event in c and >>how could I receive it in a python event handler >>routine done with the win32event module? >> >>Thanks for any answer, >> >>Markus Hi Roger, I don't know how to pass the handle. Is only the event.handle important? And how to wait for the event? Do I have to verify that the correct event fired my WaitForSingleObject? Can you help me? I do the following in my python code: import win32event . . . evt = win32event.CreateEvent(None, 0, 0, None) # pass event to c-extension cam_ext.SetEvent(evt.handle) # and wait for the event win32event.WaitForSingleObject(evt) ########################################### // c-extension int event; PyObject *cam_ext_SetEvent(PyObject *pSelf, PyObject *pArgs) { if (!PyArg_ParseTuple(pArgs, "i", &event)) return NULL; Py_INCREF(Py_None); return Py_None; } // Set the event ::SetEvent(event); Do you think it's correct? generally SetEvent needs an event object and not only a number? Thanks for hints, Markus From calvin at ironfroggy.com Sun May 30 07:23:35 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Sun, 30 May 2004 11:23:35 +0000 Subject: Prothon vs. Python integers References: <%WRsc.18276$bF3.9891@fed1read01> Message-ID: <4437220.utrTRUgGuI@ironfroggy.com> Marcin 'Qrczak' Kowalczyk wrote: > It's more efficient if ints which fit in a machine word (or a machine word > minus one or two bits used for tagging them as ints) are represented as > such, rather than using a generic big int representation. Seems like it should be possible to implement big numbers in a way that small numbers are nearly as, as, or more efficient than machine integers, when you take into account the overflow checking needed for regular integers in a language like python. From mcherm at mcherm.com Mon May 24 09:43:01 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Mon, 24 May 2004 06:43:01 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] Message-ID: <1085406181.40b1fbe56de0c@mcherm.com> gabor writes: > look...i am not asking for a way in python to COMPLETELY RESTRICT the > access to a variable... i hint is enough... now...if i know correctly > that means that i have to prefix my wanto-to-be-private variables with a > "_"... that restriction would be enough for me. my problem is with the > syntax. i HATE anything that even remotely resembles perl/hungarian > notation. [...] > the point is: > i only want to WRITE that the variable is private once... > i don't want to deal with _prefixed variables in my whole code... Sounds to me as if you are complaining about the poor quality of DOCUMENTATION for many Python programs. When using a class, the documentation ought to state which fields and methods are intended for "public" consumption, and which are intended only for "internal" use. Of course, using the "_" prefix convention is a perfectly valid way of documenting it, but a mention in the docstring would be OK as well. If you are using code which has neither, where the author does nothing to indicate how the class should be used, then that code's author needs to learn to document better. -- Michael Chermside From BruceWhoHKL at gawab.com Thu May 20 21:51:21 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Fri, 21 May 2004 09:51:21 +0800 Subject: how to keep one instance??? Message-ID: I'm using wxWidget to build an editor, so I need a cross-platform solution (at least it should work on windows & Linux). Yes,it does work ,if you use a file to lock. But I want the app behave like this : user click a .txt file, the the app runs and open the file, and later,if user click the same .txt file again, the app can detect the first app instance, and destruct, and popup the first instance to show the same .txt file. For example,you can not open the same .doc file in two MS Word windows. So, how can we get it ? Thanks. ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-21 From dmq at gain.com Fri May 21 20:55:22 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 21 May 2004 17:55:22 -0700 Subject: Unification of Methods and Functions References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> Message-ID: <879ta0132nm97hc9suesl48cqj6anblmj3@4ax.com> I've completed a revision of my OOP chapter. See Prototypes.doc at http://ece.arizona.edu/~edatools/Python The major change is adding some footnotes pointing out the limitations of Animals_2, and adding a section on Robust Programming, using your Animals_JM as an example. Comments are welcome. -- Dave From dmq at gain.com Tue May 25 07:02:36 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 04:02:36 -0700 Subject: Method binding confusion References: <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> Message-ID: <3r96b098d5ge6lnkobvpobpuumb0puljt5@4ax.com> Sorry for the double post. My newsreader ( Agent ) seems to be not threading properly on this thread, and it looked like the first post wasn't received. -- Dave From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Wed May 12 07:01:54 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Wed, 12 May 2004 13:01:54 +0200 Subject: Qt, multiple inheritance: QApplication and new-style class not possible Message-ID: <2geeh2F1vag1U1@uni-berlin.de> I want to try out several applications, all doing the same thing but using different GUI libraries (Tkinter, Qt, wxWindows). Using an example I found in a book I wrote a class containing the GUI independent methods of the application, let's call it MyAppClass. The book is written before Python 2.2, so it uses classic classes, but I want some properties, so I made MyAppClass a new style class. For the Tkinter GUI I derive another class, TkAppClass, from this, whose methods use Tkinter. As Qt applications need an application class derived from QApplication, I wanted to derive my QAppClass from both classes, QApplication and MyAppClass, but got a TypeError: "cannot create a class derived from a SIP generated class (QApplication) and a new-style class - use SIP v4 or later instead". Now I see three different ways out of this: a) use SIP v4, but it's pre-release. Moreover I'm just starting with Linux anyway, so I'd like to keep to ready-made rpm packages for my distribution (SuSE 9.1) and I can't find any. b) make MyAppClass a classic class. c) instead of deriving my QAppClass from QApplication and from MyAppClass, derive it only from QApplication and put a reference to a MyAppClass instance into it as an attribute. What's the best way (and why), or is there a d)? 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 python-url at phaseit.net Mon May 10 07:56:38 2004 From: python-url at phaseit.net (John J Lee) Date: Mon, 10 May 2004 11:56:38 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 10) Message-ID: <109urfm2arp1q98@corp.supernews.com> QOTW: "...simple genexps will work fine anyway almost all the time, so it doesn't appear to matter much that devious uses will have nightmarish semantics." -- Tim Peters on Generator Expressions "It looks like ... a developer's cookbook (eg. the O'Reilly Python cookbook) but with less Reilly and more "Oh?"." -- Paul Boddie, on the user-commented PHP documentation Andrew Bennetts discovers, without realising it, an obscure-but-useful detail of Python's argument passing rules: http://groups.google.com/groups?selm=mailman.262.1083743267.25742.python-list at python.org Thomas Heller explains how to get all your Python/win32 code working in debug mode: http://groups.google.com/groups?selm=mailman.349.1083956775.25742.python-list at python.org PEP 328 ('Imports: Multi-Line and Absolute/Relative') still isn't dead: http://groups.google.com/groups?selm=mailman.191.1083525640.25742.python-list at python.org http://www.python.org/peps/pep-0328.html Scott Archer and Uche Ogbuji rediscover the instability of Python client implementations of SOAP and WSDL: http://www-106.ibm.com/developerworks/webservices/library/ws-pyth17.html PyRapi 0.4 provides an improved, but still simple, Python interface to the libraries of the SynCE project http://synce.sourceforge.net/ PyZine upcoming articles: http://groups.google.com/groups?selm=mailman.1083816063.22766.clpa-moderators at python.org SciPy 2004 Conference - Python for Scientific Computing: http://groups.google.com/groups?selm=mailman.305.1083846542.25742.python-list at python.org Greg Ewing announces Pyrex 0.9.2 (quickly followed by 0.9.2.1): Flexible wrappers and extensions without the boring C code. http://groups.google.com/groups?selm=mailman.1083681543.24525.clpa-moderators at python.org http://groups.google.com/groups?selm=mailman.1083781203.18146.clpa-moderators at python.org http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Detleve Offenbach releases eric3 3.4.2, a Python IDE written in Python http://groups.google.com/groups?selm=mailman.1084027143.6394.clpa-moderators at python.org EuroPython is less than a month away. Many--but not all--talks have already been accepted. http://www.europython.org http://www.europython.org/conferences/epc2004/info/talks/acceptedTalksOverview ======================================================================== 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 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 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. *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 gael.pegliasco at free.fr Tue May 11 05:37:59 2004 From: gael.pegliasco at free.fr (gael.pegliasco at free.fr) Date: Tue, 11 May 2004 11:37:59 +0200 Subject: I'm looking for help with PyXML and XPath : simple Path expression seems to crash with brutality Message-ID: <40a09fb2$0$31940$626a14ce@news.free.fr> Hi, How are you dear and nice helper :) ? I'm trying to test xpath with this simple program : import xml.dom.minidom from xml.xpath.Context import Context import xml.xpath s = ''' Someroto text More text ''' d = xml.dom.minidom.parseString(s) result=xml.xpath.Evaluate( '//elem/test', d.documentElement ) for node in result: print node, node.nodeName But it crashed with the message below: -- -- Traceback (most recent call last): File "./xpath.py", line 12, in ? result=xml.xpath.Evaluate( '//elem/test', d.documentElement ) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/__init__.py", line 70, in Evaluate retval = parser.new().parse(expr).evaluate(con) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/ParsedAbbreviatedAbsoluteLocationPath.py", line 44, in evaluate sub_rt.extend(self._rel.select(context)) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/ParsedRelativeLocationPath.py", line 23, in evaluate raise Exception("Expected node set from relative expression. Got %s"%str(rt)) Exception: Expected node set from relative expression. Got () -- -- If I try with this syntax, its works : result=xml.xpath.Evaluate( 'descendant::elem/test', d.documentElement ) I have the same problem with more complex requests : Like "//DOC.PRINCIPAL//FILE/@VOL_PAGE_SEQ" that I must rewrite like "descendant::DOC.PRINCIPAL/descendant::FILE/@VOL_PAGE_SEQ" else it crashed with a different message : -- -- Traceback (most recent call last): File "/edika/vol1/users/gpegliasco/projets/dev/tools/src/xpathgrep.py", line 233, in ? searchInFile( file, searchedObject ) File "/edika/vol1/users/gpegliasco/projets/dev/tools/src/xpathgrep.py", line 77, in searchInFile listNodes = xpath.Evaluate( xpathquery, context=con ) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/__init__.py", line 70, in Evaluate retval = parser.new().parse(expr).evaluate(con) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/ParsedAbbreviatedAbsoluteLocationPath.py", line 44, in evaluate sub_rt.extend(self._rel.select(context)) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/ParsedRelativeLocationPath.py", line 21, in evaluate rt = self._left.select(context) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/ParsedAbbreviatedRelativeLocationPath.py", line 52, in evaluate res = Set.Union(res,subRt) File "/usr/local/lib/python2.3/site-packages/_xmlplus/xpath/Set.py", line 25, in Union return compare + filter(lambda x,compare = compare:x not in compare,loop) TypeError: can only concatenate list (not "tuple") to list -- -- Does someone know what's wrong with these requests ? Is it a bad use from me or a bug or something else with PyXML ? Thanks you very much for your help, With kind regards, Ga?l, From nhodgson at bigpond.net.au Tue May 25 17:44:23 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 25 May 2004 21:44:23 GMT Subject: popen and unicode References: <40b382d2$0$206$75868355@news.frii.net> Message-ID: Stuart McGraw: > Does os.popen() work with unicode strings containing characters outside > the ASCII range? (I think I answered my own question, above.) There is no Unicode support in the current implementation of popen. This could be added in a similar way to the Unicode file name support but it is more work than I currently have time for. If you are interested in fixing this, the code is in dist/src/Modules/posixmodule.c _PyPopenCreateProcess. > How can I call popen to process non-ascii filenames on a Windows box? > Is there anything else I could use (e.g. spawn) that will work with unicode > filnames? You can use ctypes to call the underlying platform APIs. Neil From iv at an.voras.fer.hr Thu May 27 11:39:33 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Thu, 27 May 2004 17:39:33 +0200 Subject: how to store binary file data to a database blob In-Reply-To: References: Message-ID: Benjamin Niemann wrote: > using the % operator. This works at least for arbitrary strings (and > that's the way to handle strings, if you don't like SQL injections ;) > But I never tried this with blobs - perhaps they need some special > treatment (thinking e.g. of laaarge files)... It is generally NOT a good idea to write large binary strings to a (sql relational) database, even if it has blobs. A much more robust (and faster) solution is to save general data about the blob in the database (its size, name, whatever, etc.) and the actual data in a separate file in the filesystem (or maybe in a "db" database (BDB, GDBM...), if you really like them). YMMV, mostly depending on the size of blobs. :) From dlissett0 at yahoo.com Thu May 13 12:33:00 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 13 May 2004 09:33:00 -0700 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> <873c64zpu7.fsf@blakie.riol> Message-ID: <6748553f.0405130833.2bf7d912@posting.google.com> Wilk wrote in message news:<873c64zpu7.fsf at blakie.riol>... > dlissett0 at yahoo.com (Duncan Lissett) writes: > > > I'd appreciate any suggestions on how to make faster Python > > implementations of Richards benchmark. Perhaps there are obvious > > problems that can be corrected? > > > > http://www.lissett.com/ben/bench1.htm > > import psyco > psyco.full() > > 2 times faster :-) And Simon: "I just tried the benchmark with Psyco, and cut the run time for input=10000 from 8.1 seconds to 3.4" Joseph, Simon, Wilk: thanks for the Psyco suggestion, and special thanks for going ahead and trying it - we get slightly better than x2. Given how little I know about Python, my assumption is that there's scope for x10 improvement by writing better code... a more Pythonic version for http://www.lissett.com/ben/bench3.htm Suggestions appreciated. best wishes, Duncan From arkon at ragestorm.net Sun May 2 17:02:05 2004 From: arkon at ragestorm.net (Arkon) Date: 2 May 2004 14:02:05 -0700 Subject: Embedded Python Tutorials Message-ID: Hello people, what's up? I'm not sure if this is the right place for my post... I wrote two tutorials while ago explaining thoroughly, in my opinion at least, how to embed Python in C applications, well the basics and some more. The reason I wrote them was because the lack of info about embedding Python in C applications, so I explored the subject and gathered info all over the Internet... First part: http://www.ragestorm.net/tutorial?id=21 Second part: http://www.ragestorm.net/tutorial?id=25 That's it, I hope it can help you somehow. I will be glad to receive any comments... Thanks, Arkon http://ragestorm.net/ From peter at engcorp.com Thu May 20 11:46:52 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 11:46:52 -0400 Subject: python hello.py hello_msg("Hello no", 3)??? Help, please! In-Reply-To: References: Message-ID: <1O-dnXbH1_NxTzHd4p2dnA@powergate.ca> Carl wrote: > This is perhaps a very simple and stupid question! > > How do you run a specific function (with actual values for the parameters) > within a module from the command prompt? That is, with "python ..." > > For instance, how do I run hello_msg("Hello no ", 3), which is a function > within the module hello.py, from the console? > > def hello_msg(msg, num): > print msg + str(num ** 3) +'!' > #hello_msg("Hello no ", 3) Use the -c option. python -c "import modulename; modulename.hello_msg('test', 5)" From randall at tnr.cc Fri May 21 20:26:43 2004 From: randall at tnr.cc (Randall Smith) Date: Fri, 21 May 2004 19:26:43 -0500 Subject: thread error when creating massive number of threads Message-ID: <87xrc.175082$f_5.151501@lakeread01> I was doing some testing with Python threads and found that when I try to create 300 threads one immediately after another, the 255th thread can't be created. The error message I get is: thread.error: can't start new thread When I put a pause between the creation of each thread of .1 second, I have the same problem. If I pause .2 seconds between creation of threads, no more problem. Why is this? If it helps, I'm using python 2.3.3 on Debian SID. Thanks. Randall From jjl at pobox.com Mon May 31 08:42:05 2004 From: jjl at pobox.com (John J. Lee) Date: 31 May 2004 13:42:05 +0100 Subject: http encodings References: Message-ID: <87u0xwbwf6.fsf@pobox.com> Manlio Perillo writes: > Hi. > RFC 2068 (Hypertext Transfer Protocol -- HTTP/1.1), introduces 4 > encoding names: > > identity > gzip (x-gzip) > compress (x-compress) > deflate [...] > Actually identity codec is banal. > -gzip: it is easy to implement using gzip module (I have written the > encode and decode methods, but it should be possible to write also > StreamWriter and StreamReader classes) Would be good to have these. Maybe this is useful: http://effbot.org/zone/consumer-gzip.htm > -deflate: codec is the same as zlib_codec? > > -compress: where can I find it? Dunno, but section 3.5 of RFC 2616 (the latest HTTP/1.1 RFC) certainly makes a distinction between the three encodings. John From shalabh at cafepy.com Mon May 31 13:28:57 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Mon, 31 May 2004 10:28:57 -0700 Subject: 2.2 <-> 2.3 surprise In-Reply-To: References: Message-ID: Roman Suzi wrote: > Hi! > > I really like python 2.3 but sometimes I write for 2.2 too. > > New cool feature of doing: > > f = open('file') > for line in f: > do_something(line) > > works strange in 2.2: I can't just quit first loop and do: > > for line in f: > do_some_more(line) > > (I as skipping message header by first loop and processing body > the the second). > > In 2.3 it works as intended! Of course, simple refacture made it one loop... > > > > Sincerely yours, Roman Suzi This is probably the following change as described in http://www.python.org/2.3/highlights.html "File objects are now their own iterators. This makes multiple interrupted iterations over the same file more reliable." Something that *might* work in both 2.2 and 2.3 using multiple loops is (not tested): f = iter(open('file')) ...and then use f as before. -- Shalabh From deetsNOSPAM at web.de Wed May 26 17:49:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 May 2004 23:49:08 +0200 Subject: Loggers and reloads References: <68fe96e8.0405261101.dd3cd14@posting.google.com> Message-ID: Francois Bouffard wrote: > The problem is that each time I reload my module, a new logger object > seems to be created, and the old one is not deleted. Both the new and > the old object are still working, so that each log message is > repeated; in general, if I did N reloads of my module, each message is > repeated N+1 times. The problem would disappear if you wrote a small testscript that uses your module and execeted that from scratch, instead of reloading the module - which might also create other state related problems. But if you insist on using your module, you could place the logger initialization into another module or encapsulate it in a function that you call manually - but only once. As the logging systems state is kept in the not-reloaded logging module, that should rid you of your problem. I bet it would also be possible to check if for a given logger already a handler is registered, and refuse to add another one. -- Regards, Diez B. Roggisch From irmen at -nospam-remove-this-xs4all.nl Mon May 24 16:27:18 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 24 May 2004 22:27:18 +0200 Subject: jython 2 cpython bridge In-Reply-To: <8dssc.179150$f_5.163363@lakeread01> References: <8dssc.179150$f_5.163363@lakeread01> Message-ID: <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> Randall Smith wrote: > I would like to use a type 4 JDBC driver in my Python program. I > believe I can use in with Jython. Do you know of some way to > communicate between the Jython and Python processes so that the CPython > program can use the Jython JDBC database connection? Create some form of IPC between the two, for instance using xmlrpc. --Irmen PS: I would have suggested to use Pyro, but: - Java/Jython doesn't have the select() system call that Pyro needs for a server, - There are bugs in Jython that make it crash when compiling Pyro's source. From bnet at ifrance.com Sun May 30 06:51:42 2004 From: bnet at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Sun, 30 May 2004 12:51:42 +0200 Subject: API : constness ? Message-ID: i don't understand why the ANSI const keyword is never used in the API. eg PyArg_ParseTuple( PyObject *args, char *format, ...) should be PyArg_ParseTuple( PyObject *args, const char *format, ...) or PyArg_ParseTuple( const PyObject *args, const char *format, ...) so i spend my time casting my format argument ... From rgacote at AppropriateSolutions.com Sat May 22 13:09:46 2004 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Sat, 22 May 2004 13:09:46 -0400 Subject: Server/OS/Dev environment In-Reply-To: References: Message-ID: >Hi. I am new to Python, but very eager to learn. Welcome! > I've browsed many >postings and found conflicting opinions on the best backend and >development setup. In fact, I am more confused now that when I first >began investigating this problem. Languages, text editors, mail clients..., it all comes down to personal preferences and precisely what you need to do. Probably need to look around at a variety of tools. >I need to create web pages with MySQL as the primary data source. >What would be the best server set up for this? RH? Windows? >mod_python? Spyce? Some other templating mechanism? I found it easy to get started with Snakelets and CherryPy These are easy to install and get started with. I'm also a fairly newbie Python programmer and simply did not have the time to wrap my thoughts around large environments like Twisted or Zope. Snakelets and CherryPy were a good start for me. Python and MySQL run just about anywhere so the 'best' platform is probably whatever you have in front of you. For myself, my development platform tends to be Mac OS X with the BBEdit text editor. Deployment tends to be on variants of Linux, BSD, Mac OS X, and Windows. Databases tend to be: Oracle, Firebird, PostgreSQL, and MySQL. --Ray -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From simoninusa2001 at yahoo.co.uk Wed May 19 13:35:50 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 19 May 2004 10:35:50 -0700 Subject: drag drop from linux to a wxpython application References: <40ab3ae7$0$21248$636a15ce@news.free.fr> Message-ID: <30260531.0405190935.6c171a@posting.google.com> marco wrote in message news:<40ab3ae7$0$21248$636a15ce at news.free.fr>... > I've got a wxpython application > and when i drag'n' drop files from(linux) rox/nautilus/konqueror to my app > i've got strange chars in filenames (on win32 : it works well) > > example: > - my dir "my photos" will become "/home/marc/my%20photos" > - a dir "f?tes ? strass" will become (something like this) > "/home/marc/f%A8%CFtes%20%8F%AC%20strass" This is URL encoding. Basically because the use of top-bit-set characters and spaces in filenames is evil. Don't forget that most file managers are basically web browsers.... You'd need to URL decode the chars to get your original filename as on Windows, try: import urllib print urllib.unquote_plus("f%A8%CFtes%20%8F%AC%20strass") That will fix your %xx characters, although I don't get the same encoding as you're getting there (maybe it's a unicode thing?): print urllib.quote("f?tes ? strass") f%EAtes%20%E0%20strass From berra at psyket.com Fri May 28 08:33:02 2004 From: berra at psyket.com (Per Erik Stendahl) Date: Fri, 28 May 2004 14:33:02 +0200 Subject: r'\' - python parser bug? In-Reply-To: <8089854e.0405260632.2f4367fc@posting.google.com> References: <8089854e.0405252339.18e0c59d@posting.google.com> <8089854e.0405260632.2f4367fc@posting.google.com> Message-ID: <40B7317E.5010806@psyket.com> Fuzzyman wrote: [snip] > Yeah.. that's not an annoying feature.... I mean no-one would ever > want to use strings to hold Windows pathnames in...... So I guess I'm not the only one who tries to use a special class for paths as much as possible then? ;-) Working with pathnames as strings is painful, IMHO. Using objects makes it much clearer, for me anyway. path = Path(r'C:\documents\my\file.txt') if path.isfile(): shutil.copyfile(path.get(), ....) print path.dir() other_path = path.parent() / 'subdir' / 'otherfile' + '.txt' ... Regards, Per Erik Stendahl From tzot at sil-tec.gr Tue May 11 09:08:20 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 11 May 2004 16:08:20 +0300 Subject: OT: Idea for Python T-shirt Message-ID: (Don't mind me, my frequent late night "I should be sleeping by now" brainstorm) A python smiling, its body curled in the background, 1's and 0's visible in its body visibly grouped in fours, and below the slogan: "With Python your nibbles explode with desire" I'll do one for myself :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From NOSPAM at easyconnect.fr Mon May 17 05:57:10 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Mon, 17 May 2004 11:57:10 +0200 Subject: NIC adress of incoming socket. References: <40a4f772$0$2280$afc38c87@news.easynet.fr> <40a5e12e$0$2277$afc38c87@news.easynet.fr> Message-ID: <40a88d6b$0$2279$afc38c87@news.easynet.fr> "Peter Hansen" a ?crit dans le message de news:CpSdnTXrVp3AljvdRVn-sw at powergate.ca... > RosalieM wrote: > > > I saw in dhcpd config for bootp that you give the adress of the nic. How > > can i be sure that in my lan it is the right computer (my dhcp server) that > > answers to my client and not another compromised machine ? Can i ask python > > some information from ethernet level in an ip connection? > > Basically, no. Use external utilities to solve whatever the > problem is. I'd suggest that if you might have compromised > machines on your own LAN which are answering in place of your > real DHCP server, you have rather big problems to solve, and > you'd be best involving a network administrator with a good > understanding of security issues. > > -Peter I saw that this could be a security issue. So i would like to prevent it. And i would like to be able to do what dhcpd and tftp are able to do, to say check the nic before sending files. But I wanted to write this program in python as i found in google a dhcpd program writen in python. You mean that python cant do it ? I read that python can do everything possible. From Christian.Gudrian at gmx.de Wed May 26 16:12:35 2004 From: Christian.Gudrian at gmx.de (Christian Gudrian) Date: Wed, 26 May 2004 22:12:35 +0200 Subject: prefix matching References: Message-ID: "Jeff Epler" wrote: > def startswith_one(s, prefixes): > for p in prefixes: > if s.startswith(p): return True > return False Thanks! startswith sounds good. > If speed is important and "prefixes" doesn't change frequently, then > coding a FSM in C is the way to go. The prefixes don't change very often but can be configured by the user. So a FSM is not the preferred approach here I think. And speed does not really matter. Christian From jeremy at jdyallop.freeserve.co.uk Wed May 12 12:43:30 2004 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 12 May 2004 16:43:30 GMT Subject: newb: object factory, and iteration References: <939f49f8.0405120822.7a22e1b6@posting.google.com> Message-ID: Chris wrote: > But is there a way for me to list all instances of a certain > class? I don't think there is, in general. If, as in your example, you can modify the __init__ method of the class, you could add weak references to created instances to a class member list. It would be even nicer, though, to make a metaclass, instances of which maintain (weak) references to instances of themselves. Jeremy. From russelllear at earthlink.net Mon May 24 23:43:38 2004 From: russelllear at earthlink.net (Russell Lear) Date: Tue, 25 May 2004 03:43:38 GMT Subject: par files? Message-ID: In java there are .jar files so I'm wondering if Python has anything similar - .par files perhaps? I know jar files have their limitations and shortcomings, but being able to bundle together a bunch of related python files with various resource files seems like a handy thing to have. Thanks, Russell. From andrew-pythonlist at puzzling.org Thu May 13 01:36:04 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 15:36:04 +1000 Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> Message-ID: <20040513053604.GB20388@frobozz> On Thu, May 13, 2004 at 05:19:56AM +0000, john fabiani wrote: > Peter Hansen wrote: > >john fabiani wrote: > > > >>I'm guessing but I bet that simple text can be sent to a printer using > >>Python (looping of course). But in today's world most users want > >>graphics along with the data. Like an invoice with a logo, boxes > >>around the bill to and ship to, along with column lines. So I'm > >>hoping that someone has at least started a project to print reports. > > > > > >That would be "ReportLab", I would think... Google for it. > > > >-Peter > I book marked it - but it looks like a web solution?????? Not at all. It's a python library that can generate PDFs for you -- it's very well suited to making things like pretty invoices. I've used it to do exactly that in one of my past jobs. -Andrew. From jepler at unpythonic.net Sat May 15 18:20:27 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 17:20:27 -0500 Subject: Good programming site In-Reply-To: References: Message-ID: <20040515222027.GE2832@unpythonic.net> On Sat, May 15, 2004 at 10:01:57PM +0000, EAS wrote: > http://www.coderforums.com > > Has forums for all the big languages, would be a lot better if there were > more people. I'll take usenet/mailing list over a "forum" any day, thank you very much. There are remarkably few banner ads, misspelled words, and ugly "smilies" here in my mail client. (okay, maybe there are more than a few misspelled words) Jeff From dmq at gain.com Wed May 12 14:45:43 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 12 May 2004 11:45:43 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> Message-ID: On 10 May 2004 16:53:06 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: < snip topics we have finished > >You are not solving a problem; that's the problem. :) If there were a >real programming task then it would be more trivial to show why your >object model is broken. I could give you an example from IC Design, but for the course I teach, I chose to use a similar hierarchy based on something everyone would understand - a taxonomy of animals. Nothing in this example is something you wouldn't find in a real program to model an integrated circuit. Instead of animal names like Cat, we would have the names of cells in the hierarchy, names like bgref25a. Instead of a variable to count the number of animals at each level, we might have several variables to track the total current on each of several supply lines. Like the counts in the Animals.py hierarchy, we need the total current to each cell, including all of its subcells. I'm sure there are other examples from other specialties. In accounting, I can imagine a hierarchy of accounts, with a total for each account including all of its subaccounts. Don't just assume that the problem isn't real because you haven't encountered it in your work. >If you can't take it below 70 pages and you only have 4 hours... maybe >it's not such a great idea to try this? I can't see your students >benefiting from what you're proposing to do, if you have so little >time. I think I could do it in 30 pages and 4 hours total ( lecture, lab, and homework ), but not if I need to cover the topics that both Mark Lutz and I consider important to basic OOP in the current version of Python. The 30 pages assumes the unification of methods and functions that I have proposed. >> >> >OK: "The whole idea of having these structures in any program is >> >> >wrong." >> >> > >> >> >Firstly, the program uses a class hierarchy as a data structure. That >> >> >isn't what class heirarchies are designed for, and not how they should >> >> >be used IMO. But it's what any bright student will pick up from the >> >> >example. >> >> >> >> The classes contain both data and functions. The data is specific to >> >> each class. I even show an example of where the two-class first >> >> example forced us to put some data at an inappropriate level, but with >> >> a four class hierarchy, we can put each data item right where it >> >> belongs. >> >> >> > >> >The data is not specific to the class. It's specific to the class and >> >it's subclasses. Subclasses should be dependent on the superclass, >> >and generally not the other way around. >> >> What data are we talking about? numMammals is specific to Mammal. >> genus is specific to Feline, but *inherited* by instances of a >> subclass like Cat. > >The numAnimals etc... data, which is stored in Animals but gets >arbitrarily altered by the actions of subclasses of Animal, and >therefore is not specific to animal; it doesn't represent the state of >the Animal class or of Animal objects, but of a whole bunch of >subclasses of Animal. The total current to an IC is the sum of the currents to all of its subcircuits. That current is a single number, for example, 35 microamps. It has a name "Iss". Iss is a characteristic of the IC which appears in data sheets, etc. It is a variable representing the state of the entire IC. It does not represent the state of any subcircuit in the IC, even though it gets "altered" whenever one of those subcircuit currents changes. Looks like this whole argument comes down to what we mean by the word "specific". Let's drop it and focus on the more interesting topics in this thread. >> >> Nothing in the Bovine class can affect anything in a Cat. Feline and >> >> Bovine are independent branches below Mammal. Adding a Mouse class >> >> anywhere other than in the chain Cat - Feline - Mammal - Animal cannot >> >> affect Cat. Could you give a specific example? >> >> >> > >> >Say someone adds a mouse class but doesn't call the constructor for >> >Mammal. The data produced by mammal and therefore cat is now >> >incorrect, as instances of mouse are not included in your count. In a >> >real example, anything might be hanging on that variable - so e.g. >> >someone adds some mouse instances and the program crashes with an >> >array index out of bounds (or whatever the Pythonic equivalent is :) ) >> >, or maybe we just get bad user output. This type of behaviour is >> >damn-near impossible to debug in a complex program, because you didn't >> >change anything which could have caused it. It's caused by what you >> >didn't do. >> >> These are normal programming errors that can occur in any program, no >> matter how well structured. I don't see how the specific structure of >> Animals.py encourages these errors. > >Imagine if your structure had been implemented as one of the basic >structures of, say, Java. That is, some static data in the Object >class stores state for all the subclasses of Object. Now, someone >coming along and innocently creating a class can break Object - >meaning that may break anything with a dependency on Object, which is >the entire system. So I write a nice GUI widget and bang! by some >bizzare twist it breaks my program somewhere else because of an error >in, say, the StringBuffer class. This is analagous to what you are >implementing here. I'll need an example to see how these general worries can affect the Animals_2 hierarchy. What I see is quite robust. I added a Feline class between Mammal and Cat, and I had to change only two lines in the Cat class. ( And I could avoid even that if I had used a "super" call instead of a direct call to the Mammal functions.) >While errors are always going to happen, OOP calls on some conventions >to minimize them. The most absolutely vital of these is that it's >clear what can break what. Generally I should never be able to break >a subsystem by breaking it's wrapper; definitely I should never be >able to break a superclass by breaking it's subclass; and I >*certainly* shouldn't be able to break a part of the system by >changing something unconnected to it. The whole of OOP derives, more >or less directly, from these principles. Expressions like 'A is a >part/type of B' derive from this philosophy, not the other way around. Sounds good. >Your program breaks with this concept. It allows an event in Cat to >affect data in Mammal and in Animal, which also has knock-on effects >for every other subclass of these. Therefore it is bad object >oriented programming. We are modeling the real world here. When you add a lion to a zoo, you add one to the count of all animals. When you add 2 microamps to the core currents in a bandgap voltage reference, you add that same 2 microamps to the total supply current. I'm no expert in OOP, but what I have seen so far is not near as clear in structure as the origninal Animals_2 example. >It takes us back to the days before even structured programming, when >no-one ever had any idea what the effects of altering or adding a >piece of code would be. > >It is therefore not a good teaching example. :) I'll need to see something better before I abandon the curent example. The problem may be our expectations of OOP. I see classes as modeling the real world, including variables that are altered by changes in subclasses. You seem to have some computer science notion of what a class should be. I'm not saying its wrong, but unless it helps me solve my real-world problems, in a better way than what I am doing now, I won't use it. I'm reminded of the criticism Linus Torvalds got when he first published Linux. The academic community thought it was the worst, most fundamentally flawed design they had ever seen. It did not fit some expectation they had that a "microkernel" architecture was the proper way to design an OS. Luckily, Mr. Torvalds was not dependent on their approval, and had the confidence to move ahead. >> >> I'm not sure what you mean by "side effects" here. The show() >> >> function at each level is completely independent of the show() >> >> function at another level. > >> > >> >But the inventory data isn't independent. It's affected by classes >> >somewhere else in the heirarchy. Worse, it's done implicitly. >> >> The "inventory data" actually consists of independent pieces of data >> from each class. ( numCats is a piece of inventory data from the Cat >> class.) I'm sorry I just can't follow this. >> > >numMammals OTOH is not just a piece of data from one class - it's a >piece of data stored in one class, but which stores data about events >in many different classes, all of which are outside it's scope. Exactly as we see in objects in the real world. >> >> Chaining them together results in a >> >> sequence of calls, and a sequence of outputs that is exactly what we >> >> want. The nice thing about separating the total "show" functionality >> >> into parts specific to each class is that when we add a class in the >> >> middle, as I did with Feline, inserted between Mammal and Cat, it is >> >> real easy to change the Cat class to accomodate the insertion. >> >> >> >> Python has a 'super' function to facilitate this kind of chaining. >> >> Michele Simionato's 'prototype.py' module makes 'super' even easier to >> >> use. Instead of having Cat.show() call Mammal.show() I can now just >> >> say super.show() and it will automatically call the show() function >> >> from whatever class is the current parent. Then when I add a Feline >> >> class between Mammal and Cat, I don't even need to change the >> >> internals of Cat. >> > >> >That's fine - providing you're not using a class heirarchy to store >> >data. It's not the act of calling a method in a super-class which is >> >a bad idea, it's the way you are making *the numbers outputted* from >> >cat dependent of actions taken *or not taken* in another class >> >*completely outside cat's scope*. >> >> Seems like this is the way it has to be if you want to increment the >> counts for Cat and all its ancestors whenever you create a new >> instance of Cat. Again, I'm not understanding the problem you are >> seeing. You seem to be saying there should be only methods, not data, >> stored in each class. >> > >That's the way it has to be, if you want to write it like that. >However there is nothing to say that a given problem must use a >certain class structure. If you come up with a solution like this >then it's near-guaranteed that there was something badly wrong with >the way you modelled the domain. Either the program shouldn't need to >know the number of instances which ever existed of subclasses of >mammal or else your class structure is wrong. Trust me, the need is real. We just need to find the optimum example to show how Python solves the problem. In my work as a software product engineer, I've learned to deal with two very common criticisms. 1) The user doesn't need to do that. 2) The user is an idiot for not understanding our wonderful methodology. These are generally irrefutable arguments that can only be trumped by a customer with a big checkbook. I generally don't engage in these arguments, but on one occasion, I couldn't resist. I was trying to show an expert how a complicated feature could be done much more easily with simpler functions we already had in our program. His argument was basically -- every expert in this company disagrees with you, and you're an idiot for not understanding how our new feature works. I replied that I was the one who wrote the User Guide on that feature. He started to say something, but it was only a fragment of a word, and it kind of fell on the table and died. There was a few seconds of silence, while he tried to figure out if he could call me a liar. I just looked right at him without blinking. Forget what you have learned in books. Think of a real zoo. Think how you would write the simplest possible program to do what Animals_2 does -- keep track of all the different classes of animals, and display the characteristics of any animal or class, including characteristics that are shared by all animals in a larger grouping. >And, as general rule, you should think carefully before using classes >to store data; that's typically what objects are for. I used static >data in programs quite a lot before I realised that it too-often bit >me later on. Classes *are* objects. I think you mean instances. I make a distinction between class variables and instance variables, depending on whether the variable is different from one instance to another. Every instance has a different cat.name, but all cats share the genus "feline". In fact, they share that genus with all other members of the Feline class. That is why I moved it from Cat to Feline as soon as our example was big enough to include a Feline class. >> >> In one syntax we need special "static methods" to handle calls where a >> >> specific instance is not available, or not appropriate. In another >> >> syntax we can do the same thing with one universal function form. >> >> To try and get to the bottom of this, I re-wrote the Animals.py >> example, following what I think are your recommendations on moving the >> static methods to module-level functions. I did not move the data out >> of the classes, because that makes no sense to me at all. >> > >*Sigh* No, I must say that doesn't help much. :-\ > >As I said, there is something wrong with the whole idea behind it; the >design needs refactoring, not individual lines of code. > >Having said that, I'll try to redact the issues as best I can, on the >basis that it may illustrate what I mean. > >OK: start with the basics. We need iterative counting data about the >individual elements of the heirarchy. > >The first thing is that we need to factor out the print statements. >Your back-end data manipulation modules should never have UI elements >in them. So, whatever form the data manipulation comes in, it should >be abstract. You are adding requirements to what I already have. OK if it doesn't slow the introductory presentation too much. >Secondly, we want to keep the data stored in each class local to that >class. So, Mammal can store the number of Mammals, if that turns out >to be a good solution, but not the number of it's subclasses. OTOH we >could remove the data from the classes altogether. Think of a real zoo. If you ask the zookeeper how many animals he has, will he tell you only the number that are animals, but are not also lions or tigers or any other species? That number would be zero. I really do want numMammals to display the total number of all mammals, whether or not they are a member of some other class in addition to Mammal. If I were to guess at your objection to this, I would assume you are worried that the different counters will get "out-of-sync", if for example, someone directly changes one of these variables, rather than calling the appropriate functions to make a synchronized change. My answer to that is to make the counter variables private. I've added a leading underscore to those names. numMammals is now _numMammals. >Thirdly, it would probably be nice if we had the ability to implement >the whole thing in multiple independant systems. Currently the design >only allows one of "whatever-we're-doing" at a time, which is almost >certainly bad. ??? >After a bit of brainstorming this is what I came up with. It's not a >specific solution to your problem; instead it's a general one. The >following class may be sub-classed and an entire class-heirarchy can >be placed inside it. It will then generate automatically the code to >keep a track of and count the elements of the class heirarchy, >returning the data you want at a method call. > >This is done with a standard OO tool, the Decorator pattern, but >ramped up with the awesome power of the Python class system. :) My non-CIS students are not familiar with the Decorator pattern. I fear that will make this example incomprehesible to them. >class Collective: > class base: pass > > def startup(self, coll, root): > #wrapper class to count creations of classes > self.root = root > class wrapper: > def __init__(self, name, c): > self.mycount = 0 > self.c = c > self.name = name > def __call__(self, *arg): > tmp = self.c(*arg) > self.mycount += 1 > return self.c(*arg) > self.wrapper = wrapper > #replace every class derived from root with a wrapper > #plus build a table of the > self.wrap_list = [] > for name, elem in coll.__dict__.items(): > try: > if issubclass(elem, self.root): > tmp = wrapper(name, elem) > self.__dict__[name] = tmp > self.wrap_list.append(tmp) > except: pass > > #when subclassing, override this > #call startup with the class name > #and the root of the class heirarchy > def __init__(self): > self.startup(Collective, self.base) > > #here's the stuff to do the counting > #this could be much faster with marginally more work > #exercise for the reader... ;) > > def get_counts(self, klass): > counts = [ (x.c, (self.get_sub_count(x), x.name)) \ > for x in self.super_classes(klass) ] > counts.append( (klass.c, (self.get_sub_count(klass), >klass.name)) ) > counts.sort(lambda x, y: issubclass(x[0], y[0])) > return [x[-1] for x in counts] > > def get_sub_count(self, klass): > count = klass.mycount > for sub in self.sub_classes(klass): > count += sub.mycount > return count > def super_classes(self, klass): > return [x for x in self.wrap_list if issubclass(klass.c, x.c) >\ > and not x.c is klass.c] > def sub_classes(self, klass): > return [x for x in self.wrap_list if issubclass(x.c, klass.c) >\ > and not x.c is klass.c] > >So we can now do: > >class animal_farm(Collective): > class Animal: pass > class Mammal(Animal): pass > class Bovine(Mammal): pass > class Feline(Mammal): pass > class Cat(Feline): pass > def __init__(self): > self.startup(animal_farm, self.Animal) > > >a_farm = animal_farm() >cat = a_farm.Cat() >feline = a_farm.Mammal() >print a_farm.get_counts(a_farm.Feline) > >>>> [(2, 'Animal'), (2, 'Mammal'), (1, 'Feline')] > > >The above code is 51 lines with about 10 lines of comments. For a >project of any size, this is a heck of an investment; I believe it >would take a fairly determined idiot to break the system, and *most >importantly*, they would be able to trace back the cause from the >effect fairly easily. This is an impressive bit of coding, but I can assure you, as an introduction to OOP, it will blow away any non-CIS student. It may also be difficult to modify, for example, if we want to do what Animals_2 does, and provide a custom display of characteristics for each class. One possibility is to make this an Animals_3 example. Animals_1 was a simple two-class structure. It served to introduce instance variables, and some basic concepts like inheritance. When we moved to Animals_2, we pointed out the limitations of Animals_1, like not having enough classes to put variables like 'genus' where they really belong. Maybe we should go one more step, and make this a third example. We can point out the limitations of Animals_2 in the introduction to Animals_3. I can see the benefit of moving the print statements to the top level. This is needed if we ever want to make the classes in Animals_2 work in some kind of framework with other classes. The show() functions in Animals_2 could be modified to return a list of strings instead of printing directly to the console. I've posted your program as Solution 3 to the exercise at http://ece.arizona.edu/~edatools/Python/Exercises/ Could you give us a brief description of the advantages and disadvantages compared to the original. I'm not able to do that, because I'm having difficulty restating what you have said above in terms that students will understand. I cannot, for example, explain why your solution is more robust. >Admittedly the solution is on the complicated side, though perhaps >someone with more experience than me could simplify things. >Unfortunately, a certain amount of complexity is just a reflection of >the fact that your demands strain the OO paradigm right to it's limit. > You could possibly implement the same thing in Java with a Factory >pattern, and perhaps the reflection API. Your vast experience may be blinding you to the problems non-CIS students will have with these more complex solutions. I may be pushing a paradigm to some limit, but these are real-world problems that should be easily solved with a good OOP language. -- Dave >(Of course I'm none too sure I could do that after many years of >hacking Java vs a few weeks of Python!) > > >> Take a look at http://ece.arizona.edu/~edatools/Python/Exercises/ and >> let me know if Animals_2b.py is what you had in mind. If not, can you >> edit it to show me what you mean? >> >> -- Dave From sholden at holdenweb.com Fri May 28 08:22:12 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 May 2004 08:22:12 -0400 Subject: terminological obscurity In-Reply-To: References: <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: Donn Cave wrote: > In article <1l25b0damv22nmja2na0i3k55e0p3jsef4 at 4ax.com>, > Arthur wrote: > ... > >>Well for one, before new style classes, it was easier to think of an >>"instance" as in some sense a pseudo data type. Instances of >>different classes - even with no hierarchical relationship - were more >>conceptually homogenous. >> >>But with everything subclassable, 2 different classes, each derived >>from object, are conceptually distinguished more similarly to the way >>in which a str and int are distinguished. > > > Really makes no difference at all - not just insignificant, > really _no_ difference. A truly heterogeneous sequence may > be full of references to the _same_ object (e.g., (1, 1, 1)), > and a truly homogeneous sequence may have objects as different > as None and a module. It's not about properties of the objects, > considered in isolation. > Absolutely. See below. > >> GvR> I always think of the type of a list as "list of T" while I >> GvR> think of a tuple's type as "tuple of length N with items of >> GvR> types T1, T2, T3, ..., TN". So [1, 2] and [1, 2, 3] are both >> GvR> "list of int" (and "list of Number" and "list of Object", of >> GvR> course) while ("hello", 42) is a "2-tuple with items str and >> GvR> int" and (42, "hello", 3.14) is a "3-tuple with items int, >> GvR> str, float". >> >>He sort of stacks the cards by making his tuples of hetereogenous >>type, and his list easily described as a list of T. And thereby >>sidesteps all the ambiguities inherent in the ten word edict. Except >>that at the Object level, we are at lists of Objects and tuples of >>Objects. It detracts little from the point of the above quote, but >>this quote then becomes substantially weaker as support for his 10 >>worder. While Arthur is possibly correct in the sense that "I can't argue with that", he's also correct in the sense that "English and Python are both languages". > > > Guess he may have overestimated his audience. > More likely he was speaking to a specific question, and is now being taken out of context. > If you're interested in the history of this matter, it may > help to know that Guido did not invent the tuple. It has > been around in computer programming languages since Lisp. > You can actually find precisely parallel descriptions of > the concept in that context, down to the unnecessary use > of different data types to emphasize the heterogeneity. > Furthermore, all such implementations are probably based on the tuple as used by mathematicians since God was a lad. A tuple is an ORDERED collection of items, not necessarily of the same type. The important thing about a mathematical tuple is that it is constructed so that the position of an element in the tuple signifies its purpose. The important thrust of this apparently endless discussion is to highlight the possible need for some way *other than indexing* to get information out of a tuple. Really, most places where tuples are used, a programmer might find it more convenient to extract the elements as attributes - by name rather than position - hence the changes to the os.path.stat() return value in version 2.2. People got tired of accessing the individual values by using the appropriate index. I'm guessing (though in this forum I am likely to be proved wrong at some length) that most uses of tuples could senibly be replaced by simple "bunch"-type objects in the Alex Martelli sense: >>> class bunch: ... def __init__(self, **kw): ... self.__dict__.update(kw) ... >>> a = bunch(my=0, word=1) >>> a.word 1 >>> However it's a bit late to start insisting on this usage when the tuple has been embedded in the language so long. The thing that ticks me off is when I come across a module that INSISTS I provide a tuple, when really a list would be perfectly adequate. This often happens in database munging applications: retrieving data yields a tuple (perfectly appropriate, as each column is potentially of its own type). To add further information I have to convert this tuple to a list and modify it. Can I write this list out using the DBAPI interface? Well, usually I first have to convert it to a tuple, because most database modules require a tuple. Frankly I wish they'd be a bit less picky, and do the conversion themselves if they must. Obviously it would also be helpful if DB values were accessible by attribute name. The problem wtih that is one can't always guarantee that SQL will name things in Python-compatible ways. For some reason, it seems that database deigners (though probably the ones who exclusively use GUIs) have a penchant for weird characters like spaces and pound signs in their column names. Don't get me started ... > Lisp and its relatives have both a tuple and a list type, > but the list is a `real list', not a 1-dimension array as > in Python but a recursive data structure. In Python, this > data structure can be represented using a tuple: > > t = (0, None) > t = (1, t) > t = (2, t) > ... > def print_list(tail): > value, tail = tail > if tail: > print_list(tail) > print value > > Guido's "mistake" is that unification of all these sequence > types leaves the distinctions less obvious. > While it's interesting for us all to discuss how many objects can dance on the head of a pin, however, it probably won't be profitable. The bottom line, for pragmatists, is that you can do 'most anything with a list that you can with a tuple EXCEPT use it as a dictionary key. Just as some people will do integer arithmetic using floating point numbers, so some people will use lists where tuples might be more appropriate. Just as (sometimes) floating-point's inaccuracies will bite the careless user in the ass, so (sometimes) will inappropriate use of lists (though much less frequently). regards Steve From danb_83 at yahoo.com Thu May 27 21:26:23 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 27 May 2004 18:26:23 -0700 Subject: Can someone help me with this bug? References: Message-ID: "Duncan Smith" wrote in message news:... > Hello, > I'm probably missing something that should be obvious, but can > anyone tell me what's wrong with the following? > > temp.py > --------------------------------------------------------------------- > > class Item(object): > def __init__(self, id, data): > self.id = id > self.data = data > > class KeyedSet(dict): > def __init__(self, items=None): > if items is not None: > for item in items: > self[item.id] = item > def __iter__(self): > return self.itervalues() > def __repr__(self): > return '%s(%r)' % (self.__class__.__name__, self.keys()) > def __contains__(self, item): > return self.has_key(item.id) > def intersection(self, other): > res = self.__class__() > for item in self: > if item in other: > res[item.id] = item > return res > def __and__(self, other): > return self.intersection(other) > def intersection_update(self, other): > self &= other > def __iand__(self, other): > self = self.intersection(other) > return self > -------------------------------------------------------------------- > > >>> from temp import Item, KeyedSet > >>> a = Item(0, 'W') > >>> b = Item(1, 'X') > >>> c = Item(2, 'Y') > >>> d = Item(3, 'Z') > >>> aset = KeyedSet([a, b, c]) > >>> bset = KeyedSet([b, c, d]) > >>> aset &= bset > >>> aset > KeyedSet([1, 2]) > >>> aset = KeyedSet([a, b, c]) > >>> aset.intersection_update(bset) > >>> aset > KeyedSet([0, 1, 2]) > >>> > > I can't figure out why 'aset' is unchanged? Thanks. Your __iand__ method doesn't work the way that you think it does. Remember, "self" is just another local variable name, so your function works as if you had done: def __iand__(self, other): x = self.intersection(other) return x which (incorrectly) has the same effect as __and__. From Chris.Hornberger at blackrock.com Fri May 14 14:55:25 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Fri, 14 May 2004 14:55:25 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: > >WINDOWS >... Windows users may also be >interested in Mark Hammond's win32all, a collection of >Windows-specific extensions including COM support and Pythonwin, an >IDE built using Windows components. > PS... I have moral and ethical arguments against this. I believe it's just plain WRONG to use a language like Python or Java or even C#/.NET and RELY on platform specific "extensions". If it ain't cross platform, then it's VB. $.02/MHO From manju.george at hantzsoft.com Mon May 24 02:43:40 2004 From: manju.george at hantzsoft.com (manju) Date: Mon, 24 May 2004 12:13:40 +0530 Subject: EnumObjects Error Message-ID: <000501c4415a$76fcaf30$c500a8c0@hantz.com> Hi all, When I am trying to discover a Win XP resource for Performance Data Collection , using win32pdh.EnumObjects() function call, I got the following error :I specified the IP address of the remote XP system. pywintypes.error: (-1073738789, 'EnumObjects for buffer size', 'No error message is available') While I am able to discover a Win 2003 resource for Performance Data Collection with the same function. I suppose there is some problem with Win XP security.The Authentication level has to be set to PKT. Please give some suggestions Manju From grante at visi.com Mon May 24 11:14:32 2004 From: grante at visi.com (Grant Edwards) Date: 24 May 2004 15:14:32 GMT Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> Message-ID: On 2004-05-23, Arthur wrote: > Lists are for [...] data that under some cricumstance might be > sensibly used in a list. :) My amusement at the above statement aside, I think I do get it now: Tuples are for when you should have used a structure with symbolically named fields. -- Grant Edwards grante Yow! In Newark the at laundromats are open 24 visi.com hours a day! From andrew-pythonlist at puzzling.org Thu May 13 04:37:11 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 18:37:11 +1000 Subject: things I wish python could do In-Reply-To: References: Message-ID: <20040513083711.GG20388@frobozz> On Thu, May 13, 2004 at 10:07:19AM +0200, Jacek Generowicz wrote: [...] > > > I want a way to extend a class as easily as I can define it. > > You can. There is one syntax for creating new classes, and another for > mutating existing ones. Ruby conflates the two. > > I think that what you "want" is to cleate new classes and mutate > existing ones using the same syntax. Perhaps you should question > whether you really want that. > > Maybe there's a satisfactory solution based on the decorators that are > being proposed in PEP 318: > > class Shape [update]: > def triangle(self, sideLength): > ... Or there's the evil solution, available right now: http://www.intarweb.us:8080/evil/reopenable.py -Andrew. From __peter__ at web.de Thu May 20 12:52:30 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 May 2004 18:52:30 +0200 Subject: "Extracting" a dictionary References: <5fd6ba56.0405200818.60b0259@posting.google.com> Message-ID: Noldoaran wrote: > Arnold Filip: >> How about this: >> >> In [1]: d = {'foo' : 23, 'bar' : 42} >> >> In [2]: for item in d.items(): >> ...: exec "%s = %d" % item >> ...: >> >> In [3]: foo >> Out[3]: 23 >> >> In [4]: bar >> Out[4]: 42 > > you could extract them in to there own namespace: >>>> class AttrDict: > ... def __init__(self, d): > ... self.__d = d > ... def __getattr__(self,attr): > ... return self.__d[attr] > ... def __setattr__(self,attr,value): > ... self.__d[attr] = value > ... def __delattr__(self,attr): > ... del self.__d[attr] > ... >>>> d = AttrDict({'foo' : 23, 'bar' : 42}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __init__ > File "", line 10, in __setattr__ > (snip) > RuntimeError: maximum recursion depth exceeded >>>> d.foo > > That didn't work like I hoped. I decided to share it anyway in case > someone can get it to work. Saying self.__d = dont_care invokes __setattr__() to set __d, __setattr__() asks __getattr__() for __d, which asks __getattr__() for __d to determine __d ...ad infinitum. To avoid the recursion you must bypass __setattr__() by accessing __dict__ directly (and do some name mangling due to the evil double-underscore attribute name by hand): >>> class AttrDict: ... def __init__(self, d): ... self.__dict__["_AttrDict__d"] = d ... def __getattr__(self, attr): ... return self.__d[attr] ... def __setattr__(self, attr, value): ... self.__d[attr] = value ... def __delattr__(self, attr): ... del self.__d[attr] ... >>> d = AttrDict({'foo': 23, 'bar': 42}) >>> d.foo 23 >>> d.baz = 123 >>> d.foo = 456 >>> d.__d Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getattr__ KeyError: '__d' >>> d.AttrDict__d Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __getattr__ KeyError: 'AttrDict__d' >>> d._AttrDict__d {'baz': 123, 'foo': 456, 'bar': 42} >>> While this works, you can achieve the same functionality in a more elegant way: >>> class AttrDict: ... def __init__(self, d): ... self.__dict__.update(d) ... >>> d = AttrDict({"foo": 23, "bar": 42}) >>> d.bar 42 >>> d.foo *= 2 >>> d.__dict__ {'foo': 46, 'bar': 42} >>> del d.foo >>> d.__dict__ {'bar': 42} >>> A standard trick, by the way. Can't think of the right google keywords right now, so I use another standard trick and leave finding them as an excercise to the reader :-) Peter From __peter__ at web.de Mon May 3 06:12:01 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2004 12:12:01 +0200 Subject: Method binding confusion References: Message-ID: Eric Brunel wrote: > I can reproduce the OP's behaviour with old-style classes in Python 2.1.1: Me too, with new-style classes in Python 2.3.3: import math #import myModule def mypow(x, y): return "%s ** %s" % (x, y) class Klass(object): def doOperation(self, x, y): return self.operator(x, y) class KlassMath(Klass): operator = math.pow class KlassMyModule(Klass): operator = mypow #myModule.pow km = KlassMath() kmy = KlassMyModule() print km.doOperation(2,4) print kmy.doOperation(2,4) Running the above: $ python -V Python 2.3.3 $ python kmy.py 16.0 Traceback (most recent call last): File "kmy.py", line 21, in ? print kmy.doOperation(2,4) File "kmy.py", line 9, in doOperation return self.operator(x, y) TypeError: mypow() takes exactly 2 arguments (3 given) > I also cannot understand the difference between C1 and C2: math.pow and > myPow are both functions with two parameters, so why does the first work > and not the second? Or was it an "unwanted feature" that was removed in a > later version? > > I also have some difficulty to understand the "automatic addition of self" > you mention. In what case is it needed? I would have sworn the two classes > worked... >>> class A: ... pass ... >>> def method(*args): ... print args ... >>> A.m = method >>> >>> A().m(1,2) (<__main__.A instance at 0x40296bac>, 1, 2) See? Although defined outside the class, method() is called with 3 parameters. *I* could have sworn that _that_ would always happen. But: >>> import math >>> A.m = math.pow >>> A().m(1,2) 1.0 >>> Now I am as confused as you and the OP :-( Peter From donn at drizzle.com Tue May 25 19:18:41 2004 From: donn at drizzle.com (Donn Cave) Date: Tue, 25 May 2004 23:18:41 -0000 Subject: avoid stderr output References: None <47c46d82.0405251328.7dfe84be@posting.google.com> Message-ID: <1085527117.968399@yasure> Quoth giorgenes at terra.com.br (Gi?rgenes): ... | When I use, for example, PyRun_File to run a script and an error | occur, the error is sent to stderr. | What can I do to avoid it? To cleanly capture the error w/out it | beeing sent to stderr. I think you are talking about the top-level exception handler. One simple way to do it, if this works for you, is to execute your own Python program instead, passing the intended script and arguments as command line parameters to it. Your Python program can run the script in a try: block intercepting any possible error. I haven't actually done this myself. Donn Cave, donn at drizzle.com From ville at spammers.com Sat May 22 07:21:23 2004 From: ville at spammers.com (Ville Vainio) Date: 22 May 2004 14:21:23 +0300 Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: >>>>> "Mel" == Mel Wilson writes: Mel> The best solution would be for somebody to volunteer to Mel> write a program that would take Python source, marked up Mel> with block brackets (perhaps '##{' and '##}', perhaps not) Mel> and create properly indented Python. If you volunteered for It already exists in Python - it's the Tools/Scripts/pindent.py script. Here's the copy-pastage of the way code is written, for those who don't care enough to check: def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar -- Ville Vainio http://tinyurl.com/2prnb From arsenal_hl at yahoo.com.hk Thu May 27 05:15:28 2004 From: arsenal_hl at yahoo.com.hk (Arsenal) Date: 27 May 2004 02:15:28 -0700 Subject: wxpython moved? Message-ID: its official site www.wxpython.org has been dead for some time... was it moved? From peter.maas at mplusr.de Thu May 6 06:29:59 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 06 May 2004 12:29:59 +0200 Subject: classes vs dicts In-Reply-To: References: Message-ID: Charlie wrote: > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? Use a class to model address data, advantage is that you can define methods operating on address data, subclass address etc. A dictionary gives you fast access to data by key. You could create a dictionary of adresses that maps keys to addresses. You can store such a dictionary with shelve module functions. Easy to handle and sufficient if you don't need multi user access, an SQL interface or have huge amount of data. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From rick.ratzel at scd.magma-da.com Sat May 22 15:23:48 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Sat, 22 May 2004 19:23:48 GMT Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> Message-ID: <40AFA804.70602@scd.magma-da.com> How about this: >>> import re >>> for line in open( "inputFile", "r" ).readlines(): ... print re.split( "\s+", line.strip() ) ... ['Name:', 'Date:', 'Time:', 'Company:', 'Employee', 'Number:'] ['Jim', '2.03.04', '12:00', 'JimEnt', '4'] ['Steve', '3.04.32', '03:00', 'SteveEnt', '5'] >>> -Rick Ratzel Uri wrote: > I have a file that looks like this: (but longer, no wordwrap) > > Name: Date: Time: Company: Employee Number: > Jim 2.03.04 12:00 JimEnt 4 > Steve 3.04.32 03:00 SteveEnt 5 > > I want to load 'Jim' and '12:00' and those types of answers into > variables in my program, the only delimiter in the file is whitespace. > How do I do this? > > I can do it with string.split(" ",[0]) type line for a file that's > only delimited by single spaces, but when I'm searching for white > space, how do I do it? > > THanks! From mwh at python.net Thu May 27 09:29:44 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 27 May 2004 13:29:44 GMT Subject: Compiling python without garbage collector References: Message-ID: Boris Boutillier writes: > Is there a not too hackish way to compile Python without the garbage > collector overhead ? No, in short. The difficulties are in the trashcan mechanism that safely deallocates deeply nested structures, so maybe if you disable *that* as well... Cheers, mwh -- Get out your salt shakers folks, this one's going to take more than one grain. -- Ator in an Ars Technica news item From p_s_oberoi at hotmail.com Wed May 5 20:38:12 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Wed, 05 May 2004 19:38:12 -0500 Subject: doctest: address in output References: Message-ID: > >> > >>> mymodule.do_something() > >> > > > Param> The return value of the function is designed to be ignored in > Param> normal use. > > Then make it return None and use a different function on those presumably > rare occasions where you need it. I may realize later that the interface is inappropriate; but I don't want to change it because of what the testing framework wants. (Yes, difficulty in testing often hints at problems in the code, but in this particular case I think the problem is in the testing framework) > Maybe not if the "test" part of "doctest" is more important than the "doc" > part. I started writing it as documentation, and then realized that it could be made to do double duty for testing. And, it could be checked automatically so that it didn't become inaccurate. Anyway, the patch I posted works for me. It could be made more robust and/or general in case other people are interested. -param From kkto at csis.hku.hk Thu May 20 11:11:35 2004 From: kkto at csis.hku.hk (Isaac To) Date: Thu, 20 May 2004 23:11:35 +0800 Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: <7izn83jfq0.fsf@enark.csis.hku.hk> >>>>> "Andrei" == Andrei Smirnov writes: Andrei> Please, Python writers, do provide braces as compatibility mode. Andrei> Give the chance to the world! If you think that the designer who is proud of eliminating the braces in the language is any easier to change than your boss, you're deadly mistaken about the reasons why people are writing open-source software. Regards, Isaac. From pete at shinners.org Mon May 24 11:21:17 2004 From: pete at shinners.org (Pete Shinners) Date: Mon, 24 May 2004 08:21:17 -0700 Subject: Pygame classes and files In-Reply-To: <9125a2e9.0405231913.7d8e40f@posting.google.com> References: <9125a2e9.0405231913.7d8e40f@posting.google.com> Message-ID: Nickchch wrote: > I am a newbie to pygame !! Be sure to use the over 10 tutorials and many examples included with the pygame documentation to get started. A lot of people jump right into the reference docs, which aren't verbose enough to get you started. From __peter__ at web.de Thu May 6 13:05:31 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 19:05:31 +0200 Subject: AttributeError: 'function' object has no attribute 'split' References: <11e5f362.0405060845.16fff0f8@posting.google.com> Message-ID: Earl wrote: > PathList= string.split(FullPath, "/") is generating the above error > message. when I run my script, but works just fine from the python > command line! What gives? Either the FullPath is not a string: >>> import string >>> string.split(1, "/") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'int' object has no attribute 'split' Or you are using 'string' as a variable name: >>> string = None >>> string.split("abc/def", "/") Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'split' Peter From rogerb at rogerbinns.com Thu May 6 20:38:59 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 6 May 2004 17:38:59 -0700 Subject: How to get Hostname using SimpleXMLRPCServer References: Message-ID: <1e2rm1-unk.ln1@home.rogerbinns.com> Golawala, Moiz M (GE Infrastructure) wrote: > I figured it out. I realized that in the SimpleXMLRPCRequestHandler there is a doPost method which is inherited from > BaseHTTPRequestHandler. In the doPost method you can simply ask the self.header for the host variable (clientName = > self.host["host"]) and you get the client that is invoking the call to the server. Actually that header is what the client thinks the server is called. It is used when you use virtual servers. Think of an ISP that hosts many sites off the same machine. The web server examines the Host header to see which server's content to serve up. (In the olden days you would have to make one server IP address per web site!) Technically the Host header is part of HTTP/1.1 but most web browsers specify it (even when speaking HTTP/1.0). I don't know if XML-RPC clients are required to specify the Host header, but you will probably find in practise that most do. Roger From godoy at ieee.org Tue May 25 20:50:10 2004 From: godoy at ieee.org (Jorge Godoy) Date: Tue, 25 May 2004 21:50:10 -0300 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: On Ter 25 Mai 2004 21:43, SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since a > strength of Python is rapid application development, it slows one down > to have to put in all those self.'s. The code seems much cleaner to me > without classes that have only one instance. Oh, also, all the methods > of this class will have to have the instance name prepended to them. > > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. How can you guarantee that such a code will never ever be used again, anywhere? It's easier to allow for code reuse from the beginning, IMHO. -- Godoy. From fumanchu at amor.org Thu May 6 02:54:30 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 5 May 2004 23:54:30 -0700 Subject: What does 'is' do? Message-ID: Derek Fountain wrote: > I recently saw a use of 'is' in a piece of Python code. I was > trying to find > out what it does. I can't find it in the online docs. I have > the "Python in > a Nutshell" book and that mentions it as a keyword, but I can't find a > description of it in there either. It's not in the index. > > Can someone tell me where to look? It's mentioned briefly in both the Library Reference: http://docs.python.org/lib/comparisons.html and in the Language Reference: http://docs.python.org/ref/comparisons.html ...you really should read: http://www.python.org/doc/current/ref/objects.html Robert Brewer MIS Amor Ministries fumanchu at amor.org From segphault at sbcglobal.net Tue May 25 17:47:06 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Tue, 25 May 2004 21:47:06 GMT Subject: alter / modify a list as well as iterate on its items / objects References: Message-ID: On Tue, 25 May 2004 12:57:32 -0700, Derek Basch wrote: > Hello, > > Can anyone point me towards an article or explain > how to properly alter a list as well as iterate > on its items? For example: > > input: > > word = ["albert", "likes", "surfing!"] > > for word in sentence: > word += "foo" > > result: > > word = ["albertfoo", "likesfoo", "surfingfoo"] > word = ["albert","likes","surfing!"] you could do it with a map: word = map(lambda x: x + "foo", words) or with a list comprehension: word = [x + "foo" for x in words] From rogerb at rogerbinns.com Mon May 3 20:04:20 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 3 May 2004 17:04:20 -0700 Subject: Tkinter and XML-RPC References: <0jZjc.65$pw1.70887@news.uswest.net> Message-ID: Etienne Posthumus wrote: > That is a good tip, very interesting. Do you mind explaining what you > did further? My program (bitpim) manipulates the phonebook, wallpaper, ringtones etc for US based CDMA cellphones (they behave very differently than GSM phones used in the rest of the world :-). I wanted the ability to have the program and the phone on different machines, including over the Internet (which would make development easier). I wanted to use XML-RPC to remote the various methods used when talking to a port (open, close, read, write) as well as some others I have (list available devices, read until certain criteria are met). (Using XML-RPC meant I didn't have to reinvent the wheel). I wrote a program (named BitFling) that listens (by default on all interfaces) for incoming connections and obeys commands sent by XML-RPC. The BitPim program then makes a connection to this and issues commands. Behind the scenes, everything is wrapped in classes in BitPim so it can't tell the difference between a local or remote port, and really doesn't need to care. For this solution I obvious required security. I use certificates (self signed) for BitFling with access granted using username and password combinations. (You also have to list valid source addresses). You have to rework the existing XML-RPC client and server classes to add the HTTP authentication. I then wrapped it all in SSL using M2Crypto. Unfortunately the existing XML-RPC stuff goes out of its way to do one transaction per connection. Additionally M2Crypto doesn't implement the makefile method, which internal has the same effects as a dup. I tried pretty hard to rework the code to not rely on dup, not close connections etc, but never could get everywhere. Fortunately I found Paramiko and it was really easy to switch to that. I didn't both with the HTTP layer and just send the raw output of the XML-RPC encoding. SSH defines authentication up front, rather than on every transaction like in HTTP. It also has the idea of multiple named channels. So I just use a channel named "bitfling" and use regular old SSH password authentication. > Nie to know about Paramiko, it looks a little more lightweight than the > SSH that comes with Twisted, if one does not want to go the whole > Twisted route. I really don't like Twisted anyway. My code naturally is threaded as the device access doesn't have the equivlent of polling methods. In theory I could run a background thread that updates something else that emulates polling, but I far prefer to just directly write the code I want executed rather than the Twisted approach of giving a list of what will be executed. > Curious how much it could be sped up by using OpenSSL > for the crypto operation in stead of PyCrypto. You do know that pyCrypto uses native code? Paramiko is all Python however. Consequently I don't think there will be much performance difference between the two. Paramiko itself is being repeatedly improved and I think that will give the biggest performance improvements. Roger From dpharris76 at msn.com Tue May 25 23:09:36 2004 From: dpharris76 at msn.com (Dave Harris) Date: Tue, 25 May 2004 22:09:36 -0500 Subject: Why a class when there will only be one instance? Message-ID: Mitchell Timin wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since a > strength of Python is rapid application development, it slows one down > to have to put in all those self.'s. The code seems much cleaner to me > without classes that have only one instance. Oh, also, all the methods > of this class will have to have the instance name prepended to them. > > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. I may very well be the person prompting this question -- Mitchell has been reviewing some Python code I wrote. As a matter of fact, I asked myself the same question, wondering if I was slavishly using a technique that obfuscates the code. In particular (and this may remind list readers of an embarrassing recent post by me), I have a window with multiple Frames. Two of the frames, CourseView(Tk.Frame) and DetailView(Tk.Frame) contain independent Canvas objects. The views have different origins and I found it very convenient to set up instance variables named xoffset and yyoffset for coordinate translations. The names are meaningful (to me) and serve the same purpose in each Canvas. This seems minor, but the idea extends to other orthogonal relationships. The most likely non-class alternative leads to longer function names which slow down comprehension and inflate the namespace. For example, instead of: courseView = CourseView(frame) courseView.pack() detailView = DetailView(frame) courseView.pack() courseView.drawAll() detailView.drawAll() I might have to resort to: courseView = Frame(frame) courseView.pack() courseView.canvas = Canvas(courseView) courseView.canvas.pack() detailView = Frame(frame) detailView.pack() detailView.canvas = Canvas(detailView) detailView.canvas.pack() drawAllCourseView(courseView) drawAllDetailView(detailView) (I'm almost positive I made this look as bad as I possibly could. Another embarrassment?) What I decided I like about the class arrangement is the data hiding that makes the application conceptually simpler. I cannot (at the moment) envision re-use, but I've been wrong about that in my C career more times than I can count. Sorry about the length, Dave Harris From mday at apple.com Fri May 14 19:13:36 2004 From: mday at apple.com (Mark Day) Date: Fri, 14 May 2004 16:13:36 -0700 Subject: how to run an arbitrary function with timeout? References: <2004051413541084557280@k2.sage.att.com> Message-ID: <140520041613369125%mday@apple.com> In article <2004051413541084557280 at k2.sage.att.com>, Garry Hodgson wrote: > i would like a function RunWithTimeout( func, args, timeout ) > i would like it to invoke the function func on arguments args. > if timeout seconds elapse before func(args) returns, i would > like it to raise an exception. if func(args) returns before timeout > seconds, i would like it return the result. I'm guessing you want the exception raised after func has executed for timeout seconds (as opposed to waiting for func to complete). Since you can't stop func from the outside (as Tim said), I suppose you could run func in a separate thread. From the original thread, you'd have to wait for either timeout seconds or until func completes, whichever comes first. If the timeout happened first, then raise the exception (else you presumably return func's result). I'm no expert on threading in Python, but I'll bet the Library Reference has the information you need. -Mark From tjreedy at udel.edu Mon May 10 21:03:39 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2004 21:03:39 -0400 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: "Wolfgang Buechel" wrote in message news:4629559b.0405101330.286ddb32 at posting.google.com... > Hi, > > I want to iterate over all 2x2 matrices with elements in range 0..25 > (crypto-stuff). > > To produce them, first I wrote a fourfold nested for loop: > > M=26 > for a in range(M): > for b in range (M): > for c in range (M): > for d in range (M): > matr = [[a,b],[c,d]] > (dosomething) This is completely clear and space efficient. > Then I had a look in comp.lang.python and found: Oh dear... > for (a,b,c,d) in [(x,y,z,t) for x in range(M) > for y in range(M) > for z in range(M) > for t in range(M)] : > matr = [[a,b],[c,d]] This is less clear. It took me about 10 seconds (versus 1) to see as equivalent. It produces a list with M**4 elements that you don't actually need and soon throw away. > Is there a shorter (and probably, with respect to exec time, faster) > way to write such a 4for loop? Write a C extension, maybe with Pyrex. However, an hour of your time is worth lots of hours of PC time. But for a million runs, it might be worth it. Terry J. Reedy From has.temp2 at virgin.net Sat May 1 11:44:19 2004 From: has.temp2 at virgin.net (has) Date: 1 May 2004 08:44:19 -0700 Subject: What is good about Prothon? References: <108t2tlo06j8vb9@corp.supernews.com> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <69cbbef2.0404291609.72d391db@posting.google.com> <69cbbef2.0404300855.4dce5e5@posting.google.com> Message-ID: <69cbbef2.0405010744.32e4cb9a@posting.google.com> "Mark Hahn" wrote in message news:... > Donn Cave wrote: > > > He's saying `language that tries to please everybody [by adding > > features like copy instead of doing it right in the first place] == > > C++' He could have a point. (Is there going to be an optional > > __copy__ method?) > > Yes, there already is a copy method. It solves the problem he posted of AS > versus Prothon. One: No, it does not. But it does prove _just how little_ of what I've said you have actually understood. Two: BTW, learn to differentiate between "ludicrous" and "hyperbole". They are _not_ the same. Three: You I was just giving you a hard time for the sake of it? I wasn't; you asked for criticism, and I gave it. It just wasn't the criticism you wanted. You want to hear what I say when asked to critique something I think is a piece of piss but simply don't care about enough to say? "Yes, that looks very nice/interesting. I'll be very curious/interested to see how where it goes." Four: You think it's just you? Obviously you've never seen me chewing AppleScript a new one; it's such a fundamentally flawed language that I'm now actually working actively against it. (MacPython-to-AEM bridge, more hours spent critiquing and reading and learning than I can shake a stick in, mystery language project in development; hey, you do the math.) Five: You think I don't give my own work this treatment? Obviously you have never seen me spend weeks or months working at something, only to throw it out the moment I've uncovered a flaw too deep or uneconomic to fix, or simply discover a new and much simpler way to solve the same problem, and take all that blood-sweat-and-tears effort and postmortem then shitcan the lot of it without a second thought. So if your only reaction to hard criticism is to run away or barricade your mind to it, if you're not willing to make such sacrifices in the name of the greater good, if you're not willing to at least entertain the possibility that You Might Be Wrong Too; then I'm sorry to say but you really have chosen the wrong line of work to get into, and I can find much better things to devote all my attention to. Six: As for what will make me happy? That I never again hear that bloody Lieberman name used to deflect every criticism I offer. Because that is so intellectually lazy of you it's actually insulting mine. I have provided you with plenty of answers throughout; you simply choose not to notice or accept them. And that is something I absolutely _cannot_ help you on. Therefore, I am finally willing to state: "Prothon looks very nice/interesting. I'll be very curious/interested to see how where it goes." May you find some fulfillment in that. has From lbates at swamisoft.com Wed May 26 13:27:31 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 26 May 2004 12:27:31 -0500 Subject: creating .exe file References: <3f0686ff.0405260841.6deba711@posting.google.com> Message-ID: As others have stated, py2exe creates a .EXE file consisting of all of your code. External .pyd files (including python itself) are left as external files. I use InnoSetup to create a single "installation" .EXE file for distribution but it installs all the files necessary for program execution separately. Doesn't seem to be a problem to me as almost all programs require that you have additional files beyond the .EXE file itself. You can use getopt to pick up any command line arguments but syntax would be: pythonprogram.exe -c d:/temp -f c:/hi.text or pythonprogram.exe --classpath d:/temp --file c:/hi.text (actually you can support both in a single program) And yes all of this is FREE!!!! HTH, Larry Bates Syscon, Inc. "Q X" wrote in message news:3f0686ff.0405260841.6deba711 at posting.google.com... > Hello everyone, > > I am wondering what kind of tools are available to wrap python scripts > into just 1 .exe file (with no other files) in windows. I also want > the .exe file to be able to use command line arguments ie. > pythonprogram.exe -classpath d:/temp -file c:/hi.text > > Also, is this possible to do this free ie. without a commercial > compiler like Visual Studios? > > Help is greatly appreciated. > > Thanks!!!! From peter at engcorp.com Tue May 18 10:44:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 May 2004 10:44:25 -0400 Subject: So what's a "pythong"? (was Re: Python/C++ Developers required for consulting position in Brooklyn, NY) In-Reply-To: References: Message-ID: > We are looking for several contractors with very strong C++ and > Pythong development skills. "Pythong"... now there's a scary image. :-) Ouch! -Peter From jfabiani at yolo.com Mon May 17 11:24:21 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 17 May 2004 15:24:21 GMT Subject: module for working with the result set Message-ID: Hi, newbie question: PyPgSQL (postgres driver) returns a list (not a tuple O'Rielly states DBAPI returns a tuple) and most of the books describe how to work with tuples and dictionaries when working with a result set. Does anyone know of a paper or tutorial that explains a few ways to deal with result sets. Or if anyone knows of a module that will help (that I can study) - that would be just as helpful? TIA John From fumanchu at amor.org Fri May 28 16:10:06 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 28 May 2004 13:10:06 -0700 Subject: mod_python confusion Message-ID: Kylotan wrote: > I thought mod_python would be the answer to my CGI performance issue, > but I can't seem to make much sense out of it. All the examples are > too trivial to be of much use. > > Given that I have an application consisting of several CGI scripts, > what is the simplest way to go about converting it to run on > mod_python, not using the CGI-handler which is allegedly slow and > buggy? Everything seems to suggest a major rewrite because I not only > need to shift from printing everything to calling req.write or > whatever, but I may also need to sort out some sort of dispatching > mechanism mapping URLs to functions if I use mod_python directly. PSP > doesn't work on my system as 3.1.2 gives me errors and the Win32 > installer for 3.1.3 fails at the last step (finding the Apache > directory in the registry or something). Given that webserver advocacy comes and goes, I always recommend abstracting the webserver interface, so rewrites like the one you're talking about hurt less: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/225299 I use that recipe to develop apps which run on Apache2 (Windows) or IIS simply by turning off one server and turning on the other via the Services applet. Notice that recipe also includes a dispatch mechanism for mod_python. Robert Brewer MIS Amor Ministries fumanchu at amor.org From sarah_wang23 at hotmail.com Sat May 29 10:50:15 2004 From: sarah_wang23 at hotmail.com (Sarah Wang) Date: 29 May 2004 07:50:15 -0700 Subject: JMS-like Messaging Service for Python? Message-ID: <9405c70f.0405290650.8e5ad88@posting.google.com> Does python have JMS-like messaging service? (open-source preferred) or any kind of message queue server? From peter at engcorp.com Mon May 3 13:36:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 13:36:01 -0400 Subject: python/pyGtk : How to generate a keyboard interrupt? In-Reply-To: References: Message-ID: Riccardo Attilio Galli wrote: > On Sat, 01 May 2004 08:31:07 -0700, ahk wrote: > >>I would like to emulate the keyboard interrupt through other means >>other than the actual hitting on the keyboard such that a call to >>scaninput() (a C function call?) will be able to pick up the >>interrupt. How is it possible to do that in python/pyGTK? TIA. > >>>>raise KeyboardInterrupt > > Traceback (most recent call last): > File "", line 1, in ? > KeyboardInterrupt I think I detect two people on very different wavelengths here. Forgive me if I'm wrong. I think the OP is talking about the "keyboard interrupt" in the sense of the low-level mechanisms by which keystrokes get into the PC. Each key hit on the keyboard causes data to be sent on the serial link between the keyboard and the motherboard. The motherboard has circuitry which decodes the keystroke and generates a hardware interrupt through the PIC (Programmable Interrupt Controller) chip or the modern equivalent. People with a hardware or low-level software background will sometimes talk about "keyboard interrupts" when they really just mean to ask about receiving raw keystrokes in their software. And this has very little to do with Python's KeyboardInterrupt exception, which is generated by the interpreter when it detects the Ctrl-C keystroke in a console application. I hope that helps avoid what I think was some confusion here... Unfortunately, I can't help the OP with anything to do with PyGTK... -Peter From mir4uu at yahoo.com Sat May 22 08:58:37 2004 From: mir4uu at yahoo.com (mir nazim) Date: 22 May 2004 05:58:37 -0700 Subject: cannot import csv Message-ID: <425cc8d1.0405220458.9668650@posting.google.com> hi, i m unable to import csv module. it says: ImportError: no module named csv. plz help me. is csv module not a part of standard dist? From SeeBelow at SeeBelow.Nut Mon May 3 20:55:13 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 04 May 2004 00:55:13 GMT Subject: Must function defs appear earlier than calls? Message-ID: <4096E9F8.38ABF26D@shaw.ca> Must function defs appear earlier in a file than use of their name? If so, is there some way around this? It's creating a puzzle for me. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From claird at lairds.com Wed May 5 08:04:57 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 05 May 2004 12:04:57 -0000 Subject: Tkinter on way out? (was: Newbe-books) References: Message-ID: <109hm398jc2uk3e@corp.supernews.com> In article , asdf sdf wrote: . . . >wxPython, then Learning Python would totally rock! The sun is setting >on Tkinter.) . . . Perhaps so. I trust that asdf believes the evidence he sees for Tkinter's demise. I agree that wxPython has much to re- commend it. What's most certain, though, is that there have been similar predictions about Tkinter's destiny for at least the last eight years. The ... prematurity of these claims in the past makes me hesitate to write Tkinter off now. -- Cameron Laird Business: http://www.Phaseit.net From Mike at DeleteThis.Geary.com Mon May 17 01:48:47 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 16 May 2004 22:48:47 -0700 Subject: benchmarks and questions for new python programmer References: Message-ID: <10agki14qhts2c2@corp.supernews.com> stormslayer wrote: > Benchmarks (for the paramter settings in the file): > > C++builder 6.0: 3 seconds > Perl (ActivePerl 5.6.1.638): 14 seconds > Python (ActivePython 2.3.2 Build 232): 1 minute 13 seconds > > Note that I didn't fiddle overmuch with any of the programs -- each > one took about 15 minutes to bang out on the keyboard. I'm hoping > that there is some obvious mistake in the way I used something in > python to account for the speed differential. It seems like a really, > really nice language, but orders of magnitude slower than C/C++ and a > 5x slowdown over Perl seems abusive... It's pretty easy to speed up your code by a factor of more than 10. First, you need to figure out where the time is going. Profiling is always a Good Thing, but in this case, it was pretty obvious just by eyeballing the code that the loop in init_all() was the likely culprit. To confirm this, I commented out the call to one_choose(), and sure enough, this didn't reduce the time much at all. So init_all() is where to concentrate our efforts. Here's your init_all() code: > def init_all(): # init globals > global pop, gold, standard > pop = [] > gold = 0 > for i in range(N): > if random.randint(1,2) == 1: > pop.append(1) > gold=gold+1 > else: pop.append(2) > if gold>N/2: standard=1 > else: standard=2 # if tie, silver wins And here is a new version: def init_all(): # init globals global pop, gold, standard pop = [2] * N gold = 0 rand = random.random for i in xrange(N): if rand() < .5: pop[i] = 1 gold += 1 if gold>N/2: standard=1 else: standard=2 # if tie, silver wins What's different here? * I used xrange(N) instead of range(N). This helps a little bit but not much by itself. * Instead of using append() repeatedly to extend the array, I preallocated the entire array with the "pop = [2] * N" statement. This avoids repeated memory allocation and helps a little bit. But still not enough to make a huge difference. * Finally, I tried tracing into the code in the debugger, and when it stepped into the random.randint() funciton, I noticed that this is a fairly complex little function. All you're using it for is to make a 50-50 decision, so we can bypass a lot of code by using random.random() intead. This is where the big speedup comes from. Also, I grabbed a reference to random.random outside the inner loop, which helps a little bit. On my machine, your original code runs in 139 seconds. With these changes, it runs in 10.9 seconds, which would be about 5.7 seconds on your faster machine. If that's not fast enough, you can get the psyco module from http://psyco.sourceforge.net/ and add these two lines to the top of the source file: import psyco psyco.full() With that change, the code runs in 3.6 seconds, which would be about 1.9 seconds on your machine--considerably faster than the C++ Builder time. Good enough? :-) -Mike > Python code: > > #!/usr/bin/env python > import random > > pop=[] # popluation of agents; initially empty list > N = 10000 # population size > ep = .05 # mutation rate > its = 100 # number of times through the main loop > gold=0 # initial number of gold adopters; (1-gold) = silver > adopters > standard=0 # either 1 for gold or 2 for silver > shifts=0 # number of regime shifts > > def init_all(): # init globals > global pop, gold, standard > pop = [] > gold = 0 > for i in range(N): > if random.randint(1,2) == 1: > pop.append(1) > gold=gold+1 > else: pop.append(2) > if gold>N/2: standard=1 > else: standard=2 # if tie, silver wins > # print "Initial Population of Gold Users: ", gold > # end function init_all > > def one_choose(): > global pop, standard, gold, shifts > for i in range(its): > temp = random.randint(0,N-1) > tempval = pop[temp] > old_stand = standard > if random.random() if random.random()<0.5: > pop[temp]=1 > if tempval!=pop[temp]: > gold=gold+1 > if gold>N/2: standard=1 > else: > pop[temp]=2 > if tempval!=pop[temp]: > gold=gold-1 > if gold if standard!=old_stand: shifts=shifts+1 # check for regime > shift after each agent chooses anew > else: > if gold>N/2: > if pop[temp]!=1: > pop[temp]=1 > gold=gold+1 > if gold>N/2: standard=1 > else: > if pop[temp]!=2: > pop[temp]=2 > gold=gold-1 > if gold if standard!=old_stand: shifts=shifts+1 # check for regime > shift after each agent chooses anew > # print "Final Population of Gold Users: ", gold > # end function one_choose > > # start main loop > > > for i in range(1000): > init_all() > one_choose() > print "Number of regime shifts: ", shifts From mwh at python.net Thu May 6 07:20:33 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 6 May 2004 11:20:33 GMT Subject: Is IronPython open source or not ? References: Message-ID: "CHEN Benfeng" writes: > I am interested in IronPython and want to have a study on the source > code. But I cannot find any download link in the homepage of IronPython. I don't think it's publically released at all; source, binary; free or at cost. Cheers, mwh -- If trees could scream, would we be so cavalier about cutting them down? We might, if they screamed all the time, for no good reason. -- Jack Handey From jcarlson at uci.edu Thu May 13 11:22:54 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 13 May 2004 08:22:54 -0700 Subject: classes vs dicts In-Reply-To: References: <409b9a3f_5@newsfeed.slurp.net> Message-ID: > Still, I think it is an overgeneralization to say that classes are > just syntactic sugar for dictionaries. How about this; classes are syntactic sugar for handling object namespaces. Since object namespaces in Python are generally handled with dictionaries, classes are therefore syntactic sugar for dictionaries. Before I read the tutorial on classes when I was learning Python that fateful afternoon years ago, I used dictionaries as the equivalent of instance namespaces. For about 20 minutes it bothered me that I had to use quotation marks to get and set attributes, until I read the class portion of the tutorial and said "ah-hah, classes embed dictionaries as namespaces, perfect", or something like that. - Josiah From maxm at mxm.dk Thu May 13 03:50:18 2004 From: maxm at mxm.dk (Max M) Date: Thu, 13 May 2004 09:50:18 +0200 Subject: if Request("something") == None: doesn't work In-Reply-To: References: Message-ID: <40a328ab$0$257$edfadb0f@dread12.news.tele.dk> Sam Sungshik Kong wrote: > Hello! > > I use Python for ASP programming. > I found something weird. > > Response.Write(Request("something")) > It draws "None" when there's no value for something. > Actually I expect "" instead of "None". You could make it easier on yorself and you convert your Request object to a Python Dictionary instead. http://www.mxm.dk/products/public/iisUtils regards Max M From fredrik at pythonware.com Mon May 24 03:01:51 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 May 2004 09:01:51 +0200 Subject: nested grouping with regular expressions References: <2164532c.0405232251.3877859a@posting.google.com> Message-ID: "ds2000" wrote: > Unfortunately, re.match("<(..)*>", string).groups() will return only > the groups correspond to the last occurence of (regex) > > Is it possible to get a more tree-like group match (i.e. or at least a > list which will contain the groups of each regex occurence). use re.findall (you may have to use multiple REs; a re.search to find the entire group, a re.findall/finditer to split it up). From andrew-pythonlist at puzzling.org Thu May 13 01:12:44 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 15:12:44 +1000 Subject: __slots__ vs __dict__ In-Reply-To: <86d659ylh0.fsf@sysfault.org> References: <120520041314481389%JBrouwers@ProphICy.com> <86hdul2tad.fsf@sysfault.org> <86d659ylh0.fsf@sysfault.org> Message-ID: <20040513051244.GA20388@frobozz> On Thu, May 13, 2004 at 06:55:39AM +0200, Marcus von Appen wrote: > Andrew Bennetts writes: > > [...] > >> > >> # start > >> class Foo (object): > >> __slots__ = "_test", "_test2" > >> > >> def __init__ (self): > >> self._test = 1 > >> self._test2 = 2 > >> > >> def __setattr__ (self, name, value): > >> # just test a simple rebinding > >> self.__slots__ = self.__slots__ > >> return > >> > >> if __name__ == "__main__": > >> f = Foo () > >> f.testvar = "test" > >> return > >> # end > > > > Also a syntax error. I also don't get a bus error, just infinite recursion > > (because assigning to self.__slots__ calls __setattr__, but __slots__ isn't > > an attribute of the instance). What version of Python, and what platform? > > Typed in a wrong line again here. Change it to something appropriate like > > def __setattr__ (self, name, value): > # just test a simple rebinding > self.__slots__.__add__ (tuple (name)) > return Now your example runs just fine (i.e. the script terminates normally, and nothing happens). I still don't see any error. (And why do you keep putting a redundant return at the end of your functions?) Are you sure this is the same code that you get a crash with? What version of Python are you using? (I've tested with 2.2.3 and 2.3.3). -Andrew. From dieter at handshake.de Sun May 23 15:16:06 2004 From: dieter at handshake.de (Dieter Maurer) Date: 23 May 2004 21:16:06 +0200 Subject: Scaling on multi-processor machine References: Message-ID: In article , Atul Kshirsagar wrote: >GIL prevents my C++ application embedding and extending python to scale even >though I spawn multiple C++ threads. I read lot of references on internet >about using multiple processes rather than threads. While your C++ threads are not touching Python objects, they can release the GIL (but must acquire it again before they touch Python objects, e.g. call into Python). Thus, you can have your C++ threads work in parallel as long as they do not touch Python objects. Dieter From plucker-dev-admin at rubberchicken.org Thu May 27 02:59:02 2004 From: plucker-dev-admin at rubberchicken.org (plucker-dev-admin at rubberchicken.org) Date: Thu, 27 May 2004 16:59:02 +1000 Subject: Your message to plucker-dev awaits moderator approval Message-ID: <20040527065902.18867.89912.Mailman@ike.inomial.com> Your mail to 'plucker-dev' with the subject Re: Its me Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From Chris.Hornberger at blackrock.com Wed May 12 13:18:17 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 13:18:17 -0400 Subject: zlib and gzip Message-ID: I got rid of the offsets for a quick test (see code) import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s ) #, -15) return s def makeString(s): s = zlib.compress(s ) #, 9) s = base64.encodestring(s) return s initialdata = "this is a test" print "1)" + initialdata compresseddata = makeString( initialdata ) print "2)" + compresseddata uncompressed = getString( compresseddata ) print "3)" + uncompressed and got the following results: C:\>comp.py 1)this is a test 2)eJwrycgsVgCiRIWS1OISACYzBRY= 3)this is a test C:\> -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Hornberger, Chris Sent: Wednesday, May 12, 2004 1:14 PM To: Bakken, Gregory A; python-list at python.org Subject: RE: zlib and gzip Ok, fair enough. Can you supply (if it's non-sensitive information) some samples? I'm on this conference call for the next hour or so, so I'm glued to my desk. I have time to tinker. It's just a general status call. I just have to chime in from time to time. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: Bakken, Gregory A [mailto:gregory_a_bakken at groton.pfizer.com] Sent: Wednesday, May 12, 2004 1:10 PM To: Hornberger, Chris; python-list at python.org Subject: RE: zlib and gzip The short answer is I don't know. The longer answer is that I really don't know the driving force behind the compression/encoding that is being used. What I am doing is a more downstream process (so I am stuck with the chosen scheme). -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 1:04 PM To: Greg Bakken; python-list at python.org Subject: RE: zlib and gzip Silly questions first: Is it just a matter of 72 column-bounding to make it email-compliant? (keep in mind I haven't run your sample code yet, I'm sitting here perusing while on a conference call - meetings suck!!!) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Greg Bakken Sent: Wednesday, May 12, 2004 12:57 PM To: python-list at python.org Subject: zlib and gzip I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg -- http://mail.python.org/mailman/listinfo/python-list LEGAL NOTICE Unless expressly stated otherwise, this message is confidential and may be privileged. It is intended for the addressee(s) only. Access to this E-mail by anyone else is unauthorized. If you are not an addressee, any disclosure or copying of the contents of this E-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. If you are not an addressee, please inform the sender immediately. -- http://mail.python.org/mailman/listinfo/python-list From winexpert at hotmail.com Mon May 17 14:45:28 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 17 May 2004 18:45:28 +0000 Subject: bit shifting question Message-ID: Hi, My background is c/c++ and java. I'm learning python at this point. My question is does python share java's peculiar mode of bit shifting, or does python adhere closer to c's bit shifting? in java there are 3 kinds of bit shifts: << (shift left) >> (preserve the sign bit as we move right ) >>> (0 filled on the left as we move right) In C, the behavior is << (shift left) >> (shift right , 0 filled (like java's >>>')) I tried looking around but haven't really got an answer yet. I guess I need to write a mini python script. Please don't write any code, I'm just looking for a website or something where I can figure this stuff out in python. Thanks in advance, David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From Joseph.V.Laughlin at boeing.com Fri May 14 17:47:23 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Fri, 14 May 2004 14:47:23 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: <67B3A7DA6591BE439001F2736233351202B479BA@xch-nw-28.nw.nos.boeing.com> > -----Original Message----- > From: Erik Max Francis [mailto:max at alcyone.com] > Sent: Friday, May 14, 2004 2:39 PM > To: python-list at python.org > Subject: Re: RELEASED Python 2.3.4, release candidate 1 > > > beliavsky at aol.com wrote: > > > Thanks to the Python developers for their continuing work. > > > > I wonder why the Linux installation needs to be more > tedious than the > > Windows counterpart. The problem is of course not specific > to Python. > > There are many Linux distributions, running on different > kernels, but > > maybe binaries that have been tested on the "major" > distributions like > > Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. > > Why do you think the standard and near-universal ./configure > && make && make install is tedious? > I would avoid installing applications that way, if only for the fact that you can't uninstall an application. Package management exists for a reason. And once a package is created, installing the application should be a snap. From rzantow at ntelos.net Fri May 14 10:10:37 2004 From: rzantow at ntelos.net (rzed) Date: Fri, 14 May 2004 14:10:37 GMT Subject: Loop and the list References: Message-ID: Krzysztof Szynter wrote in news:Xns94E9A04898D48dygimailpocztafm at 127.0.0.1: [...] > I don't understand why function maxvalue returns "9". When i > start a program and check TY list in 'first main point', the max > value has an index 0'. Then putting the list into the function > maxvalue, gives me the index '9'. ;--/ > > Where is the mistake? > > ps > Apologise for the Polish text's, in the code. I'll answer for > any question. > In maxvalue, you are comparing an index to a value, which seems unlikely to be what you want. Did you mean: if (TY[max] < TY[i]): -- rzed From mwh at python.net Thu May 27 05:41:24 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 27 May 2004 09:41:24 GMT Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: Jacek Generowicz writes: > Michael Hudson writes: > > > Jacek Generowicz writes: > > > > > Could we now just all agree, once and for all, that compiling > > > dynamic languages to native binary really can give significant > > > speedups? > > > > Has anyone really been arguing that? > > Ryan Paul writes in this very thread: > > > I dont understand why everybody seems to want a machinecode compiler. It > > wont make a high-level, dynamically typed language run any faster. OK, that looks wrong :-) Cheers, mwh -- Have you considered downgrading your arrogance to a reasonable level? -- Erik Naggum, comp.lang.lisp, to yet another C++-using troll From nikolai.kirsebom.NOJUNK at siemens.no Mon May 3 04:31:32 2004 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Mon, 03 May 2004 10:31:32 +0200 Subject: Automated installation framework References: Message-ID: On Fri, 30 Apr 2004 15:46:33 +0200, Thomas Heller wrote: >Have you read the paper? The title talks about packaging the Python >distribution, but what Martin does is creating the msi installer using >Python. In other words, a Python framework to create msi packages, >which could contain anything... > >Sorry if I misunderstood again. > >Thomas > Have read through it, and maybe it will do the job. Do you know where I can find examples of use of this module. Thanks for all help. Nikolai From sylphaleya at gmx.net Wed May 26 02:30:49 2004 From: sylphaleya at gmx.net (Manuel Huesser) Date: Wed, 26 May 2004 08:30:49 +0200 Subject: XML-RPC - instance References: Message-ID: > Could you be more specific? It is possible to do method dispatch pretty > much any way that you want; is that the functionality that you are > looking for? Yep there are classes where you can do that in any order, but there are classes where you can't call methods in any order, too. More specific? From grante at visi.com Fri May 28 15:43:16 2004 From: grante at visi.com (Grant Edwards) Date: 28 May 2004 19:43:16 GMT Subject: Anyone know what 512 as a return code for fetchmail means? References: Message-ID: On 2004-05-28, David Stockwell wrote: > I created a userid and put a couple of emails out there. I've tried both > imap and pop3 but both give an answer of 512. I have also removed the > files via a normal remove on the server and then done the below and it > always returns 512. The exit code from the program is in the upper byte of the value returned by os.cmd(). So the return code is 2. According to fetchmail's man page: The exit codes returned by fetchmail are as follows: [...] 2 An error was encountered when attempting to open a socket to retrieve mail. If you don't know what a socket is, don't worry about it -- just treat this as an 'unrecoverable error'. This error can also be because a protocol fetchmail wants to use is not listed in /etc/services. -- Grant Edwards grante Yow! over in west at Philadelphia a puppy is visi.com vomiting... From ssk at chol.nospam.net Thu May 27 01:38:33 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Thu, 27 May 2004 05:38:33 GMT Subject: gencache.EnsureModule Error References: Message-ID: Hi, Tony! You were right. After I gave the permission, the problem was gone. Thanks. Sam "Tony Meyer" wrote in message news:mailman.342.1085608011.6949.python-list at python.org... > I believe that the error occurs at > def ensuremodule(): > gencache.EnsureModule('{00000201-0000-0010-8000-00AA006D2EA4}',0,2,1) > which is for ADO for SQLServer. > > Does anybody know why? [...] > IOError: [Errno 13] Permission denied: > 'C:\\PROGRA~1\\Python23\\lib\\site-packages\\win32com\\gen_py\ > \dicts.dat' It looks like you don't have permission to (re)create that file. Check that it's not locked by someone else, and that you have the appropriate permissions in that directory. =Tony Meyer From ville at spammers.com Thu May 27 11:05:43 2004 From: ville at spammers.com (Ville Vainio) Date: 27 May 2004 18:05:43 +0300 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: >>>>> "Josh" == Josh Gilbert writes: Josh> Now that's a great idea! Not the sigils stuff, I switched Josh> from Perl to Python for a reason, I was putting sigils in my Josh> English, C, and so on. I agree - the $ @ stuff was a (bad) joke, as I said elsewhere. Josh> There are two paths, have the IDE convert each line to Josh> Python when you hit '\n' or as a batch. The first method Josh> would allow it in Python shells. Live conversion would probably bring less surprises. Josh> This is a very good idea. I wonder how hard it will be. At least it doesn't *seem* difficult. It might even be easy enough to do with regexps! Some syntax brainstorming again: d f x,y,z=12: -> def f(x,y,z=12): (, is one keystroke just like space) d f x,y: -> def f(self,x,y): (d with indent, add self) p x; r x; -> print x; return x a.b 1,2 ; a..b ; .a; -> a.b(1,2); a.b ; self.a; Sounds like a potentially fun emacs project, and the style of programming that could be appreci8ed by TXT MSG gener8n :-). -- Ville Vainio http://tinyurl.com/2prnb From me at privacy.net Fri May 28 13:45:14 2004 From: me at privacy.net (Heather Coppersmith) Date: 28 May 2004 13:45:14 -0400 Subject: "Private" Member Variables References: Message-ID: On Fri, 28 May 2004 09:56:43 -0700, "Scott Brady Drummonds" wrote: [ information hiding? ] > ... Why not just allow direct reading and writing of the member > variable? Is there something here I'm missing? Why not indeed? No, there's nothing you're missing. Python takes a "we're all adults here" philosophy. Collections of trivial getters/setters are just clutter (and, IMHO, mean that your class is merely encapsulating data rather than functionality; obviously, though, there are times when that's the Right Thing). If there's something worth "hiding," write a wrapper function, document it, and use it. If there's nothing worth hiding, then don't write a wrapper function, document the members, and just access the members directly. You know your application as well as anyone. You'll know (or learn from experience) when it's time to present an interface to larger functionality rather than just let the rest of the code directly at your objects' members. At worst, you can convert individual members to properties, and run arbitrary code to access those properties, but explicit is better than implicit. > What are your thoughts? How much privacy should I build into my > code? Should I be using variables beginning with "__" and > accessors? Or is that simply not necessary (or normal) in > Python code? Just document your intentions, and stick to your documentation. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From PeterAbel at gmx.net Wed May 12 15:48:02 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 12 May 2004 12:48:02 -0700 Subject: max value in list References: Message-ID: <21064255.0405121148.152ec1f4@posting.google.com> "C GIllespie" wrote in message news:... > Dear all, > > I have a few lists. What's the best way of finding the maximum number of all > the lists. > > For example, > > [2,3,4],[1,2,3],[4,7] > > The max is 7. > > Thanks > > Colin >>> l=[[2, 3, 4], [1, 2, 9], [4, 7]] >>> max(map(max,l)) 9 >>> l=[[2, 3, 4], [1, 2, 9],[12], [4, 7]] >>> max(map(max,l)) 12 >>> Regards Peter From jdhunter at ace.bsd.uchicago.edu Wed May 5 11:14:05 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 05 May 2004 10:14:05 -0500 Subject: the dreaded double fork Message-ID: I am using python to run an xml rpc daemon using SimpleXMLRPCServer. Following a cookbook recipe, I am trying to do a double fork so that when I exit the shell the daemon remains running. But it doesn't. Here is how I start the script > ssh somehost > sudo python mydaemon start& But when I exit the shell, I lose the process. What am I doing wrong? Here is my script, with all the non server stuff snipped. import sys, os pidfile = '/tmp/ogtt_daemon.pid' host = 'dardd.bsd.uchicago.edu' port = 2358 class AnalysisServer: snip def main(): import SimpleXMLRPCServer while 1: # Daemon's main code goes here server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port)) server.register_instance(AnalysisServer()) server.serve_forever() def get_daemon_pid(): if os.path.exists(pidfile): pid = open(pidfile, 'r').read() return int(pid) else: return None def stopd(): print 'Stopping daemon...', if not os.path.exists(pidfile): print 'Daemon does not appear to be running' return pid = get_daemon_pid() os.popen('kill -9 %d' % pid) print 'OK' os.remove(pidfile) if __name__ == "__main__": if sys.argv[1]=='start' and os.path.exists(pidfile): print 'Process appears to be running' sys.exit() if sys.argv[1]=='stop': stopd() sys.exit() # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent, print eventual PID before print "Daemon PID %d" % pid file(pidfile, 'w').write('%d\n'%pid) sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # start the daemon main loop main() From __peter__ at web.de Thu May 6 10:46:52 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 16:46:52 +0200 Subject: classes vs dicts References: <7id65haegq.fsf@enark.csis.hku.hk> Message-ID: Yermat wrote: > So the real question is what do you prefer to type : somePerson.name or > somePerson["name"] ? And if you [OP] really cannot make up your mind: >>> class Both: ... def __getitem__(self, key): ... return self.__dict__[key] ... def __setitem__(self, key, value): ... self.__dict__[key] = value ... >>> b = Both() >>> b["name"] = "won't tell" >>> b.name "won't tell" >>> b.address = "in the middle of nowhere" >>> b["address"] 'in the middle of nowhere' >>> b["this is nasty"] = "now what?" >>> After all a class is just syntactic sugar for a dictionary and a dictionary is just a class, which is... :-) Peter From chetan_hram at rediffmail.com Wed May 12 17:07:35 2004 From: chetan_hram at rediffmail.com (chetan hs) Date: 12 May 2004 21:07:35 -0000 Subject: istalling python2.3 on RH linux9 Message-ID: <20040512210735.19400.qmail@webmail26.rediffmail.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- Hi, I have installed Red Hat Linux 9, and tried to install python2.3 on python2.2 but there was a library installation error, while doing "make install". I wanted to access BerkelyDB4.2 from python but it was not possible. Please can you help me rectify that error. BerkeleyDB4.2 is installed without any errors. regards, chetan From http Wed May 12 01:51:58 2004 From: http (Paul Rubin) Date: 11 May 2004 22:51:58 -0700 Subject: How to batch download files from web page? References: Message-ID: <7x4qqmxke9.fsf@ruckus.brouhaha.com> sj writes: > I wish to download hundreds of files from the University of Iowa sound > archive. Doing it manually would be a daunting task especially since the > files are each a few mega bytes long. Is there a standard way of using > Python for such a task? I have a fair amount of programming experiance but > very little of it relates to networks. You could use the urllib module, or maybe you could use wget: http://www.gnu.org/software/wget/wget.html From ally_burnett at yahoo.co.uk Fri May 14 08:40:53 2004 From: ally_burnett at yahoo.co.uk (alastair) Date: 14 May 2004 05:40:53 -0700 Subject: smtplib - missing message Message-ID: <23ae7099.0405140440.341a6244@posting.google.com> Hi, I'm trying to send an email using smtplib and a Yahoo smtp server. I've read that this uses authentication, so in order to use 'smtp.mail.yahoo.com' as the host, I use the login() method, and this works fine (ie I login ok) . When I look at the received mail, the text I send is not there - does anyone know why this is the case ? Here's the code I've been using: import smtplib server = smtplib.SMTP("smtp.mail.yahoo.com") server.debuglevel = 25 server.login("myusername", "mypassword") fromClause = "me at me.com" toClause = "you at yahoo.co.uk" msg = "Please display me." server.sendmail(fromClause, toClause, msg) server.quit() Regards, Alastair. From skjj at earthlink.net Tue May 4 13:55:02 2004 From: skjj at earthlink.net (Your name) Date: Tue, 04 May 2004 17:55:02 GMT Subject: Arbitary VTABLE/Python References: <87isfy5egr.fsf@pobox.com> Message-ID: can you please elaborate on: > It has, only quite recently, acquired the > ability to implement arbitrary vtable interfaces. Does this mean that one can call QueryInterface functionality from Python? Having very large C++ COM interfaces (and not all of the interfaces support automation, only some support), can I replicate what we are doing in C++ WITHOUT going through external interface libraries (ctypes, boost etc)? jjl at pobox.com (John J. Lee) wrote in news:87isfy5egr.fsf at pobox.com: > John Smith writes: > [...] >> We have very,very large C++ applications >> that talk to third part COM based server(s), >> both in-proc & out-of-proc >> >> - For large arbitary vtable based interfaces, >> what is the best approach from Python? >> >> We looked at FAQs, DOCs (including ActiveState), WEB >> searches, and saw references to SWIG, PythonCOM extensions >> BOOST.Python etc, and some problems people have reported using >> arbitary vtable interfaces from PythonCOM (BTW: where is are DOCs on >> one using/creating PythonCOM extensions? From our >> WEB searhces, it looks like 'makepy' may not >> work under all situations?) > [...] > > makepy applies only to IDispatch-based interfaces. PythonCOM doesn't > call arbitrary vtable interfaces yet (unless it has very recently > grown that ability). It has, only quite recently, acquired the > ability to implement arbitrary vtable interfaces. Of course, you can > always write an extension in C or C++, and integrate that with > win32all, but that's a bore, and I'm not sure it's a well-documented > process. > > (Just to clear up any possible confusion: PythonCOM is part of > win32all (which itself is also bundled with ActiveState's Python > distribution, if they're still doing that). Mind you, I can never > remember whether PythonCOM is an internal part of win32all, or an > umbrella name for win32all's COM functionality, or what... so I always > just say 'win32all', or win32com, if I specifically mean that module >:-) > > So, win32all is nice, but it doesn't do what you want (call arbitrary > vtable COM interfaces), at least without doing some wrapping and > knowing about win32com's / pythoncom's internals. > > The most Pythonic route is ctypes. > > ctypes is quite elegant, thin and small (in contrast to win32all). > It's still fairly new, but because it's relatively small, if you've > got highly experienced COM developers on board, I'd imagine you're not > going to struggle too much with any problems that do crop up. I used > an earlier release and bumped into two bugs when I played with it, but > found they were already fixed in CVS. It's more stable now (6 months > or more since the version I used was released). Recent testimony: > > http://mail.python.org/pipermail/python-list/2004-April/214912.html > > > The other way is to write your client code in C++, then wrap it. > Boost Python is pretty much the standard way to do that for Python. > I've never used it. I guess it's useful as an insurance policy if > ctypes fails at some task for you. I think Mark Hammond (primary > win32all author) )has his own ways of wrapping COM interfaces, but > whether they're suitable for public consumption I don't know. > > If my goal were at all related to C++, I wouldn't use SWIG, unless it > has advanced quite a bit since I last looked (a year or so ago). > Boost Python is generally agreed to be a better solution unless you > need to expose things to multiple scripting languages. > > > John > From mal at egenix.com Tue May 11 09:35:28 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 11 May 2004 15:35:28 +0200 Subject: mx.DateTime bug? In-Reply-To: References: Message-ID: <40A0D6A0.1040505@egenix.com> Denis S. Otkidach wrote: > DateTime objects always compare equal to instances of > user-defined classes: > > Python 2.3.2 (#1, Nov 27 2003, 18:07:14) > [GCC 3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>>>from mx import DateTime >>>>DateTime.__version__ > > '2.0.3' > >>>>class c: pass > > ... > >>>>DateTime.now()==c() > > True > > Documentations states that "DateTime and DateTimeDelta instances > can be compared and hashed, making them compatible to the > dictionary implementation Python uses (they can be used as > keys)", but there is at least race condition when instance of > user defined class has the same hash value. Moreover, making > DateTime objects to be always equal to instances with unknown > nature is a bad idea. That's a bug that needs fixing. The reason is that mxDateTime checks the nb_float slot of the object and thinks that it gets number if the slot is non-NULL. For Python instances, the slot is non-NULL, but whether they behave like floats depends on the availability of the __float__ method. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 11 2004) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ EuroPython 2004, G?teborg, Sweden 26 days left ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From __peter__ at web.de Thu May 6 02:28:42 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 08:28:42 +0200 Subject: question: parameters for create_polygon() method References: <40984D5A.B819BF28@shaw.ca> <40986DD6.F06FF651@shaw.ca> <4099AF0C.85717026@shaw.ca> Message-ID: SeeBelow at SeeBelow.Nut wrote: > The suggestion about a flatten() function is also a good one, but it > turns out not to be needed. Looking into the source it turns out that Tkinter has its own flattening function (implemented in C, with a Python fallback), which ignores None and processes both tuples and lists: >>> Tkinter._flatten([((0, 0), (100, 0)), None, ((100, 100), (0, 100)), 50, 70, (50, 30)]) (0, 0, 100, 0, 100, 100, 0, 100, 50, 70, 50, 30) >>> So you are not limited to tuples when constructing your polygons: import Tkinter as tk root = tk.Tk() canvas = tk.Canvas(root) canvas.pack() line1 = (0, 0), (100, 0) line2 = (100, 100), (0, 100) points = [line1, None, line2, 50, 70, (50, 30)] canvas.create_polygon(fill="red", *points) root.mainloop() Peter From aahz at pythoncraft.com Fri May 21 19:50:13 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 May 2004 19:50:13 -0400 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> Message-ID: In article , Grant Edwards wrote: > >OK, I see what you mean. That brings up the question of why >use integer indexes to access members of of a group of objects >when the order of the objects is meaningless? Because it's lightweight compared to using string indexes (i.e. a dict). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From devnull at example.com Thu May 6 02:44:08 2004 From: devnull at example.com (Derek Fountain) Date: Thu, 06 May 2004 14:44:08 +0800 Subject: What does 'is' do? Message-ID: <4099de7e$0$4321$5a62ac22@freenews.iinet.net.au> I recently saw a use of 'is' in a piece of Python code. I was trying to find out what it does. I can't find it in the online docs. I have the "Python in a Nutshell" book and that mentions it as a keyword, but I can't find a description of it in there either. It's not in the index. Can someone tell me where to look? From theller at python.net Fri May 28 04:52:04 2004 From: theller at python.net (Thomas Heller) Date: Fri, 28 May 2004 10:52:04 +0200 Subject: ANN : ConfigObj 3.0.0 - Simple config file parsing References: <8089854e.0405260620.230f8319@posting.google.com> Message-ID: David Fraser writes: > Just as an aside, we've just written a config system for our app that > I think is quite interesting and am planning to release when I get > time. > > Some of the goals are the same as ConfigObject: easy for either a > human or a computer to read / edit the files. > Some are different. Particularly it handles hierarchical config tries > in a nice pythonic syntax. For example you can specify things like > this: > > app1.title = "Title of app" > app1.font.face = "Arial" > > Or like this: > > app1: > title = "Title of app" > font.face = "Arial" [...] > The module will automatically remember where an element is defined and > save changed values to the same location. It will also save new values > to an appropriate location (e.g. app2.newvalue would appear in the > app2 section). > > I think the hierarchical aspect of configuration is important ; it > lets you do things like Mozilla's generic prefs interface etc. It also > gives plugins / customizations to an app an easy way to add their own > preferences. > > If anyone is interested in this module, post a reply... Looks interesting, if you ask me. Thomas From riccardo_cut-me at cut.me.sideralis.net Mon May 3 15:56:09 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Mon, 03 May 2004 21:56:09 +0200 Subject: python/pyGtk : How to generate a keyboard interrupt? References: Message-ID: On Sat, 01 May 2004 08:31:07 -0700, ahk wrote: > I would like to emulate the keyboard interrupt through other means > other than the actual hitting on the keyboard such that a call to > scaninput() (a C function call?) will be able to pick up the > interrupt. How is it possible to do that in python/pyGTK? TIA. >>> raise KeyboardInterrupt Traceback (most recent call last): File "", line 1, in ? KeyboardInterrupt -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From Chris.Hornberger at blackrock.com Wed May 12 16:22:43 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 16:22:43 -0400 Subject: __slots__ vs __dict__ Message-ID: >PS) The tests were run on a dual 2.4 GHz Xeon system with RedHat >8.0 and Python 2.3.2. The test script is attached but keep in mind >that it only has been tested on Linux. It will not work elsewhere >due to the implementation of the memory() function. When you're trying to eke out every last bit of performance, that's fine. However, I tend to shy away from using VM-based solutions (Java, Python, even .NET/C#) when they are tied to a platform. If I *must* do so, I farm out the platform-specific pieces to a library, and my main app gets some code added that knows how to load libraries on the fly. When feasible, mind you. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. From dmq at gain.com Mon May 3 14:44:06 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 03 May 2004 11:44:06 -0700 Subject: Unification of Methods and Functions References: Message-ID: <4n4d905eflq6ekrutjmrg3t6llk2b8lab7@4ax.com> On Mon, 03 May 2004 13:11:17 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> The concept of using a >> global variable __self__ is no surprise at all. > >Except that __self__ can't be a global variable. >Implementing it that way would be a disaster. It seems to work in Michele Simionato's 'prototype' module. { comp.lang.python, 4/28/04, "Prototypes in Python"} It is global only to the called function, but the key requirement is met -- no alteration of the standard function calling sequence. Why can't it be a true global? -- Dave From peter at engcorp.com Wed May 5 11:13:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 May 2004 11:13:31 -0400 Subject: OT: software like VNC In-Reply-To: References: Message-ID: Alberto Vera wrote: > Do you know another software that works like VNC or PCAnywhere? Two questions: 1. What did Google tell you when you tried to search? 2. Are you looking for something done with Python specifically or, if not, what's the connection to the subject of this mailing list/ newsgroup? From timothy.williams at nvl.army.mil Wed May 19 11:01:21 2004 From: timothy.williams at nvl.army.mil (Williams, Timothy J Mr RDECOM CERDEC NVESD) Date: Wed, 19 May 2004 11:01:21 -0400 Subject: alternatives to making blocks like { } or other ?? Message-ID: <0C00093F0D28524691B5763B554A7F253C7D1D@nvlex01.nvl.army.mil> > -----Original Message----- > From: Michael Chermside [mailto:mcherm at mcherm.com] > Sent: Wednesday, May 19, 2004 9:09 AM > To: timothy.williams at nvl.army.mil; python-list at python.org > Subject: alternatives to making blocks like { } or other ?? > > > Tim Williams writes: > > I have to put my 2 cents in here. I love Python, but the one thing I > > miss is using {} or something to enclose blocks. I edit in emacs > > python-mode, and believe in indentation, but sometimes I'll > > inadvertently change a line of code's indentation and it throws the > > logic off. I found a bug in one of my programs recently where a line > > of code should have been outside of an 'if', but wasn't > because I hit > > TAB one too many times. A {} block would've caught that. I > know that's > > just being careless, but I need all the help I can get! > > I don't mind using C-derived languages occasionally, but one > thing that > bothers me is having to use {} or something to enclose blocks. I use > various editors, and I believe in both delimiting and indenting, but > sometimes I'll inadvertently change indentation or move the > position of > a brace and either way it throws the logic off. I created a > bug in one of > my programs recently just by adding logging. It looked like this: > > if (some_complicated_condition) > log_message("Error has occurred: taking corrective action"); > take_corrective_action(); But here if there were braces, the logic would be right. Indentation wouldn't matter. if (some_complicated_condition) { log_message("Error has occurred: taking corrective action"); take_corrective_action(); } > > When I read through the code it LOOKED like it worked, but of course > the corrective action was taken even when it wasn't needed. I've also > seen more complex examples like this: > > if (condition_1) { > code_1; > } else if (condition_2) > if (condition_2_a) { > code_2_a; > } > // nothing to do for 2b > else { > code_3; > } > Looks like an argument for braces to me. > But the ones that I hate the MOST are the ones that my unit > tests can't > catch. A typical example looks like this: > > if (condition) { > code; > goes; > here; > } else { > more; > code; > } > > Notice how that one line ("here;") is indented wrong? Obviously, that > doesn't meet our coding standards, yet there's no way for the compiler > to catch it, because the compiler looks only at the braces and ignores > the indentation! I know that's just being careless, but I need all the > help I can get! If only there were a better language I could use. > Here again indentation doesn't matter. A smart editor could do a "pretty-print" for you using the braces. I agree that *visually* indentation w/o the braces are nice, but as a check for having code in the right logical block, it's just too easy have a stray extra or missing space (for me anyway) that would throw everything off. Isn't just one space needed in Python to signify a different block? From cy.fbp.eryvtvne at ncbybtrglxn.pbz Wed May 5 03:37:55 2004 From: cy.fbp.eryvtvne at ncbybtrglxn.pbz (JZ) Date: Wed, 5 May 2004 09:37:55 +0200 Subject: Best IDE? References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> Message-ID: <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> 1 May 2004 15:06:21 -0700, na comp.lang.python, SM napisa?(a): > you can download it from http://projects.blender.org/projects/spe/ The > windows XP version is already quite stable, for linux and mac os x, > I'm dependent of other users. SPE is still buggy for Windows XP. If you use non-ascii characters it can delete all content of the file. Yesterday I lost one file usign new SPE editor and I come back to PythonWin. The same bug was in earlier version. -- JZ From peter at engcorp.com Fri May 21 11:40:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 11:40:42 -0400 Subject: Specify start and length, beside start and end, in slices In-Reply-To: References: Message-ID: Noam Raphael wrote: > Grant Edwards wrote: >> It's a bit less efficient, but you can currently spell that as >> >> l[12345:][:10] >> > That is true, but if the list is long, it's *much* less efficient. Considering that the interpreter special-cases some integer math including the BINARY_ADD, it likely wouldn't take a very long list to pass the point where they're the same. I like the idea of the optimization, in a sense, but I don't like the syntax and doubt that there is much performance gain to be had. There are probably better places for people to hack on the interpreter, and which don't need syntax changes. -Peter From GPodubs at hotmail.com Wed May 26 15:14:50 2004 From: GPodubs at hotmail.com (SilverShadow) Date: Wed, 26 May 2004 15:14:50 -0400 Subject: Defining Multiple Objects at Once References: <464afbb13c2bd25bb14351db772159e0@localhost.talkaboutprogramming.com> Message-ID: Thank you both for the input. I think that your suggestions will be very helpful. I guess it is back to work then! Greg From aahz at pythoncraft.com Wed May 12 09:41:58 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 May 2004 09:41:58 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: In article , Kirk Job-Sluder wrote: > >And here is the fundamental question. Why should I spend my time >writing a module in python to emulate another tool, when I can simply >use that other tool? Why should I, as a resarcher who must process >large quantities of data, spend my time and my employer's money >reinventing the wheel? Why should your employer pay for the time for all of its employees to learn all of those other tools, when Python will do the job? I've used sed and awk often enough to read other people's code some of the time, but I certainly can't write them without a great deal of effort, and modifying an existing example to do what I want might or might not be easy -- no way of knowing in advance. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From kdahlhaus at yahoo.com Mon May 10 10:57:17 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 10 May 2004 07:57:17 -0700 Subject: What I don't like about wxPython References: Message-ID: <283adf56.0405100657.6f4840ef@posting.google.com> I'll throw a plug in here for pyFltk. It overcomes many of the issues you have with wxPython. It's not as heavily developed as the wxWin, but Andreas is doing a great job of updates since taking it over. It's based FLTK, which is intended to be small, fast, good-looking, cross-platform API. I chose it originally because it was all of these and I found the API remarkably clean. I don't recall the exact list of depdendencies off hand, but it's nothing large other than FTLK, optionally opengl, and perhaps the standard image libs. Everybody probably has a slightly different definition of 'pythonic.' pyFltk works via registering a callable as a callback. So that can be a member-function on an object or static class function or a stand-alone function, heck even a lamda. The event handling/callback mechanism meets my definition of pythonic. The wrapper even handles overloaded functions transparently. One of the greatest contributions Andreas made was allowing subclassing of the FLTK widgets in python. The downside is that it's not quite as polished yet as wxWindows. This plug is because although I'm not actively involved anymore, I think it has potential to be a great asset to the the Python community and would to see the rough edges smoothed out. Ryan Paul wrote in message news:... > On Sat, 08 May 2004 12:40:52 -0700, j_mckitrick wrote: > > > Just thought I'd play devil's advocate... From ajsiegel at optonline.com Fri May 28 01:44:02 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 05:44:02 GMT Subject: terminological obscurity References: <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <1085718479.27401@yasure> Message-ID: On Fri, 28 May 2004 04:28:00 -0000, "Donn Cave" wrote: >Note that >the passage above describes a slightly different homogeneity. Why if Martin was consciously using the terminolgy differently than it had been used before - which is one of the possbilities I had identified - would he choose not to disclose the fact. If some kind of purposeful mystification was not at least an unconscious motivation. >This list still contains a module and a None, but now some >arrangement has been made to give them each the same type, when >before they were of completely disparate types (and still are.) >Well, I'm not really sure what he has in mind there, so there >is some ambiguity for students of homogeneity such as ourselves. I have concluded that one needs a post-doc in ambiguity as a prerequisite to becoming a student of homogeneity. :) Art From theller at python.net Thu May 6 15:07:36 2004 From: theller at python.net (Thomas Heller) Date: Thu, 06 May 2004 21:07:36 +0200 Subject: changing exceptions in C code Message-ID: I'm calling into Python code from C with PyObject_CallObject(). If the python function raises an exception, the above code returns NULL, and I want to print out the exception with PyErr_Print(). For whatever reasons, I want to prepend a short string "(in callback)" to the error message itself: result = PyObject_CallObject(callable, arglist); if (!result) { Extend_Error_Info("(in callback)"); PyErr_Print(); } I figured out this code for the Extend_Error_Info function: void Extend_Error_Info(char *fmt, ...) { va_list vargs; PyObject *tp, *v, *tb, *s; va_start(vargs, fmt); s = PyString_FromFormatV(fmt, vargs); va_end(vargs); if (!s) return; PyErr_Fetch(&tp, &v, &tb); PyErr_NormalizeException(&tp, &v, &tb); PyString_ConcatAndDel(&s, PyObject_Str(v)); Py_DECREF(v); PyErr_Restore(tp, s, tb); } Does this look ok by the experts? TIA, Thomas From martin at v.loewis.de Sat May 29 02:39:51 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 May 2004 08:39:51 +0200 Subject: terminological obscurity In-Reply-To: References: <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> Message-ID: <40b83034$0$27038$9b622d9e@news.freenet.de> Arthur wrote: > But then nothing can be determined about the hetergenousity or the > homogenousity of any particular context for this data by reference to > the data itself. > > Though the reverse is not true. > > In the conversation I am having this is a significant point. > > But I suspect we are not having the same conversation. I'm uncertain. I would see a significant point if you would admit that "a list is for homogenous data" is not a tautology. You certainly need a context to make a statement about homogeneity, but that context is *not* the mere fact that the data are all stored in the list. Regards, Martin From mwall at diversa.com Wed May 26 13:29:52 2004 From: mwall at diversa.com (Mark Wall) Date: Wed, 26 May 2004 10:29:52 -0700 Subject: How do I read compressed (.Z) files Message-ID: <81D14648D6BD694CBDB4F45536E81CBC3FD085@aquarius.diversa.com> If I have a UNIX compressed text file 'python.txt.Z' with contents: "Python " How do I read this data without uncompressing the file? Thank you, Mark From peter at engcorp.com Wed May 26 06:47:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 06:47:35 -0400 Subject: Cleaner idiom for text processing? In-Reply-To: References: Message-ID: Peter Otten wrote: > But if that lets you sleep better at night, change Peter Hansen's suggestion > to use islice(): No! Yours is much more elegant! Wonderful... zero overhead. -Peter From pete.forman at westerngeco.com Tue May 11 10:10:27 2004 From: pete.forman at westerngeco.com (Pete Forman) Date: 11 May 2004 15:10:27 +0100 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <109t59e3v0oob1d@news.supernews.com> <8cGdnYFHpPRsBgLdRVn-iQ@comcast.com> Message-ID: Jason Mobarak writes: > John Roth wrote: > > "Olivier Scalbert" wrote in message > > news:409e86e9$0$22811$a0ced6e1 at news.skynet.be... > > > What is the python way of doing this : > > > perl -pi -e 's/string1/string2/' file > > > > I'm not sure what the -pi and -e switches do, but the rest is > > fairly simple, although not as simple as the perl one-liner. > > Just load the file into a string variable, and either use the > > string .replace() method, or use a regx, depending on which is > > appropriate. Then write it back out. > > [...] > > More obfuscated: > > python -c '(lambda fp: fp.write(fp.seek(0) or > "".join([L.replace("th","ht") for L in fp])))(file("foo","rw+"))' For a less obfuscated approach, look at PyOne to run short python scripts from a one-line command. http://www.unixuser.org/~euske/pyone/ -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- opinion of Schlumberger, Baker http://petef.port5.com -./\.- Hughes or their divisions. From bignose-hates-spam at and-benfinney-does-too.id.au Sun May 16 22:19:42 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 17 May 2004 12:09:42 +0950 Subject: Is there any instruction on implementing a python debugger? References: Message-ID: On Mon, 17 May 2004 10:08:50 +0800, Phipps Xue wrote: > I wanna implement a python debugger, but I don't know the way exactly. By "implement", do you mean you want to use an existing one, or you want to make your own? -- \ "An idea isn't responsible for the people who believe in it." | `\ -- Donald Robert Perry Marquis | _o__) | Ben Finney From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Wed May 5 12:01:27 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Wed, 05 May 2004 18:01:27 +0200 Subject: Web programming ... In-Reply-To: References: Message-ID: <40990fd8$0$567$e4fe514c@news.xs4all.nl> Sarah Tanembaum wrote: > Is python good for creating Web application? Short answer: yes. Long answer: http://www.python.org/cgi-bin/moinmoin/WebProgramming --Irmen From timr at probo.com Mon May 24 01:51:11 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 23 May 2004 22:51:11 -0700 Subject: ANN: uid.py 1.0.2 -- Configurable unique ID generation References: <40AC1487.EA453C74@alcyone.com> Message-ID: Erik Max Francis wrote: > >Summary > > Configurable unique ID generation. > >Overview > > Provided is an implementation of a "unique" ID (UID) generator in > Python. The implementation does not follow UUID or GUID > standards, ... Maybe I'm being ridiculous, but intuitively, this makes me uncomfortable. If one has a "unique ID" generator, isn't it likely that any change to its configuration is only going to serve to reduce the "uniqueness"? UUIDs and GUIDs are standardized for a reason. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From peter at engcorp.com Wed May 26 19:57:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 19:57:41 -0400 Subject: Cleaner idiom for text processing? In-Reply-To: <7xzn7uojmi.fsf@ruckus.brouhaha.com> References: <7xzn7uojmi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > mellis at frogwing.com (Michael Ellis) writes: > >>for line in infile: >> tokens = line.split() >> dict = {} >> for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1] >> do_something_with_values(dict['foo'],dict['bar']) > > > Here's a pessimized version: > > for line in infile: > tokens = line.split() > d = {} > while tokens: > name = tokens.pop(0) > value = tokens.pop(0) > d[name] = value > do_something_with_values(dict['foo'],dict['bar']) Paul, I don't understand why you say "pessimized". The only potential flaw in the original and most (all) of the other solutions seems to be present in yours as well: if there are an odd number of tokens on a line an exception will be raised. -Peter From nikolai.kirsebom.NOJUNK at siemens.no Tue May 18 07:48:27 2004 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Tue, 18 May 2004 13:48:27 +0200 Subject: print / str / repr Message-ID: <4mm9a05hjv10vgle5bh07d9bpf2e7sj44b@4ax.com> How do I (in a program) achieve the same result as using the print statement (interactive). In the interpreter: >>> s = u "some '\xcf' text" >>> print s Traceback (most ....): UnicodeError: ASCII encoding error: ordinal not in range(128) >>> s.encode('latin-1') "some '\xcf' text" >>> print s.encode('latin-1') some '?' text >>> `s.encode('latin-1')` '"some \'\\xcf\' text"' Thanks for any help. Nikolai From __peter__ at web.de Wed May 5 02:50:24 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 May 2004 08:50:24 +0200 Subject: question: parameters for create_polygon() method References: <40984D5A.B819BF28@shaw.ca> <40986DD6.F06FF651@shaw.ca> Message-ID: Andrew Bennetts wrote: > Sorry, I misinterpreted the problem slightly; I just checked the docs for > create_polygon and realised it takes an argument that is a sequence of > co-ords, rather than a variable number of args that are the co-ords. I just tried it - it may not be in the docs, but it does work. For example import Tkinter as tk root = tk.Tk() canvas = tk.Canvas(root) canvas.pack() points = [(20, 20), (50, 150), (200, 50)] canvas.create_polygon(fill="blue", *points) root.mainloop() will draw a blue triangle. Peter From claird at lairds.com Wed May 5 08:22:47 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 05 May 2004 12:22:47 -0000 Subject: Several questions about embedding Python References: Message-ID: <109hn4ng8bcdnaa@corp.supernews.com> In article , Miki Tebeka wrote: >Hello All, > >I'm trying to extend a hardware simulator (written in C/C++) by >embedding Python. >After reading the documentation and playing around several questions >popped up: > >1. Is there a way (using SWIG/Boost.Python ...) to export existing C/C++ >functions other than hand writing the wrapper functions. >Something like: py_export(a_c_function) >Since the Python module need to get information from the simulator I >can't just write pure SWIG wrapper (or can I?) > >2. How do I debug the Python code? Since the interpreter is called from >the simulator application I can't run `pdb' on it. > >3. Why on does pyconfig.h decides that `python23_d.lib' should be used >when _DEBUG is on (IMO is should use Py_DEBUG)? I'm debugging *my* >application not Python. . . . I'm sympathetic on 3. Python's compile options ... well, *my* preferred mental models don't match them well, yet. I have no feel for the likelihood of a change or workaround here. With luck, timbot will say a few words. I don't know how to debug, in this sort of embedding context in particular; the reason you cite is a good example of why. I sit and think a lot, so that I understand what my applica- tions do. I don't use debuggers. I'm still undecided about whether it's helpful for me to confess that. Yes, you can use pure SWIG wrappers. I'll be more precise: it *sounds* as though you're saying SWIG is only for extending Py- thon, and not embedding Python. This is false; SWIG can be used to embed Python. Maybe there's a problem with use of SWIG in a particular approach to embedding; just from what you've written, though, I think it's reasonable to expect success with SWIG's use. -- Cameron Laird Business: http://www.Phaseit.net From peter at engcorp.com Tue May 11 12:54:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 May 2004 12:54:31 -0400 Subject: OT: Idea for Python T-shirt In-Reply-To: References: Message-ID: Heiko Wundram wrote: > Am Dienstag, 11. Mai 2004 15:41 schrieb Peter Hansen: > >>If you plan to try selling them, note that in North America it's >>generally "nybble", by analogy with "byte". Nibble is the British >>English spelling. > > > I guess he refers to the other meaning of nibble (from dictionary.com): > > 1. A very small quantity, especially of food; a morsel. Then I _really_ don't get it. From fishboy at spamspamspam.com Mon May 31 07:34:23 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 31 May 2004 11:34:23 GMT Subject: NNTP binary attachment downloader using asyncore and generators Message-ID: <3h5mb0h7mq7n7peruqat9ia6jhahbf1ons@4ax.com> Howdy, Sorry if this is a double post. First try seemed to go into hyperspace. I'm working on a personal project. It's going to be a multipart binary attachment downloader that will search alternate servers for missing pieces. This is the working code so far. It will walk a newsgroup and download and decode all the single part attachments. Just change server,user,password,group at the bottom to something less virtual. I'm posting this to get some feedback on my use of generators (and anything else). It's my first time using them in a non-trivial program, and I'd like to know if there is more 'Pythonic' way I could be doing any of this. My email is obviously fake, so responding here would be great. Thanks in advance, David Fisher #!/usr/bin/env python2.3 # import asyncore import socket import os import uu import email # class Newser(asyncore.dispatcher): def __init__(self, host,port,user,password,group): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect( (host,port) ) self.buffer = '' self.user = user self.password = password self.group = group self.n = 0 self.head = '' self.body = '' self.inbuffer = '' self.dataline = '' self.handleline = self.handleline_gen() def handle_connect(self): pass def handle_close(self): pass def writable(self): return (len(self.buffer) > 0) def handle_write(self): print 'sending: ' + self.buffer.strip() sent = self.send(self.buffer) self.buffer = self.buffer[sent:] if self.buffer: print 'didnt send whole line' #does this ever happen? print 'didnt send whole line' #just getting my attention print 'didnt send whole line' #in case it does def handle_read(self): self.inbuffer += self.recv(8192) while 1: n = self.inbuffer.find('\r\n') if n > -1: self.dataline = self.inbuffer[:n+2] self.inbuffer = self.inbuffer[n+2:] try: result = self.handleline.next() if result == 'OK': pass # everything is groovy elif result == 'DONE': self.del_channel() # group walk is finished break else: print 'something has gone wrong!' print result print self.dataline self.del_channel() break except StopIteration: print 'should never be here' print 'why did my generator run out?' print 'why god? why?!' print self.dataline self.del_channel() break else: break def handleline_gen(self): # # handshakey stuff # welcome username password group # after this is set we'll start the message walk # if self.dataline[:3] == '200': # welcome, post ok print self.dataline.strip() self.buffer = 'authinfo user ' + self.user + '\r\n' yield 'OK' else: yield 'WTF?! fail welcome? god hates me!' # if self.dataline[:3] == '381': # more auth needed print self.dataline.strip() self.buffer = 'authinfo pass ' + self.password + '\r\n' yield 'OK' else: yield 'WTF?! fail authinfo user' # if self.dataline[:3] == '281': # auth ok, go to town! print self.dataline.strip() self.buffer = 'group ' + self.group + '\r\n' yield 'OK' else: yield 'WTF?! fail authinfo pass' # if self.dataline[:3] == '211': # group print self.dataline.strip() self.buffer = 'next\r\n' yield 'OK' else: yield 'WTF?! fail group' # # main state loop # walk from one message to the next # issuing HEAD and BODY for each # never reenter here after we receive '421', no next article # so we should never issue StopIterator # while 1: # if self.dataline[:3] == '223': # next print self.dataline.strip() self.buffer = 'head\r\n' yield 'OK' elif self.dataline[:3] == '421': # err, no next article yield 'DONE' else: yield 'WTF?! fail next' # if self.dataline[:3] == '221': # head print self.dataline.strip() self.head = '' yield 'OK' # XXX what am I going to do if the server explodes while self.dataline <> '.\r\n': self.head += self.dataline yield 'OK' # XXX parse headers here # XXX decide whether we want body self.buffer = 'body\r\n' yield 'OK' else: yield 'WTF?! fail head' # if self.dataline[:3] == '222': # body print self.dataline.strip() self.body = '' yield 'OK' # XXX what am I going to do if the server explodes while self.dataline <> '.\r\n': # XXX line-by-line decode here (someday) self.body += self.dataline yield 'OK' self.decode() self.buffer = 'next\r\n' yield 'OK' else: yield 'WTF?! fail body' def decode(self): """decode message body. try UU first, just decode body then mime, decode head+body save in tempfile if fail""" tempname = 'temp' + `self.n` + '.txt' self.n += 1 file(tempname,'wb').write(self.body) f = file(tempname) try: uu.decode(f) except Exception,v: print 'uu failed code: ',v print 'trying MIME' file(tempname,'wb').write(self.head+self.body) f = file(tempname) message = email.message_from_file(f) for part in message.walk(): print part.get_content_type() filename = part.get_filename() if filename: if not os.path.isfile(filename): file(filename,'wb').write(part.get_payload(decode=True)) print 'yay! MIME!' os.remove(tempname) else: print "oops, we've already got one" else: print 'yay! UU!' os.remove(tempname) def main(): mynews = Newser('news.server',119,'fishboy','pass','alt.binaries') try: asyncore.loop() except KeyboardInterrupt: mynews.del_channel() print 'yay! I quit!' if __name__ == '__main__': main() From Mike at DeleteThis.Geary.com Sat May 22 15:20:20 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 22 May 2004 12:20:20 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> Message-ID: <10av9vknj074bc4@corp.supernews.com> Uri wrote: > I have a file that looks like this: (but longer, no wordwrap) > > Name: Date: Time: Company: Employee Number: > Jim 2.03.04 12:00 JimEnt 4 > Steve 3.04.32 03:00 SteveEnt 5 > > I want to load 'Jim' and '12:00' and those types of answers > into variables in my program, the only delimiter in the file > is whitespace. How do I do this? > > I can do it with string.split(" ",[0]) type line for a file that's > only delimited by single spaces, but when I'm searching > for white space, how do I do it? Use a regular expression. For speed, precompile it at the beginning of your program: reWhitespace = re.compile( r'\s+' ) Then, split each line with: fields = reWhitespace.split( line ) -Mike From breakpoint_break at hotmail.com Wed May 19 12:50:33 2004 From: breakpoint_break at hotmail.com (Kornl) Date: Wed, 19 May 2004 17:50:33 +0100 Subject: n-tier application in Python Message-ID: <2h1hljF7u74vU1@uni-berlin.de> Hello, does anyone has any experience in developing n-tier applications in python? If yes would you like to share your experience? What turn out good and bad?? In your experience, how is a python server capable of handling various simultaneous connections in the context of a n-tier application? I'd also like to ask how is the state of database access and XML libraries on python? From rtarjeft at yahoo.com Sat May 8 13:49:36 2004 From: rtarjeft at yahoo.com (Richard Tarjeft) Date: Sat, 8 May 2004 13:49:36 -0400 Subject: Looking to hire a python programmer Message-ID: <001c01c43524$d4950fd0$6d00a8c0@rmtlaptop> I need to hire a python programmer for a small modification project. Where is the best place to find one? Richard Tarjeft http://www.mlmlead.net http://www.lowcostlocal.com http://www.lower-my-mortgage.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From Hartmut.Wallbrecher at web.de Sat May 22 15:04:45 2004 From: Hartmut.Wallbrecher at web.de (FeU Hagen) Date: Sat, 22 May 2004 21:04:45 +0200 Subject: Determine Whether File Exists On HTTP Server References: Message-ID: This works with HTTP: import sys # exc_info import httplib # HTTPConnection HOST = "www.python.org" PAGE = "/path/to/some/file.html" try: c = httplib.HTTPConnection( HOST ) # c._http_vsn = 10; c._http_vsn_str = "HTTP/1.0" c.connect( ) c.putrequest ( "GET", PAGE ) c.endheaders() r = c.getresponse() print "%s\n%s\n%s\n" % (r.status, r.reason, r.msg) if r.status == 200: # OK print "%s exists" % PAGE PageContent = r.read() # this is the requested html file in a string elif r.status == 404: # not found print "%s does not exist" % PAGE Page404 = r.read() # this is the 404 page in a string else: print "%s : status %s %s %s" % (PAGE, r.status, r.reason, r.msg) except: print sys.exc_info()[1] Greetings Harald Walter "OvErboRed" wrote in message news:Xns94F1EA84483Byangstaoverbored at 127.0.0.1... > Hi, I'm trying to determine whether a given URL exists. I'm new to Python > but I think that urllib is the tool for the job. However, if I give it a > non-existent file, it simply returns the 404 page. Aside from grepping this > for '404', is there a better way to do this? (Preferrably, there is a > solution that can be applied to both HTTP and FTP.) Thanks in advance. From SeeBelow at SeeBelow.Nut Tue May 18 22:14:10 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 19 May 2004 02:14:10 GMT Subject: Python compilers? References: <40AA2C16.C1245362@shaw.ca> <6PSdnRxCG8pxLjfdRVn-hg@powergate.ca> Message-ID: <40AAC308.A3A2B255@shaw.ca> Peter Hansen wrote: > The bottleneck is almost certainly in evaluating the fitness > function, not in performing the mutations and cross-overs. > What does your fitness function do with all those floats? > Perhaps it can be handled much faster with one of the numeric > extensions for Python... or with Pyrex. You are right, the worst bottleneck is the fitness function. Every population member is an ANN (artificial neural network) and the ANNout() function must be called for each fitness evaluation. You can see there is a lot of looping. This C code runs very quickly: ----------------------------------------------------------------------- /* neursubs.c - for computing output of artificial neural network - for EvSail-2.2 M. Timin, August, 2003 piecewise parabolic approximator replaced conventional sigmoid, October, 2003 */ #include #include #define NEUR_MAX 80 /* maximum number of neurons in a layer */ #define LOOP(i,N) for(i=0; i Message-ID: On 2004-05-18, Svein Ove Aas wrote: > Seems to me that you want 'smarter', not 'worse'. I can't take a language > seriously if it says that 1/3 is 0.33333... . Dude, didn't you take high-school math? 1/3 _is_ 0.33333... -- Grant Edwards grante Yow! My forehead feels at like a PACKAGE of moist visi.com CRANBERRIES in a remote FRENCH OUTPOST!! From aahz at pythoncraft.com Thu May 6 12:33:44 2004 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2004 12:33:44 -0400 Subject: classes vs dicts References: Message-ID: In article , Heather Coppersmith wrote: > >In the end (and in the implementation), classes are just syntactic >sugar for dictionaries. > > object.attribute is equiv. to dictionary[ 'key' ] Saying that masks some critically important machinery that classes provide. For example:: class A: x = 'spam' class B(A): pass z = B() print z.x print z.__dict__['x'] That machinery can make classes quite a bit slower in some cases, though you're correct that it's more important to focus on the functional needs than performance. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From michael at foord.net Wed May 12 04:58:14 2004 From: michael at foord.net (Fuzzyman) Date: 12 May 2004 01:58:14 -0700 Subject: newbie question: should I learn TKinter or skip it and learn more advanced toolkit? References: <56cfb0e3.0405111528.b203b78@posting.google.com> Message-ID: <8089854e.0405120058.31babd3e@posting.google.com> porky_pig_jr at my-deja.com (Porky Pig Jr) wrote in message news:<56cfb0e3.0405111528.b203b78 at posting.google.com>... > I'm in a process of digging into Python, and one of the problems I'm > having is whether I should spend any time at all learning TKinter or > skip it and start with more advanced staff like wx or QT. > > I have no experience with GUI whatsoever, so anything will be a > learning experience for me. The reason I've decided to post this > question is that I see some contradictory information in different > resources. > > In 'Programming Python', learning TKinter is recommended -- before you > move to more advanced toolkits. The rationale is (i) it is built-in > and since it is also shared by TCL and Perl, it is well-maintained and > always in sync with the latest version of Python, (ii) it is fairly > simple to learn, small learning curve, easier to grasp some concepts > before moving to more comprehensive production quality toolkit such as > QT. > > In some other resources TKinter is critisized as not well integrated > at Python at all, so recommendation is 'not to waste your time and > start learning GUI with either wx or QT'. > > My intent is *not* to become professional GUI developer, but simply to > get a handle on it, so if I write some utilities, I can provide some > nice GUI if required. Yet of course, since I'm learning something new, > it would be nice to learn it 'right from the start'. > > So: should I spend some time or TKinter or simply skip it and start > learning GUI with something like wx or QT? > > (my background: solid C, enough C++ to understand the OOP concepts, > Perl, too much of it to my liking, BTW) > > TIA. I was faced with the same dilemna - and was about to dive nto wx when my copy of 'Programming Python' arrived through the post. The wx tutorials I had found were a bit obscure - it's possible there are good ones out there... I just failed to find them !! I followed the tutorial on Tkinter in Programming Python - once you've got over the initial learning curve it's not bad and pretty flexible. I've not reached the point yet where Tkinter isn't powerful enough for what I need to do - but then I've only written small apps... nothing huge. *I'd* certainly reccommend starting with Tkinter - when you've got the basics it's very easy to hack together a simple GUI... You can have a look at Nanagram - a python anagram generator that has a Tkinter front end... The whole program is about 20k including comments. (Added to which it's great fun to use - use the link below). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From timr at probo.com Mon May 31 20:40:16 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 31 May 2004 17:40:16 -0700 Subject: API : constness ? References: Message-ID: Beno?t Dejean wrote: >Le Mon, 31 May 2004 11:56:57 +1000, Delaney, Timothy C (Timothy) a >?crit?: > >> Beno?t Dejean wrote: > >>> static const char * const kwlist[] = { "uri", "open_mode", "exclusive", >>> "perm", NULL }; >> >> Does this give any performance or size improvement? > >of course, it avoids a lot of relocation, reduces load time, and manque >the compiler to make further informations because data will be in a >readonly segment. The data MAY be in a read-only segment, but even assuming that it is, that doesn't do anything to reduce relocation or load time. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From chuck.amadi at ntlworld.com Thu May 27 21:11:41 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Fri, 28 May 2004 02:11:41 +0100 Subject: a python script which will parse an email message Message-ID: <40B691CD.1050002@ntlworld.com> any python script which will parse an email messages into a file to poplulate a database. Im trying with UnixMailbox but I cant figure out howto abstract the all email data messages to a file . ## mailbox-Survey.py #!/usr/bin/env python import mailbox,rfc822 # Open Users Mailbox mb = mailbox.UnixMailbox(open("/var/spool/mail/chucka")) while 1: msg = mb.next() if not msg: break for k, v in msg.items(): print k, "=", v body = msg.fp.read() ## built-in function len gives you the length of a list. print len(body), "bytes in body" # Abstract email messages into a tmp file #mb.next() #mb = ("/var/spool/mail/chucka") #mb = sys.stdin Cheers Chuck From peter at engcorp.com Sun May 16 09:52:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 16 May 2004 09:52:11 -0400 Subject: Python and Windows.Forms In-Reply-To: <5foda055796ui1putjgobd28pl8r8q9mh7@4ax.com> References: <87n08qrpcv.fsf@pobox.com> <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> <5foda055796ui1putjgobd28pl8r8q9mh7@4ax.com> Message-ID: Tim Roberts wrote: > Shane wrote: > >>Sorry Tim, I first learned programming with C# so when I said >>Windows.Forms I meant any generic Windows form, and especially common >>dialogs. My mistake! I'm glad I made though since Marijan Tadin pointed >>out that python .NET link that I wasn't aware of (see his reply). Thanks >>again... > > Interesting that this newsgroup is able to answer not only the question you > ASKED, but the question you MEANT to ask... It's the time machine again. Marijan noticed in 2006 that Shane had founded a very successful startup company based on using Python to provide continuing support for legacy technologies that had been abandoned by the original vendor. Their "Safe-T-Net for .NET" (tm) product alone was generating millions in annual revenue. Using the third-generation Google "I Feel Really Lucky" link, Marijan discovered Shane's original question and gave him the answer to the question he should have asked in the first place. This will have had been going to have resulted in a huge increase in the share price for Marijan's stock portfolio, allowing him to retire in comfort to the Cayman's at the age of twenty-two... -Peter From svein+usenet01 at brage.info Tue May 18 10:54:44 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Tue, 18 May 2004 16:54:44 +0200 Subject: Python compilers? References: Message-ID: Brian Quinlan wrote: > Svein Ove Aas wrote: >> Erk. >> Seems to me that you want 'smarter', not 'worse'. I can't take a >> language seriously if it says that 1/3 is 0.33333... . > > What is that? Are you arguing for an integer result, a fixed result or > a rational result? A rational result, of course. If I'm okay with losing precision, I'll *tell* the language I'm okay with losing precision. From claird at lairds.com Fri May 28 07:57:58 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 28 May 2004 11:57:58 -0000 Subject: pdf2txt References: Message-ID: <10beaa626i4o09e@corp.supernews.com> In article , B P wrote: >Is there a way via Python or even Perl to capture records from a pdf and > output a delimited text file? My work has a situation with a trunk . . . -- Cameron Laird Business: http://www.Phaseit.net From miki.tebeka at zoran.com Thu May 13 02:04:29 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 13 May 2004 08:04:29 +0200 Subject: Class instance problem? In-Reply-To: References: Message-ID: <40A30FED.7010307@zoran.com> Hello Zhao, > class aclass: > num = 0 > l = [[],[]] > > a = aclass() > b = aclass() > a.l.append(1) > print "a.l",a.l > print "b.l",b.l > > My expectation is that a,b are separate objects, but appending to > a's l also appends to b's l. Why does this occur? On the other hand, > the command > > a.num = 1 > > doesn't change b.num's. This is inconsistency is driving me crazy. > What am I doing wrong? Several things :-) First, "num" and "l" are both *class* properties and not object properties. The right way to do this is: class aclass: def __init__(self): num = 0 l = [[], []] Each class method has a `self' parameter which is the object that is currently called. See the tutorial for more explanation on the subject. Second "num" and "l" are named bounded to the same objects objects both in a and b. When you do `a.num =1' you change the binding of a.num to 1. When you do a.l.append you append to the same objects as in b.l. HTH. Miki From jason at __nospam__mobarak.name Wed May 19 13:26:40 2004 From: jason at __nospam__mobarak.name (Jason Mobarak) Date: Wed, 19 May 2004 11:26:40 -0600 Subject: sample code for wxpython/twisted In-Reply-To: <425cc8d1.0405190904.4b92a20b@posting.google.com> References: <425cc8d1.0405190904.4b92a20b@posting.google.com> Message-ID: mir nazim wrote: > hi, hello, > > i am new to python but not new to programming. i am a php > developer(with some c/c++ under by belt). to let u know the level of > programming experience i have (so that u can help me better, no > arrogance intended), i have developed a web based adaptive testing > system, a sale/stock/inventory/ management system and am currently > working on a web based school management system, all in php. > > now i and my team want to shift to python. i will first shift to > python the my team members. > > i have been doing python(language only) for quite a good time. by now > i feel little confident with python and i want to try my hands on some > larger/real life things. i want to learn wxPython and twisted. > > but my problem is that i am unable to locate some project that uses > wxPython or twisted. i would like to know about some open source > projects which address the needs businesses wxPython/twisted. for > example an small accounting package,point of sale system, a hotel > management system, a groupware system etc. > > it is not necessary that wxPython and twisted must used in the same > project. can be two different projects. my point is that i want to > learn both. i am look for some good quality code to get started. i > have seen the wxPython demos but am not satisfied. > > if any one of u can point me to the projects that use wxPython or > twisted or both. best if it not a too big project that a beginner like > me will get overwhelmed. > > Thanks in advance for any help. > > --------------- > Mir Nazim. > Lead Developer. > XenSoft, Inc. > Kashmir(India). Try the Twisted mailing list [0]. Also, Quotient [1] is a big project written with Twisted. I'm writing a web application with Twisted and Nevow [2], but I'm not ready to advertise it :) 0 - http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python 1 - http://www.divmod.org/Home/Projects/Quotient/index.html 2 - http://nevow.com/ From catcher at linuxmail.org Sun May 2 19:51:33 2004 From: catcher at linuxmail.org (Robert) Date: Sun, 02 May 2004 19:51:33 -0400 Subject: IDE for Python In-Reply-To: References: Message-ID: dont bother wrote: > Hi Guys: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but > to my surprise its just an editor. I guess it cannot > even compile my code in python or maybe I am wrong. > Any ideas/recommendations for a free IDE for Python > Thanks > Dont > Try SciTE...it's simple and easy to use. From yazzoo at null.net Mon May 24 23:32:15 2004 From: yazzoo at null.net (yazzoo) Date: Tue, 25 May 2004 03:32:15 GMT Subject: smtplib data error In-Reply-To: References: Message-ID: <37zsc.16577$SQ2.1218@edtnps89> Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina wrote: > If the drugs i got are still working, `550' error code stands "No soup for > you!!" (Relaying Denied). Maybe the IP in your web server is not into the > sendmail's access configuration file. > > Gerardo > > >>Does anyone know what causes an SMTPLIB DataError? >> >>The only thing I can find in the manual is >>exception SMTPDataError >> The SMTP server refused to accept the message data. >> >>My problem is a previously functioning script suddenly failed last week. >> My ISP thinks it maybe something to do with upgrading CPanel on their >>server -- maybe a library was missed, but when I try and execute a >>script I get... >> >>Traceback (most recent call last): File "test-py.cgi", line 790, in ? >>sendemail(EmailFrom, EmailTo, emsg) File "test-py.cgi", line 20, in >>sendemail failed = server.sendmail(EmailFrom, EmailTo, emsg) File >>"/usr/lib/python2.2/smtplib.py", line 685, in sendmail raise >>SMTPDataError(code, resp) smtplib.SMTPDataError: (550, 'Administrative >>prohibition') >> >>Thanks for any suggestions. >> >>Lester. > > Thanks, it turns out that the ISP upgraded their smtp server software which breaks smtplib, I guess. They suggest I use sendmail. The traceback above though seems to suggest that smtplib uses sendmail, so I don't know whether this will resolve or not Thanks again for your suggestions Lester From me at privacy.net Wed May 12 16:54:58 2004 From: me at privacy.net (Duncan Booth) Date: 12 May 2004 20:54:58 GMT Subject: max value in list References: Message-ID: "Terry Reedy" wrote in news:mailman.462.1084374987.25742.python-list at python.org: > Sidestepping 'best' which may depend on context, a general 'good' way is > >>>> lists = [2,3,4],[1,2,3],[4,7] >>>> max([max(l) for l in lists]) > 7 > Without any claims to better or worse, here is another option: >>> l = [2,3,4],[1,2,3],[4,7] >>> l ([2, 3, 4], [1, 2, 3], [4, 7]) >>> max(itertools.chain(*l)) 7 >>> From olli at secnetix.de Mon May 10 17:57:55 2004 From: olli at secnetix.de (olli at secnetix.de) Date: 10 May 2004 21:57:55 GMT Subject: Inverse of int(s, base)? Message-ID: <2gac73Fk1ooU1@uni-berlin.de> Hi, Is there an inverse function of int(s, base) where base can be any number up to 36? I've searched the library reference up and down, but haven't found anything. For example, I need to work with base-24 numbers, which can be parsed nicely with x = int(s, 24), but there doesn't seem to be a way to convert integers back to their base-24 representation as a string. (Of course, I can define my own function in Python to do that, but I wonder if there's a more efficient way.) Best regards Oliver PS: This is what I'm using right now. import string str_digits = string.digits + string.ascii_lowercase def str_base (x, base): result = "" while x: result = str_digits[x % base] + result x /= base return result or "0" >>> print str_base(2065027084, 24) aj83kb4 >>> int("aj83kb4", 24) 2065027084 -- Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 M?nchen Any opinions expressed in this message may be personal to the author and may not necessarily reflect the opinions of secnetix in any way. "Clear perl code is better than unclear awk code; but NOTHING comes close to unclear perl code" (taken from comp.lang.awk FAQ) From linuxarticles at yahoo.com Mon May 17 11:36:24 2004 From: linuxarticles at yahoo.com (noviceUser) Date: 17 May 2004 08:36:24 -0700 Subject: HTTP 1.1 pipelining Message-ID: <4860c084.0405170736.13c6e8b4@posting.google.com> can some one guide me how to use HTTP 1.1 pipelining in Python. Client will generate 3 get requests continuously as shown below and then read the response for each GET request. Algorithm ---------- GET(ur1_l) GET(url_2) GET(url_3) readResponse(url_1) readResponse(url_2) readResponse(url_3) i m a python newbie and pls forgive me if this question sounds silly. thanks in advance for any help. From lesstif-admin at lesstif.org Mon May 17 03:06:18 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Mon, 17 May 2004 07:06:18 -0000 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "my advice...." has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From mirandacascade at yahoo.com Sun May 23 17:21:21 2004 From: mirandacascade at yahoo.com (Miranda Evans) Date: 23 May 2004 14:21:21 -0700 Subject: pywin.mfc, win32ui, Windows common dialogs Message-ID: <59e5b87.0405231321.2df9af43@posting.google.com> Below is a copy/paste of a paragraph from a posting: "You can access all the Windows common dialogs (forms?) Python by using Win32 extensions. Specifically using pywin.mfc dialog and win32ui modules." My questions are: 1) is a combo box control something that is part of the set of stuff that is referred to as 'all the Windows common dialogs'? 2) if so, is there any sample code available in which a combo box control is accessed from the pywin.mfc dialog and win32ui modules? if so, where can I find this sample code? From tdelaney at avaya.com Sun May 30 20:19:07 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 31 May 2004 10:19:07 +1000 Subject: python crash Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01880705@au3010avexu1.global.avaya.com> whydoineedaname wrote: > for like the last week the python shell keeps crashing and wont load > when i try to open it and also when i tried to run some simple aps it > crashes > > does anyone know how to fix this??? This will help you find an answer to your problem. http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From mcherm at mcherm.com Mon May 3 14:27:14 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Mon, 3 May 2004 11:27:14 -0700 Subject: Embedded comments in Python? Message-ID: <1083608834.40968f02bca2e@mcherm.com> Ernie writes: > Whats the legal way in Python to embed comments in Python code? [...] > In C/C++, this would be no problem with /* */. Python has no way of producing these sorts of comments.[1] I suggest putting the comments either above the line or below it. In the case of type specifications, I suggest describing the expected types in your docstring, unless you use a framework to actually validate the types, in which case the format you use will depend on the framework. -- Michael Chermside [1] - Well, almost. I suppose there *IS* actually a way of inserting a comment between two Python tokens. Simply preceed the comment with "\\\n#" (a backslash, a newline, and a hash) and follow it with "\\\n" (a backslash and a newline). I *think* this works between any two tokens... right? From mwh at python.net Thu May 13 09:09:47 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 13 May 2004 13:09:47 GMT Subject: Python - open forever ? References: Message-ID: "Romans Krjukovs" writes: > Hi ! > > Our company is going to start use Python widely. > To make this reality we have to include Python in our strategy > plans for at least 3 nearest years. > This would be a green light to our developers to start new projects on > Python. > > At the presentation of Python and its usage posiibilities in our > home environment to the members of the project managers board, > we got such questions: > - There is a risk that Python can become closed and unsupported in the > future. Exceedingly unlikely. > - Who can guarantee that Python will be usable and available to us > if it is develeped and maintained by the hackers from all over the > world without any obligations and guarantees ? Well, noone really. But who guarantees such things for any other bit of software you use? > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) Are you aware of the PSF? http://www.python.org/psf/ If handing out money would make you feel more secure, that's where it should go. Cheers, mwh -- In that case I suggest that to get the correct image you look at the screen from inside the monitor whilst standing on your head. -- James Bonfield, http://www.ioccc.org/2000/rince.hint From gnosticray at aol.com Tue May 11 03:01:20 2004 From: gnosticray at aol.com (A B Carter) Date: 11 May 2004 00:01:20 -0700 Subject: efficient list reduction Message-ID: I have two lists. The values of the second list can be viewed as keys for the first. I want to create a newlist based on the implied mapping. The straight Python code would be: newlist=[] for key in keys: newlist.append(oldlist[key]) What's the most efficient way of doing this? The best I could do was the following list comprehension: [oldlist[key] for key in keys] Have I missed something? Regards, A B Carter From mcfletch at rogers.com Fri May 14 11:56:57 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 14 May 2004 11:56:57 -0400 Subject: Stackless python and microthreads In-Reply-To: <95aa1afa.0405140121.52a6d8e0@posting.google.com> References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> Message-ID: <40A4EC49.2000408@rogers.com> Michele Simionato wrote: >"Mike C. Fletcher" wrote in message news:... > > >>Continuations (which are the coolest things since programming was >>invented) >> >> ... >However, to pass from continuations to something useful takes a >LONG way. Continuations are a too low level concept. A high level language >should already provide the right high level tools. I mean, the language >designer should implement generators, exception systems, microthreads, etc. >not the application programmer. When you have the high level concepts written >down by others, you don't need continuations. > > Except we did ;) . When we sat down to start working with micro-threads, they were (for our purposes) extremely heavy beasts when they were sleeping and scheduling themselves. So, having a simple Python implementation built out of continuations, we were able to say "hey, we can fix that cheaply" and dedicate a few weeks of work to the project to improve the implementation. Guido may be omniscient ;) , but I don't think he's achieved omnipotence. He and the python-dev crowd can't, and *won't* implement many things that people writing frameworks *need* (and really, in many cases, they shouldn't be doing it anyway until the idea proves itself). Having a building block such as continuations exposed allows framework developers/meta-programmers the chance to experiment with new flow-control structures and to do that experimentation *in a high-level language* (does this sound familiar to all the PyPy peoples). >So I guess now Stackless has microthreads built inside, and the application >programmer is not forced to write them on top of continations. > > Sure, but it was never the app programmer that did it anyway, so let's leave them out of this. Using Python does not automatically mean you are an applications programmer rather than a framework developer or meta-programmer (btw, nothing wrong with being an apps programmer, it's just a different type of work). Python isn't *just* a scripting language either ;) . >Speaking in general, generators and the current exception system are more >than enough for my typical needs in Python: which kind of applications do >you have in mind where you would like to have continuations? (a part from >microthreads and things like changing the language introducing new >control structures, etc, all stuff than should not be left to the >application programmer, IMHO). > > Why make that kind of experimentation difficult just to erect a barrier between user and developer? Python isn't a place to keep every powerful tool from the plebeian masses just because they might hurt themselves. Heck, if we're going to do that, what the heck are we exposing metaclasses for (and really, would the two of us be happy if they took away our metaclasses)? There are framework developers/meta-programmers using Python who just aren't interested in working in C code any more. Giving them tools is *not* a bad thing. Regarding applications; restartable exceptions, micro-threads, long-running-calculation restarts, migrating running code across machines, and creating new methods of parsing all seem like experiments that would benefit from having continuations available to ease implementation. Any of those is a thing that an app programmer might want/need, and be willing to have a meta-programmer create for them... why force that work into C code needlessly? However, continuations are dead, and though I may mourn them, I'm not interested in trying to resurrect them. At the moment my company's current contracts would only be interested in are micro-threads; and even there, we aren't really interested enough to switch from our already-built frameworks; just too much inertia. Too bad, because a micro-threaded networking environment is the closest thing I've ever seen to the promised land for networking... garn I miss working on that. Peace all, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From jerry.levan at eku.edu Thu May 13 15:42:40 2004 From: jerry.levan at eku.edu (Jerry) Date: 13 May 2004 12:42:40 -0700 Subject: Mac OS X and jpeg support.... Message-ID: <46850fd1.0405131142.5ff1d525@posting.google.com> Hi, I am (today!) starting to Python... I am runnin MacOS X 10.3.3 with: 1) "Batteries included" Aqua Tcl/Tk version 8.4.5 2) The 2.3 version of Python that comes with the OS 3) The "Panther Additions for MacOS X" package I have used the package manager to install Tkinter. I ran a couple of examples and Tkinter seems to work. I tried installing via the package manage the PIL package and trying to do anything with jpegs fails....I noticed that I did not have libjpeg installed. I got the jpg-6b package and created libjpeg.dylib in /usr/local/lib. I tore out the PIL stuff from /Library and reinstalled the PIL package via the package manager....I still get failures when trying to display a jpeg file ( format not recognized...) Here is a simple program I am trying to use... #!/usr/bin/python from Tkinter import * import Image import sys def main(): filename = sys.argv[1] root = Tk() img = PhotoImage(file=filename) label = Label(root, image=img) label.pack() root.mainloop() main() The program will do gifs ok... How can I get jpeg support going? Jerry From mb at muenster.de Wed May 19 15:35:30 2004 From: mb at muenster.de (Martin Bless) Date: Wed, 19 May 2004 19:35:30 GMT Subject: CSV: minimalquoting and skipinitialspace, References: <40ac2eba.12454921@news.versatel.de> Message-ID: <40abb44b.10129750@news.muenster.de> [Skip Montanaro ] >Can you post a feature request to the Python >project on SF? Ok, I think I can do that. Having thought it over I'd love to see this logic: # pseudo code, untested if dialect.quoteminimal: quote_the_field = False if dialect.delimiter in field: quote_the_field = True elif dialect.separator in field: quote_the_field = True # NEW: do quoting if field starts OR ends with a space or a tab elif field[:1] in " \t" or field[-1:] in " \t": quote_the_field = True >Even better would be a patch that implements the idea. ;-) Too bad, I can't. I had a look at it: the crucial parts are in the c-code. That's too far for me in the moment ... MB - Martin Bless From beliavsky at aol.com Tue May 11 09:53:00 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 11 May 2004 06:53:00 -0700 Subject: [numarray] mean vector of 2d matrix References: <409f9edd$1@maser.urz.unibas.ch> Message-ID: <3064b51d.0405110553.7ee2468a@posting.google.com> Curzio Basso wrote in message news:<409f9edd$1 at maser.urz.unibas.ch>... > Hi all, > > I was wondering what is the best way to compute the mean vector of a > matrix. Currently I'm doing this: With Numeric, one can use the 'average' function to compute the average along an axis, or the average of all elements when the axis argument is set to None. See p317 of Martelli's "Python in a Nutshell" book. For example, the code from Numeric import zeros,Float,average nr = 3 nc = 2 xx = zeros([nr,nc],Float) for i in range(nr): for j in range(nc): xx[i,j] = i + 10.0*j print xx for i in [None,0,1]: print "\n",i,average(xx,axis=i) produces output [[ 0. 10.] [ 1. 11.] [ 2. 12.]] None 6.0 0 [ 1. 11.] 1 [ 5. 6. 7.] From rjt-usenet at thegrindstone.me.uk Fri May 7 11:41:00 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Fri, 07 May 2004 16:41:00 +0100 Subject: usage/future status of PyProtocols Message-ID: <409bae0d$0$12099$fa0fcedb@lovejoy.zen.co.uk> We are considering making use of the PyProtocols (http://peak.telecommunity.com/PyProtocols.html) package. I have read through the documentation and it appears to offer much of what we want. I have already used both Zope's and Twisted's interface implementations to a greater or less extent in existing projects and I have been a bit disappointed that no 'standard' approach to interfaces has appeared in the Python libraries. Before jumping into PyProtocols I was wondering: Are other people using it in real projects? What are their experiences regarding payback for effort expended? Does anyone know if there are plans to include a 'standard' approach to interfaces/protocols in the Python library? If so, is it likely that it will be PyProtocols? I just don't want to spend a lot of time, and persuade my team members to use a package that is then superseded by a different approach in a future standard library package. Regards Richard From dmq at gain.com Thu May 6 19:00:16 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 06 May 2004 16:00:16 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> Message-ID: On 6 May 2004 08:37:50 -0700, moughanj at tcd.ie (James Moughan) wrote: > David MacQuigg wrote: >>Have you read the explanations of instance variables at the end >> of http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm >> Does this change your thinking? >> >> Explanation of Simplified Instance Variables >> -------------------------------------------- >> """ Some of the variables inside the functions in a prototype have a >> leading dot. This is to distinguish local variables in the function >> from "instance variables". When a function is called from an instance >> ( cat1.talk() ) a special global variable __self__ is automatically >> assigned to that instance ( __self__ = cat1 ) Then when the function >> needs an instance variable ( .sound ) it uses __self__ just as if you >> had typed it in front of the dot ( __self__.sound ) The leading dot >> is just an abbreviation to avoid typing __self__ everywhere. """ > >The changes would go beyond a simple change of syntax; it would break >the python functional object model, e.g. as you couldn't write a >global function and assign it to a class at runtime. (I'm not saying >this is a good thing to do :) I'm saying that this is not a trivial >matter of syntax.) I don't want to argue implementation details, as I am no expert, but I think you are saying something is wrong at the user level, and that puzzles me. A global function, if I understand your terminology correctly, is one defined at the module level, outside of any class. Such a function cannot have instance variables. If you were to reference that function from within a class, it would just act as a normal function (a static method in Python terminology). I can't see the problem. >>> def global_func(x): print x >>> class Cat: f = global_func f = staticmethod(f) >>> Cat.f('hello') hello The difference in the proposed syntax is that it doesn't need the staticmethod wrapper to tell the interpreter -- don't expect a special first argument. In the new syntax all functions/methods will have the same calling sequence. >> Python is clearly superior to C++ and Java for what I need ( teaching >> EE students and professional engineers ). Still, it isn't perfect. I >> believe a good presentation of OOP could be done in 50 pages ( about >> half of what is now in Learning Python, 2nd ed.) > >I believe a good working introduction could be done in 10, at most. >OOP is not complex. It's even simple enough for managers to (think >they) understand, which leads the slightly bizzare state of >programming today. I've looked at a few introductions to Python, and in my opinion Learning Python, 2nd ed, by Mark Lutz and David Ascher is the best. It strikes a good balance between the minimal presentation that tersely covers the essentials for an experienced programmer vs the long, windy introductions that put you to sleep with analogies to car parts and other "objects". Lutz takes 95 pages to cover OOP. I think I could do a little better, maybe 70 pages, but that may be just my ego :>) When you say ten pages, you must be making some very different assumptions about the students or their prior background, or the desired level of proficiency. The least I can imagine is about 30 pages, if we include exercises and examples. And that 30 assumes we get rid of all the unneccesary complexity (static methods, lambdas, etc.) that currently fills the pages of Learning Python. >> The key to this simplification is not having to discuss static methods >> or any other method form. All methods are called just like normal >> functions, which the students already understand at this point in the >> course. > >They are already called like normal functions, though. You can >copy-paste a method as a global function and it will still work. Your >syntax introduces a special case which makes them distinct, by use of >a specific method-only dot notation. Wow!! This is the complete opposite of what I am seeing. I see functions and methods *not* having the same calling sequence. You need to add the special first argument with most methods. You *cannot* just copy and paste a global function into a class without adding that special first argument, or the staticmethod wrapper. >> I think the learning process you describe above is quite common. I >> went through the same initial steps. At first I was puzzled by the >> strange 'self' first argument, and annoyed at typing 'self' in so many >> places. Then I understood the magic first argument, and got used to >> the extra typing. It did not occur to me that there was some >> unnecessary complexity yet to come. I had not yet seen how 'self' is >> handled in Ruby and in Prothon. I did not learn about static methods >> and other forms until much later, and 'lambdas' were something weird >> related to "lambda calculus". > >There are static methods in Python? :) In my coding the major reason >for static methods is for data encapsulation for singleton-style >elements. Python has no data encapsulation worth anything, so static >methods don't do much that's useful. We have the usual dose of terminology problems here. The term 'static method' in Python may be different than in other languages. In Python it just means a method that has no instance variables, no special first argument, and an extra 'staticmethod' line, to tell the interpreter not to expect a special first argument. Python does have "encapsulation" but does not have "hiding", by my understanding of these words. The idea is that __private variables are easily identified to avoid accidents, but there is no attempt to stop deliberate access to such variables. This is a design philosophy that I like. >> The second problem with the "avoidance/denial" strategy is that it >> involves moving the troublesome functions outside of the class >> definition. This results in a less-than-optimal structure for your >> program. Look at the show() methods in Animals_2.py They must be >> callable without any specific instance. Moving them outside the >> appropriate classes is not good programming. When you want to change >> a class later, you will need to remember to look in some other place >> for any "static methods" associated with the class. >> >> If you could do me one more favor, please take a look at the >> Animals_2.py example starting on page 7 of the Prototypes document at >> http://ece.arizona.edu/~edatools/Python Can you write this in Python? >> Give it a try, and let me know if you had any difficulties. Were >> there any parts you had to stop and think, or look up in a manual? >> > >I am not copy-pasting the whole thing, but I think this demonstrates >the functionality you want. It ain't pretty, but I'll discuss that in >a second. > >class static: > def __init__(self, fun): > self.__call__ = fun > >class Mammal: > > numMammals = 0 > > def __init__(self): > Mammal.numMammals += 1 > > def show(): > print "Inventory:" > print " Mammals:", Mammal.numMammals > > show = static(show) > >class Feline(Mammal): > > numFelines = 0 > > def __init__(self): > Feline.numFelines += 1 > Mammal.__init__(self) > > > def show(): > Mammal.show() > print " Felines:", Feline.numFelines > > show = static(show) > > >m = Mammal() >f = Feline() >print Mammal.numMammals, Feline.numFelines, '\n' > >Feline.show() > > >I must note that Animals_2 is a total abuse of OOP techniques. You >continuously define classes to do the same thing, repeat the same code >in each, then give them slightly different names. This is a textbook introduction, not a real program. The purpose of the example is to show a complete OOP hierarchy in a small example, with a good selection of the method styles most needed in a real program. The similarity between the show() methods in different classes would not be so tempting to reduce to one global function if I had made a larger example, with more radically different outputs from each show function. I thought that just changing one string in each function would be enough to say "This function is different." You are not the only one who had this reaction. See my reply to Don Cave above. I guess I need to thow in a little more "meat", so that experienced programmers don't get distracted by the possibility of making the whole program simpler by taking advantage of its regularities. This is the same problem I've seen in many texts on OOP. You really can't see the advantages of OOP in a short example if you look at it with the attitude -- I can do that much more easily without classes. It's when you get to really big complex hierarchies that the advantages of OOP become clear. >Also, your show method is IMO more than dubious. show does not >logically belong to Feline. As a result you are using a class to >display data about other classes to which it is not connected. This >is not OOP. I thought this part was pretty clear. The show() method at each level calls the show() method one level up, then adds its own stuff at the end. Feline.show() calls Mammal.show(), which prints lots of stuff characteristic of mammals, all in a format unique to the Mammal class. Mammal.show() in turn calls Animal.show(). At each level we have some unique display of characteristics. The purpose is to have a call at a particular level show all characteristics of the animal from that level up. >If I were teaching someone and they produced this structure then I'd >go over the rationale with them and try to figure out where they went >wrong in their planning of the program, and maybe go back and tutor >them on the basic ideas of OOP. I would not change the language to >make it easier to do in future. :) Both responses I have on this are basically experts saying -- you can solve this particular problem more easily by restructuring it. I should have been more clear. Imagine that each of these classes and methods is fully expanded with lots of parameters to make each one unique. Don't even think about re-structuring, unless you are trying to tell me that the whole idea of having these structures in any program is wrong. That would surprise me, since this "animals" example is a common illustration of OOP. What I'm looking for is not clever re-structuring, but just a straightforward translation, and some comments along the way -- oh yes, that is a little awkward having to use a staticmethod here. Wow, you mean staticmethods aren't fundamentally necessary, just a bandaid to make up for Python's deficiencies? That was my reaction when I first saw Prothon. Thanks again for your feedback. -- Dave From joewong at mango.cc Fri May 21 21:18:33 2004 From: joewong at mango.cc (Joe Wong) Date: Sat, 22 May 2004 09:18:33 +0800 Subject: how to terminate a process on win32? Message-ID: <001c01c43f9a$b3d8a650$7f00a8c0@scl01.siliconcreation.com> Hi, I am developing two app on Windows, one is a GUI using wxPython and the other is like a daemon process. The GUI app will have a start/stop button to control the excution of the daemon. While I know how to use os.popen2() to start my daemon, I can't figure out a way to stop it 'nicely'... Is there anything that I can do? Regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Mon May 3 19:23:28 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 May 2004 19:23:28 -0400 Subject: PEP 328 update References: <109d87iiu30ct7a@news.supernews.com> Message-ID: In article <109d87iiu30ct7a at news.supernews.com>, John Roth wrote: > >I also don't particularly see the reason for banning the relative form >from raw import statements. Did you see the rationale toward the end? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From rtrocca_NO_SPAM_ at divitech.it Tue May 18 09:13:48 2004 From: rtrocca_NO_SPAM_ at divitech.it (Riccardo) Date: Tue, 18 May 2004 15:13:48 +0200 Subject: pyVideoIO source release Message-ID: <2gugfoF6p9rhU1@uni-berlin.de> Hello, after a long time I'm releasing my extension to read AVI files, QuickTime and connect to WebCameras under win32. I do not have much time to create a decent website by now, therefore I released the sources and a binary for python 2.3 just to be prompted to do more. If somebody will find this useful I'll add any contribution I receive. the URL is: www.geocities.com/rtrocca/python Well, sorry for the lack of more information, I'll add docs and other stuff in the future. Riccardo From devilwolf22 at hotmail.com Thu May 6 16:48:33 2004 From: devilwolf22 at hotmail.com (Steve Menard) Date: Thu, 06 May 2004 16:48:33 -0400 Subject: Debuggin a ptyhon extension Message-ID: I am writing a python extension module in VC++ on windows. At some point, my extension crashes. Now I want to debug exactly why. I built the python projects in VC++, and put the resulting python_d.exe in my ptyon home directory, and the python23_d.dll in the windows/system32 directory. I also tried to put the python23_d.dll in python's home directory, to the same result. Problem is, running my scripts/extension with python_d.exe, it always complains it can't find win32api. Yes, I am using win32API to preload a dll, and can't really get rid of it. To try and solve this, I tried replacing the "stock" python.dll with my python_d, so at least VC++'s debugger would see the debug info. but I got the same result, of win32api not being found ... What is the best way to go about this? My extension will require a fair amount of native code and interacting with the Python code, so being able to trace into python would be invaluable. Are my problems caused because python 2.3.3 (and possible win32all) were build using VC.net? I am grateful for any help you guys can provide. Steve Menard devilwol22 at hotmail.com From vmilitaru at sympatico.ca Tue May 11 06:07:15 2004 From: vmilitaru at sympatico.ca (Vio) Date: Tue, 11 May 2004 06:07:15 -0400 Subject: Several questions about embedding Python Message-ID: <40A0A5D3.9010704@sympatico.ca> My understanding is that SWIG produces c/cxx source code, it doesn't compile your code. And nothing prevents you from linking statically, if you have problems with shared libs. Vio From donn at u.washington.edu Mon May 24 14:51:37 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 24 May 2004 11:51:37 -0700 Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> Message-ID: In article <7u94b0hi6mgfbdipirk03dksovmkd6886u at 4ax.com>, Arthur wrote: > Sorry folks, the dunamics here really interest me. It is simply group > dynamics in the circumstances of a strong individual leader. I don't > mean to be in finger pointing, or hysterics mode. > > But backing up, and re-reading the python-dev thread from which this > all starts, I think there is one other factor. > > Simply that the distinction being drawn by Guido was - I'm thinking - > formed prior to new style classes, and attendent changes to the > language. And that it was more meaningful once, than it is now is. > > Certainly a programming language like Python is tightly woven and it > should be no real surprise that changes to the language as fundamental > as occurred since 1.5.2 - not directly related to lists or tuples - > would impact the conceptualization and language with which might most > appropriate in describing these structures. That's reasonable, but can you explain your hypothesis? Like, what is it about the current class/type structure that has anything to do with this? I don't see it. As far as the group dynamics & Guido go, you can probably forget that. There are all kinds of things going on, and that could play a role, but only a weak one. People have a lot of strong opinions about programming languages, and if people here seem to find it easy to agree with Guido, the simplest explanation is that they choose to use Python and hang out on comp.lang.python because they like it. As long as he keeps singing basically the same tune, they'll like what they hear. If he were to take off in some really different direction - like imagine he announces that Python 3 will have strong static typing - the majority would be outraged and the rest would be the minority who always did wish that were the case. In fact I think this has something to do with the present issue - the notion of a homogeneous list is very familiar to users of statically typed languages, where it means exactly what it wasn't supposed to mean here. To a defender of the faith, them's fightin' words, regardless of who said it. Donn Cave, donn at u.washington.edu From tjreedy at udel.edu Mon May 10 13:17:15 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2004 13:17:15 -0400 Subject: dynamic function References: Message-ID: "Xaver Hinterhuber" wrote in message news:c7ngg7$p1$1 at online.de... > Hello pythonistas, > > I have programmed a product in Zope which allows me to source code on the > web. > Now I want to compile the code into a function and execute the function. If the source is a comple def statement with a know name... >>> exec "def f(): return 'this works'" >>> f() 'this works' Terry J. Reedy From nospam at mega-nerd.com Sun May 2 04:35:47 2004 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 02 May 2004 18:35:47 +1000 Subject: Passing data between threads Message-ID: <4094B2E3.E802F8D2@mega-nerd.com> Hi all, I have a script where I create a thread using the thread module. The thread runs its course and then calls thread.exit (). However, I'd like to pass some data back to the parent thread before alling thread.exit () but I can't figure out how. Any ideas? Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "It's far too easy to make fun of Microsoft products, but it takes a real man to make them work, and a god to make them do anything useful" -- Anonymous From collin_sq2003 at yahoo.com Thu May 20 02:28:36 2004 From: collin_sq2003 at yahoo.com (xunil) Date: 19 May 2004 23:28:36 -0700 Subject: socket programming question Message-ID: <81dff960.0405192228.1e94f3b@posting.google.com> assuming am sitted on my PC, and want to be notified when some one else logs on to his machine. throught some kind of pop-up how can i use C socket programming concepts to achieve this ? From paul at prescod.net Tue May 25 10:21:27 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 25 May 2004 07:21:27 -0700 Subject: Prothon should not borrow Python strings! In-Reply-To: <2hfv4nFch1lmU3@uni-berlin.de> References: <2hfv4nFch1lmU3@uni-berlin.de> Message-ID: <40B35667.90802@prescod.net> Greg Ewing wrote: > Paul Prescod wrote: > >> The result of reading a file is a binary data string. The result of >> parsing an XML file is a character string. > > > What if the file you're reading is a text file? In the most rigorously consistent model, you would decode the data, just as if you were reading a file that happened to be constructed of a list of integers. But of course there are a variety of shortcuts you could implement, like a "text file" object or a "read as ASCII" flag for a file object or ... practicality beats purity. Paul Prescod From rogerb at rogerbinns.com Fri May 14 17:29:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 14 May 2004 14:29:07 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 References: Message-ID: <1aqfn1-id2.ln1@home.rogerbinns.com> Hornberger, Chris wrote: > > WINDOWS > > ... Windows users may also be > > interested in Mark Hammond's win32all, a collection of > > Windows-specific extensions including COM support and Pythonwin, an > > IDE built using Windows components. > > > > PS... I have moral and ethical arguments against this. I believe it's just plain WRONG to use a language like Python or Java or > even C#/.NET and RELY on platform specific "extensions". That may be the case for code you write. But your morals and ethics don't apply to code I write. And win32all isn't a mandatory download. You also ignore the fact that Python includes UNIX specific extensions. For example it includes the UNIX process creation stuff (fork, exec) and UNIX serial port stuff (ioctl, fcntl). On Windows, you have to get the equivalent from win32all. And if you happen to use a Mac, or an AS/400 then they need platform specific stuff as well. win32all also includes APIs to manage dial up connections. There is no equivalent API under UNIX. So should everyone ignore stuff that isn't the lowest common denominator? Roger From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu May 13 11:32:33 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 13 May 2004 17:32:33 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: References: Message-ID: <40a39511$0$560$e4fe514c@news.xs4all.nl> Anthony Baxter wrote: > On behalf of the Python development team and the Python community, I'm > happy to announce the release of Python 2.3.4 (release candidate 1). Cool! Thanks. I've got a question though, I've submitted a patch for a bug in SimpleHTTPServer.py in december last year; http://sourceforge.net/tracker/?func=detail&aid=839496&group_id=5470&atid=305470 SimpleHTTPServer reports a wrong content-length of text files on windows The bug is still there in this release. Any change of getting my patch applied? --Irmen de Jong. From newsgroups at jhrothjr.com Sat May 22 12:45:18 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 22 May 2004 12:45:18 -0400 Subject: Running code on module import References: <20040521050534.21796.00001788@mb-m15.aol.com> Message-ID: <10av0tnnpv79c3c@news.supernews.com> "Grant D. Watson" wrote in message news:20040521050534.21796.00001788 at mb-m15.aol.com... > If this has been answered before, or if my terminology is off, please bear with > me; my Python experience is limited to use in one class and to personal > projects. > > I'd like to do something rather silly: I'd like to run a particular piece of > code from a given module every time that the module is imported, and not just > at the time that the module is originally loaded. So, every time a module says > import foo > or something analogous, I want foo.doYourThing() to be invoked, in addition to > the usual effects on the importing module's namespace. Look at the built-in __import__() function, and the ihooks module. For what you want to do, you should be able to hook __import__ so that you get control both before and after it. John Roth > Grant D. Watson > grant_watson at yahoo.pleasedontspamme.com (Use this one!) From BruceWhoHKL at gawab.com Wed May 12 21:32:25 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Thu, 13 May 2004 09:32:25 +0800 Subject: question on Bdb??? Message-ID: Hi ,all recently I'm trying to write a vim script to integrate python debugger in to vim so that I can debugger python script in vim. But I come across a question. First I need to write a derived class of Bdb, so I must override the user_* methods.but how can I return to vim? When user_* is called , it should return to vim, and when the user 'step' or 'next', it return to the user_* call again, and run. But how to achieve this? It's apparently I need to 'freeze' the Bdb and wait for some input coming from vim ,and then go back to the right place. but we can't make vim functions as callbacks. That's the question. maybe iterator/generator can be used to solve it. But I don't know how. Any one can help me? Any suggestions are appreciated. ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-13 From rogerb at rogerbinns.com Mon May 24 14:54:47 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 24 May 2004 11:54:47 -0700 Subject: Multimedia extensions Framework References: Message-ID: Dmitry Borisov wrote: > At this time bullets 1-3 are implemented at 90%( http://pymedia.sourceforge.net ). > Some functionality still in test, some still needs to be written. External interfaces are also needed. For example I need to convery to/from Qualcomm's PureVoice format. They conveniently only provide a Windows binary that will only accept particularly constrained wav files. To do conversions, I have to invoke the external binary (via Wine on Linux also works) and munge everything through temporary files. That is all a gross hack, but having some sort of "standard" external binary callout mechanism will be nice. > > From my prospective I want to be able to write drivers for USB devices in Python. > > It may include: You should be aware that userspace stuff just cannot match the speed of kernel level drivers. For some of the stuff you mentioned (eg camcorders, tv cards) you will have to use kernel level drivers, or you will lose data. For other stuff such as storage, you will just be a lot slower than a kernel level driver. (As an example I get about a 3rd the speed from Python than kernel drivers when dealing with a device that is just bulk data). The other reason for having kernel level drivers is so that the devices appear "normally" and can be used by other programs (eg an audio device appearing as a normal OS level audio device). > If anyone has any experience with doing USB specific bindings in Python or want > to participate or give feedback, I have already done a wrapper around libusb/libusb-win32. It has been shipping with my BitPim project on Windows, Linux and Mac for almost 8 months now. Many other projects (such as Gphoto and Linux scanners) use libusb. You can see the wrapper at http://cvs.sf.net/viewcvs.py/bitpim/bitpim/native/usb/ It does need a distutils wrapper around it all. (I haven't done one myself since there doesn't seem to be easy integration of Swig with distutils). Roger From ptmcg at austin.rr._bogus_.com Mon May 10 09:09:14 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 May 2004 13:09:14 GMT Subject: newbie question - remove a module from ram References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> Message-ID: <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> "john fabiani" wrote in message news:4AAnc.6791$dH5.4946 at newssvr27.news.prodigy.com... > Hi, > > I believe I have good understanding of import but it occurred to me that > I might want to remove an imported module. I.e I load a module into ram > and I no longer need the module. Modules just stays in ram? In the > windows world I would "thisform.release()" and the garbage collector > would release the ram. So did I miss something or is there no release > method. How about a method within a class like destroy()? > > I just got to believe it's there???? But where? > John Well, you were pretty close with calling something like .release(). Use the del statement. >>> import random >>> print random.random() 0.475899061786 >>> del random >>> print random.random() Traceback (most recent call last): File "", line 1, in ? NameError: name 'random' is not defined >>> -- Paul From ed at leafe.com Tue May 18 15:22:00 2004 From: ed at leafe.com (Ed Leafe) Date: Tue, 18 May 2004 15:22:00 -0400 Subject: Creating self-contained apps Message-ID: Is it possible to create a version of Python, along with several specific modules, and somehow package it together to be distributed as a single unit? I remember that Zope did something similar in the past, but can't recall how that was accomplished. I looked into bdist in DistUtils, but couldn't find enough info on it to determine if it would do what I want. I have an app that requires a specific version of Python, along with specific versions of various modules. What I need is a single file that I can distribute that will run my packaged version of python, assuring that the user, no matter what Linux distro they are using, will be able to run it? And while I'm at it, is this also possible in Windows? ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From jfabiani at yolo.com Mon May 17 21:02:52 2004 From: jfabiani at yolo.com (john fabiani) Date: Tue, 18 May 2004 01:02:52 GMT Subject: module for working with the result set In-Reply-To: References: <_wbqc.68175$eT6.35900@newssvr25.news.prodigy.com> Message-ID: <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> Diez B. Roggisch wrote: > john fabiani wrote: > > >>See this does not make sense to me. >> >> >>mydata[0] >>['5992 ', 'A', '5346 ', ' ', 'XX >> ', 'Kathy Stromme ', 'RICHMOND AMERICAN HOMES >> ', '7250 WEST PEAK, ST # 212 ', ' > > > > > well - its a list, and I bet its a list of columns. The columns are mostly > strings (at least at the beginning) and obviously are space padded to match > up to their size. > > The code you posted earlier assumes that the result row is returned as dict, > thus iterating over the row yields in the keys. Consider this example: > > d = {"key1" : 10, "key2" : 20 } > for key in d: > print key, d[key] > > that results in > > key1 > 10 > key2 > 20 > > notice how putting a dict as sequence in a for ... in ... : statement > iterates the keys. > > Now you don't get a dict, but a list of row-values. So your code > > for field in mydata[0]: > print mydata[0][field] > > iterates over the data you presented, yielding the '5992 ' > as first value. Thats all. Of course using that value as index makes no > sense. > > To summarize: you expect data to be returned as dict per row, where the data > is returned as list. > > Use the cursors .description property to get a mapping between name and > index. > > > OK thats great! I did the following and it works. for field in range(0,len(mydata[0])): print mydata[0][field] following your thoughts on the keys and my mistake - can you tell me how to get into a dict format? John From missive at frontiernet.net Sat May 8 15:30:22 2004 From: missive at frontiernet.net (Lee Harr) Date: Sat, 08 May 2004 19:30:22 GMT Subject: setting property to type other than what is given Message-ID: I am just starting to use properties, and wonder what you might think of this ... class RNumber(object): def __init__(self, n, nmin, nmax): self.nmin = nmin self.nmax = nmax self.n = n def _get_n(self): return self._n def _set_n(self, n): if n == 'max': self._n = self.nmax elif n == 'min': self._n = self.nmin else: self._n = min(self.nmax, n) self._n = max(self.nmin, self._n) n = property(_get_n, _set_n) >>> a = RNumber(5, 0, 10) >>> a.n 5 >>> a.n = -3 >>> a.n 0 >>> a.n = 'max' >>> a.n 10 >>> a.nmax = 50 >>> a.n = 'max' >>> a.n 50 From stefano at stefanomasini.com Tue May 18 09:10:38 2004 From: stefano at stefanomasini.com (Stefano Masini) Date: 18 May 2004 06:10:38 -0700 Subject: ValueError: argument is not a COM object Message-ID: <80ef91b8.0405180510.96cd945@posting.google.com> Hi, I'm scripting Adobe InDesign CS with python, through COM interface. This is how I get the application object: win32com.client.Dispatch('InDesign.Application') I'm not a guru of com programming, but I've gone quite far in my purpose so far. Now I'm stuck. There's a method Add in object Groups (which is in object Page, etc.) that's supposed to take a parameter called GroupItems of type "Array of Objects", according to the Visual Basic programming reference. I have the following piece of code: print 'obj1: %r, obj2: %r' % (comObjs[0], comObjs[1]) grps = self.page.comPage.Groups grps.Add( GroupItems=(comObjs[0], comObjs[1]) ) Which gives me: obj1: >, obj2: > [...] File "modPrint.py", line 204, in creaFrameLoghi grps.Add( GroupItems=(comObjs[0], comObjs[1]) ) File ">", line 2, in Add ValueError: argument is not a COM object Why is it so? I suppose the type system is having troubles figuring out the type of the list elements. So, what do I do? I hope somebody can help, thank you! stefano From BRADLEY.S.GASPARD at saic.com Tue May 11 10:21:43 2004 From: BRADLEY.S.GASPARD at saic.com (Gaspard, Bradley S) Date: Tue, 11 May 2004 10:21:43 -0400 Subject: PyFile_AsFile( ) question Message-ID: I want to open a file in python (version 2.2.3) f = open("foobar.txt", "w") and then pass the file's handle, f, to a "C" extention EnumWinsatErrorCode SetOutStream(PyObject *fileObj) { FILE *fp; if ((fp = PyFile_AsFile(fileObj)) == NULL) { fprintf(stderr, "SetOutStream(): failed to obtain stream\n"); return WINSAT_SUP_TYPE_ERROR; } fprintf(fp, "This is a foobar\n"); // Causes windows application error jglobal->debugout = fp; return WINSAT_SUP_SUCCESS; } This works fine on my linux box. Under windows however I am getting fatal error whenever I try and use the FILE * returned by PyFile_AsFile( ). Can someone help me out?? From follower at iname.com Thu May 6 10:25:31 2004 From: follower at iname.com (Follower) Date: 6 May 2004 07:25:31 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: > A similar but better solution is to follow the model created by the PHP > community. If you follow the link to > http://us2.php.net/manual/en/function.sort.php you'll see how > impressive the results can be. I'm surprised no-one has pointed out the Zope documentation system, which is a little closer to home: Comment display can be toggled on & off and the comments are essentially "inline". Just another data point. --Phil. From dmq at gain.com Sat May 29 18:11:50 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 29 May 2004 15:11:50 -0700 Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> Message-ID: On 29 May 2004 16:31:38 GMT, Duncan Booth wrote: >David MacQuigg wrote in >news:o1veb09o0vgiaf9b7cs4umu79jf977s5qa at 4ax.com: > >> I haven't added any classmethod examples to my OOP chapter, because >> until now I've thought of them as very specialized. I'm searching for >> a good textbook example, but all I can find is trivially replacable >> with an instance method or a static method. If you have an instance >> already, the class can be resolved via self.__class__. If you don't >> have an instance, the desired class can be passed as an argument to a >> static method. > >I find that slightly surprising. You say that if you have a static method >you can pass the class as a parameter, but since you already specify the >class somewhere to access the static method surely you are duplicating >information unneccessarily? You could equally say that static methods >aren't needed because you can always use a class method and just ignore the >class parameter if you don't need it. The information is duplicate only if the class we want to pass in is the always the same as the class in which the method is defined, in which case, we would just hard-code the class name in the method. class Mammal(Animal): def cmeth(cls, *args): print cls, args cm = classmethod(cmeth) def smeth(cls, *args): print cls, args sm = staticmethod(smeth) Using a classmethod: >>> Mammal.cm() () >>> Feline.cm() () Using a staticmethod: >>> msm = Mammal.sm # type "redundant" info only once >>> msm(Mammal) () >>> msm(Feline) () You are right, we could just ignore the cls argument in the classmethod, and avoid the need to learn staticmethods, but between the two, I would rather use staticmethod, as it is simpler in most cases. What would be nice is if we had a variable like __class__ that would work in any method form. Then we would not need a special first argument for classmethods, or any special method form at all for this purpose. >> I sounds like you may have a good use case for classmethods. Could >> you give us an example, and a brief explanation of what it does that >> can't be done as easily with other method forms? Your help will be >> greatly appreciated. > >Ok, I'll try and give you a couple of examples, feel free to tear them >apart. The most obvious one is to write factory methods: I like these examples, and I think they will fit nicely into the teaching sequence -- Spam and Foo, Animals_1, Animals_2, then some real programs. I would change the classmethods to staticmethods, however, and avoid the need to teach classmethods. This would make your calls look like: print Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) -- or if you prefer a short alias -- print CS(Rectangle, 10, 10, 3, 4) -- Dave >-------- begin cut --------------- >class Shape(object): > def __init__(self): > super(Shape, self).__init__() > self.moveTo(0, 0) > self.resize(10, 10) > > def __repr__(self): > return "<%s instance at %s x=%s y=%s width=%s height=%s>" % ( > self.__class__.__name__, id(self), > self.x, self.y, self.width, self.height) > > def moveTo(self, x, y): > self.x, self.y = x, y > > def resize(self, width, height): > self.width, self.height = width, height > > # Factory methods > def fromCenterAndSize(cls, cx, cy, width, height): > self = cls() > self.moveTo(cx, cy) > self.resize(width, height) > return self > fromCenterAndSize = classmethod(fromCenterAndSize) > > def fromTLBR(cls, top, left, bottom, right): > self = cls() > self.moveTo((left+right)/2., (top+bottom)/2.) > self.resize(right-left, top-bottom) > return self > fromTLBR = classmethod(fromTLBR) > >class Rectangle(Shape): pass >class Ellipse(Shape): pass > >print Rectangle.fromCenterAndSize(10, 10, 3, 4) >print Ellipse.fromTLBR(20, 0, 0, 30) >squares = [ Rectangle.fromCenterAndSize(i, j, 1, 1) > for i in range(2) for j in range(2) ] >print squares >-------- end cut ------------ >Running this code gives something like: > > > >[, instance at 9320016 x=0 y=1 width=1 height=1>, 9321200 x=1 y=0 width=1 height=1>, width=1 height=1>] > >The important point is that the factory methods create objects of the >correct type. > >The shape class has two factory methods here. Either one of them could >actually be moved into the initialiser, but since they both take the same >number and type of parameters any attempt to move them both into the >initialiser would be confusing at best. the factory methods give me two >clear ways to create a Shape, and it is obvious from the call which one I >am using. > >Shape is clearly intended to be a base class, so I created a couple of >derived classes. Each derived class inherits the factory methods, or can >override them if it needs. Instance methods won't do here, as you want a >single call to create and initialise the objects. Static methods won't do >as unless you duplicated the class in the call you can't create an object >of the appropriate type. > >My second example carries on from the first. Sometimes you want to count or >even find all existing objects of a particular class. You can do this >easily enough for a single class using weak references and a static method >to retrieve the count or the objects, but if you want to do it for several >classes, and want to avoid duplicating the code, class methods make the job >fairly easy. > > >--------- begin cut ------------- >from weakref import WeakValueDictionary > >class TrackLifetimeMixin(object): > def __init__(self): > cls = self.__class__ > if '_TrackLifetimeMixin__instances' not in cls.__dict__: > cls.__instances = WeakValueDictionary() > cls.__instancecount = 0 > cls.__instances[id(self)] = self > cls.__instancecount += 1 > > def __getInstances(cls): > return cls.__dict__.get('_TrackLifetimeMixin__instances' , {}) > __getInstances = classmethod(__getInstances) > > def getLiveInstances(cls): > instances = cls.__getInstances().values() > for k in cls.__subclasses__(): > instances.extend(k.getLiveInstances()) > return instances > getLiveInstances = classmethod(getLiveInstances) > > def getLiveInstanceCount(cls): > count = len(cls.__getInstances()) > for k in cls.__subclasses__(): > count += k.getLiveInstanceCount() > return count > getLiveInstanceCount = classmethod(getLiveInstanceCount) > > def getTotalInstanceCount(cls): > count = cls.__dict__.get('_TrackLifetimeMixin__instancecount' , 0) > for k in cls.__subclasses__(): > count += k.getTotalInstanceCount() > return count > getTotalInstanceCount = classmethod(getTotalInstanceCount) > > >class Shape(TrackLifetimeMixin, object): > def __init__(self): > super(Shape, self).__init__() > self.moveTo(0, 0) > self.resize(10, 10) > > def __repr__(self): > return "<%s instance at %s x=%s y=%s width=%s height=%s>" % ( > self.__class__.__name__, id(self), > self.x, self.y, self.width, self.height) > > def moveTo(self, x, y): > self.x, self.y = x, y > > def resize(self, width, height): > self.width, self.height = width, height > > # Factory methods > def fromCenterAndSize(cls, cx, cy, width, height): > self = cls() > self.moveTo(cx, cy) > self.resize(width, height) > return self > fromCenterAndSize = classmethod(fromCenterAndSize) > > def fromTLBR(cls, top, left, bottom, right): > self = cls() > self.moveTo((left+right)/2., (top+bottom)/2.) > self.resize(right-left, top-bottom) > return self > fromTLBR = classmethod(fromTLBR) > >class Rectangle(Shape): pass >class Ellipse(Shape): pass > >print Rectangle.fromCenterAndSize(10, 10, 3, 4) >print Ellipse.fromTLBR(20, 0, 0, 30) >squares = [ Rectangle.fromCenterAndSize(i, j, 1, 1) for i in range(2) for j >in range(2) ] > >print Shape.getLiveInstances() >for cls in Shape, Rectangle, Ellipse: > print cls.__name__, "instances:", cls.getLiveInstanceCount(), \ > "now, ", cls.getTotalInstanceCount(), "total" >--------- end cut ------------- > >The middle part of this file is unchanged. I've added a new mixin class at >the top, but the class Shape is unchanged except that it now includes the >mixin class in its bases. The last 4 lines are also new and print a few >statistics about the classes Shape, Rectangle, Ellipse: > > > >[, instance at 9376272 x=0 y=1 width=1 height=1>, 9376336 x=1 y=1 width=1 height=1>, width=1 height=1>] >Shape instances: 4 now, 6 total >Rectangle instances: 4 now, 5 total >Ellipse instances: 0 now, 1 total From newsgroups at jhrothjr.com Mon May 10 16:07:29 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 May 2004 16:07:29 -0400 Subject: How to read files written with COBOL References: Message-ID: <109vo8pdrpv636b@news.supernews.com> "Batista, Facundo" wrote in message news:mailman.404.1084210463.25742.python-list at python.org... > People: > > I'm trying to convert my father from using COBOL to Python, :) > > One difficult thing we stuck into is how to read, from python, files written > with COBOL. > > Do you know a module that allows me to do that? > > It should avoid us the work to write a COBOL program that open the COBOL > file and write a CSV one (easily readable from python). What's the OS for the two languages? COBOL from mainframe to X86ish is very different from some flavor of Windows or Unix COBOL. Also, are we talking fixed or variable length records? And if variable, how are they structured? In either case, I think the struct module (under String Services) is what you're looking for. John Roth > > Thank you all! > > Facundo Batista > Desarrollo de Red > fbatista at unifon.com.ar > (54 11) 5130-4643 > Cel: 15 5132 0132 > > > From FBatista at uniFON.com.ar Mon May 10 13:31:44 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 10 May 2004 14:31:44 -0300 Subject: How to read files written with COBOL Message-ID: People: I'm trying to convert my father from using COBOL to Python, :) One difficult thing we stuck into is how to read, from python, files written with COBOL. Do you know a module that allows me to do that? It should avoid us the work to write a COBOL program that open the COBOL file and write a CSV one (easily readable from python). Thank you all! Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 From beliavsky at aol.com Sun May 30 19:44:03 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 May 2004 16:44:03 -0700 Subject: 2d lists Message-ID: <3064b51d.0405301544.58eb854e@posting.google.com> xiaohua_sun at yahoo.com (SunX) wrote in message news:<337e6cd5.0405291411.4376debc at posting.google.com>... > What is the best way to assign a 2d lists? Something like; > > for i in range(10): > for j in range(10): > aList[i][j] = i*j > > Thank you in advance. (When I replied with subject "Re: 2d lists" Google groups complained.) If you will use the 2d lists for numerical calculations, I would recommend the Numeric or Numarray modules, which provide multdimensional arrays that are much faster than lists of lists. A restriction of Numeric or Numarray arrays is that all the elements must be of the same type (as in Fortran). With Numeric you could write from Numeric import zeros n = 10 alist = zeros([n,n]) for i in range(n): for j in range(n): alist[i,j] = i*j From jjl at pobox.com Mon May 31 18:57:50 2004 From: jjl at pobox.com (John J. Lee) Date: 31 May 2004 23:57:50 +0100 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> <40bb43f6$0$563$e4fe514c@news.xs4all.nl> Message-ID: <87llj8yzkh.fsf@pobox.com> Irmen de Jong writes: > Zunbeltz Izaola wrote: > > > Possibly the code should be restructered, and re-designed; there is > > always room for imporovement. But what I'm doing is not unittest. My > > program is controling and instrument (an x-ray powder > > diffractometer) and some parts of the instrument are not working for > > the moment, so i want to disable all error i get from this instrument > > (are coded like exceptions) > > What I usually do in comparable situations is to write STUB code for > the parts of the system that don't work yet. > Write your stub code so that it does nothing, but doesn't raise any > exceptions too. The only thing you then have to do is write the rest > of the code as you would have done, and once the Stubbed parts work, > replace the stub code with the real code. ...and if you think you want to get exceptions later: def fixme(): pass Sprinkle fixme()s through your code, then redefine later: def fixme(): raise NotImplementedError() John From nicksjacobson at yahoo.com Sun May 23 07:13:00 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 23 May 2004 04:13:00 -0700 Subject: Downloading SCXX Message-ID: I've been trying to download SCXX, but the website http://www.mcmillan-inc.com/ has been down for the last few days. Where else can I find it? Thanks in advance. From moosebumps at moosebumps.mb Tue May 25 04:56:19 2004 From: moosebumps at moosebumps.mb (Moosebumps) Date: Tue, 25 May 2004 08:56:19 GMT Subject: in operator for strings Message-ID: Wouldn't it be cool if you could do this? ('hello','test') in 'blah blah hello blah test': and it would say if all elements of the list are in the string? it would be more efficient and more readable than: 'hello' in 'blah blah hello blah test' and 'test' in 'blah blah hello blah test' From alloydflanagan at comcast.net Thu May 6 11:35:42 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 6 May 2004 08:35:42 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: Michael Chermside wrote in message news:... > Stephen Ferg writes: [snip] > Actually, please don't set up yet another wiki. Instead, go to > http://www.python.org/cgi-bin/moinmoin/ > and start creating pages. (You'll need to create a user account.) > If you're feeling REALLY ambitious, you could go to > http://www.python.org/cgi-bin/moinmoin/ModulesThatNeedDocs > and volunteer to help fill in some of the existing gaps in the > official documentation. [snip some good stuff] > other formats. A wiki can't take the place of that, but then > static docs can't incorporate community involvement as easily > as a wiki... there's room for both. > > -- Michael Chermside Apparently this has been discussed before -- there's a couple of comments on the wiki page requesting that the official documentation be added, from last year. Somebody should Just Do It. From peter.maas at mplusr.de Fri May 7 04:40:45 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Fri, 07 May 2004 10:40:45 +0200 Subject: mod_python problem In-Reply-To: References: Message-ID: Gandalf wrote: > Apache/2.0.48 (Unix) PHP/4.3.4 mod_python/3.0.3 Python/2.3.3 > mod_ssl/2.0.48 OpenSSL/0.9.7c Server at arwen.msnet Port 80 > > This is what I have in httpd.conf: > > LoadModule python_module libexec/apache2/mod_python.so > AddHandler mod_python .py > AddType applcation/x-http-python .py > > > PythonHandler mod_python.publisher > PythonDebug On > I think your handler and your script don't match. This is my working conf: LoadModule python_module modules/mod_python.so ... # This directive shouldn't be important (only for psp) Options Indexes FollowSymLinks MultiViews +ExecCGI AddHandler cgi-script cgi py AddHandler mod_python .psp PythonHandler mod_python.psp PythonDebug On # This directive enables Python scripts in a subdirectory AddHandler python-program .py PythonHandler mptest PythonDebug On mptest.py: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From MAILsweeper at jmifa.com.au Mon May 10 00:16:34 2004 From: MAILsweeper at jmifa.com.au (MAILsweeper at jmifa.com.au) Date: Mon, 10 May 2004 14:16:34 +1000 (EAST) Subject: Your document - VIRUS Infected Message ! Message-ID: <200405100417.i4A4H7dl021078@mel1.unite.net.au> *** This is an automated message *** Your message was found to contain a virus in one or more of the attachments. The message has been deleted and will not be delivered. Please virus scan your attachments before re-sending. Your local Help Desk can provide assistance in virus checking/scanning files and attachments. Original Message Details.. Subject : Re: Re: Re: Your document Sender : python-list at python.org Recipients : cward at jmifa.com.au Date : Mon, 10 May 2004 14:37:48 +1000 From roy at panix.com Sun May 23 09:25:51 2004 From: roy at panix.com (Roy Smith) Date: Sun, 23 May 2004 09:25:51 -0400 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: Peter Hansen wrote: > If by "C++ brigade" you mean "programmers who think C++ does > things the right way" then the only way to get them to take > Python seriously will be either (a) to change Python into > something that closely resembles C++, or (b) to change those > programmers so that their thinking fits Python better. The world doesn't need another language that looks like C++. Java already fills that niche quite nicely. > Merely adding "proper encapsulation" (and I happen to believe > Python already has encapsulation that is quite proper) will > not suffice. And that's a good thing, too.... ;-) 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. From davidf at sjsoft.com Mon May 17 06:07:38 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 17 May 2004 12:07:38 +0200 Subject: Python for Large Projects In-Reply-To: <10ae406ck3q1gb1@corp.supernews.com> References: <10ae406ck3q1gb1@corp.supernews.com> Message-ID: Ixokai wrote: > Hello all. :) > > I've been a long time Python fan, and have fairly recently (with the > support of a coworker who surprised me by mentioning my pet language one > day) convinced my company to begin the colossal task of basically rewriting > all of our software in Python. Woohoo. > Previously we used a few different development environments, mostly > Borland, for different products in our 'system' of thick clients sort of > operating with eachother as they dug against a database. The whole thing is > woefully out of date at this point, and platform-dependant, so we needed to > switch to something.. and Python won. Yay. > In the new platform, we'll be building a distributed system with CORBA > (omniORB + omniORBpy, etc) with Python making up most of our development for > the new edition of our software. Woohoo. Much fun. > > My question is not 'how suitable is Python for large projects?', but > instead more, 'Do you have any advice for large projects with Python?'. > > For example, our system will be made up of numerous applications -- > three or four 'servers', multiple clients, all talking to eachother, sharing > a great deal of code. Any suggestions for organization? Our current plan is > to put everything under the 'site-packages' tree of a Python installation we > provide/control, with a fairly deeply nested tree: > > apt > apt\library > apt\library\corba.py > apt\library\database\* > apt\library\controls\* > apt\application\globalapp1\ > apt\application\globalapp2\ > apt\system\editorial\application\client\ > apt\system\editorial\application\client2\ > apt\system\editorial\library\elementgrid.py > > ... etc. You get the idea, I hope. We have apt.library where we store all of > our 'global', 'shared' libraries that everything can make use of, and > apt.application with some global, shared apps. Then we have 'systems', which > are a collection of applications and libraries in a single domain. These > mostly get sold as a single product, really. Etc, etc. > > I end up doing a lot of: > > from apt.library.corba import * > from apt.library.database import Connection > from apt.library import machine > from apt.system.editorial.library.elementgrid import ElementGrid > > ... And such. When PEP328 gets in, this may become more attractive, but > occasionally I'm alarmed by the depth of the whole thing. But I also want to > keep stuff logical and separated. Well you don't neccessarily have to have everything under apt... You just need to have unique package names. Also the cleaner your system design the less you should have to refer to bits inside other packages. > > And how about distribution? Freezing and such won't work, because of the > shared nature of most of this code. Currently I'm probably planning on > looking into finding the build scripts for python, win32all, and wxPython > and seeing if I can combine them into one single install. Don't know if > that's the best thing to do or not, but expecting my customers to install > this stuff... is expecting too much of them. On the wxPython users list we are planning something called wxPRE which would be an environment pre-setup with Python and wxPython. You may want to help set this up as it is very similar to your requirements. See http://wiki.wxpython.org/index.cgi/wxPRE David From __peter__ at web.de Fri May 21 04:17:51 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2004 10:17:51 +0200 Subject: textwrap for python 2.1? References: Message-ID: Joshua Burvill wrote: > How can I use the textwrap (new in 2.3) module if I have to use python > 2.1? I would just copy it into 2.1's site-packages directory and see if it works. I haven't tried it but I am confident :-) Peter From visualcpp at edirect168.com Mon May 17 06:31:27 2004 From: visualcpp at edirect168.com (vovo) Date: Mon, 17 May 2004 18:31:27 +0800 Subject: Is there any instruction on implementing a python debugger? References: Message-ID: "Phipps Xue" ?b?l?? news:c896rk$l7o$1 at news1.wdf.sap-ag.de ?????g... > Hi All, > > I wanna implement a python debugger, but I don't know the way exactly. Is > there any document or instruction about that? > > Thanks in advance, > > Phipps > > have you tried "pdb" and "bdb" module in the python standard library? From noemail at noemail4u.com Mon May 17 08:51:55 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Mon, 17 May 2004 12:51:55 GMT Subject: beginner's question References: Message-ID: <1df3cfd12f5ac728e6aefcfd7ca32cb0@news.teranews.com> On Sat, 15 May 2004 00:10:15 +1000, "Hadi" wrote: >"Sean Ross" wrote in message >news:pI3pc.34421$dr1.946771 at news20.bellglobal.com... >> >> "Peter Hansen" wrote in message >> news:drmdnbUpXMTjITndRVn-hg at powergate.ca... >> [snip] >> > Otherwise we're likely to be spoonfeeding you answers to your homework >> > assignment. >> [snip] >> >> Hm. I've already done the 'spoonfeeding'. Didn't really think about it. >> Sorry about that. From now on, I'll have atleast one cup of coffee in the >> morning before I start replying to posts. > >what's wrong with helping to new beginners? >Don't be snob! He's not being a snob. Please understand than on the internet, many students will try to get the public to answer their homework for them, without doing the work on their own. Your question sounds like a typical beginner's programming assignment. Because you gave no indication of what you had tried already, it looked like you were trying to just get a quick answer without doing any learning on your own. Peter is very helpful when it is clear that someone has tried to resolve the problem on their own. Good luck with future posts! --dang From Chris.Hornberger at blackrock.com Wed May 12 15:43:42 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 15:43:42 -0400 Subject: perl to python Message-ID: First off, this isn't even remotely a slam, so I hope it's not taken as such. My question is this. Why bother with getting perl code translated into python code? Perl is probably one of the best string manipulation and RegEx processors ever. Python is probably one of the easist general purpose scripting languages ever. They don't have to overlap. With Python's pipe handling there's little reason not to simply leave the perl code where it is and run it from an orchestration script in Python. Perl is a pretty involved, terse and comprehensive wheel. Not sure I see the reasons to reinvent it. It's safe to say that a large majority of the people using perl are also working with it (writing in it). $.02 *note - these are my observations from the environments I'm used to working in. your mileage may vary* -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Scott Schwartz Sent: Wednesday, May 12, 2004 3:08 PM To: python-list at python.org Subject: Re: perl to python Duncan Booth writes: > import sys > for line in sys.stdin: > line = line[:-1].split('\t') > print "%s %s %s %s" % (line[3], line[2], line[1], line[0]) > While I agree with you that using the appropriate tool is preferred over > using Python for everything, I don't really see much to choose between the > Python and awk versions here. 1) Python throws an error if you have less than three fields, requiring more typing to get the same effect. 2) Python generators on stdin behave strangely. For one thing, they're not properly line buffered, so you don't get any lines until eof. But then, eof is handled wrongly, and the loop doesn't exit. 3) There is no efficient RS equivalent, in case you need to read paragraphs. The simpler example for line in sys.stdin: print line demonstrates the problem nicely. $ python z a b c ^D a b c foo bar baz ^D foo bar baz ^D ^D $ Explanations in the docs about buffering and readahead don't excuse this poor result. $ awk '{print}' a a b b c c ^D $ -- http://mail.python.org/mailman/listinfo/python-list From irmen at -nospam-remove-this-xs4all.nl Tue May 11 16:17:59 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 11 May 2004 22:17:59 +0200 Subject: Logging module, a few questions In-Reply-To: <409cf0da$0$21804$e4fe514c@news.xs4all.nl> References: <409cf0da$0$21804$e4fe514c@news.xs4all.nl> Message-ID: <40a134f7$0$64453$e4fe514c@news.xs4all.nl> Sorry to reply to myself, but I found the solution. > I'm using the logging module in Python 2.3.3, with a format string > containing %(asctime). But it now dumps a full date +timestamp in > the log, which is nice but sometimes I only want the timestamp > (no date). Is there an easy way to change this? How can I make > %(asctime) dump only the time? Never mind. I didn't read the manual very well. It tells me to add a "datefmt" to the formatter, which works like a charm. However, the other thing still stands: > I'm using a configuration file to set up the logging. > > Which brings me to another thing. > In java's log4j, it's easy to "silence" or "enable" specific > parts of a logging hierarchy, by doing: > > log4j.category.nl.company = DEBUG > log4j.category.nl.company.lib = WARN > log4j.category.org.apache = WARN > > and so on. > > I see no easy way of doing the same for Python's logging module; > it seems that I have to create a handler for each of the different > parts of the hierarchy of which I want to set the loglevel. > Am I missing something? Anybody got a good idea about this? Thanks! --Irmen. From deetsNOSPAM at web.de Mon May 3 08:33:32 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 03 May 2004 14:33:32 +0200 Subject: Bug in PyCallable_Check References: Message-ID: Arkon wrote: > Hello, > I encountered in a bug (or so I think) in the function > PyCallable_Check, Python C API. > > The problem is that in Python code you can pass to a function that > requests a function(pointer), types.FunctionType (Maybe other types > too, didn't try though) which is in fact a type-type. > > And then the PyCallable_Check won't *detect* that it's not a real > function(pointer) passed...then later when you intend to run that > function, you get an error. FunctionType _is_ callable - in fact it can be used as a constructor: >>> import types >>> co = compile("print 1", "", "exec") >>> f = types.FunctionType(co, locals()) >>> f() 1 >>> So basically PyCallable_Check works properly. And as python is a dynamically typed language, I don't see how you can actually restrict the type of values passed beyond that callable-check. -- Regards, Diez B. Roggisch From peter at engcorp.com Mon May 10 07:23:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 May 2004 07:23:56 -0400 Subject: What I don't like about wxPython In-Reply-To: References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: <5qmdnW7wAa7Q-wLdRVn-jA@powergate.ca> Ryan Paul wrote: > On Sat, 08 May 2004 17:08:59 -0700, Paul Rubin wrote: >> >>If wxPython really depends on Windows, that's a huge obstacle for >>those wanting a portable system. If it doesn't literally depend on >>Windows, but uses Windows-centric interfaces and approaches, that's >>still pretty annoying for non-Windows developers. > > now i'm curious. are there ANY gui toolkits that arent blatantly > windows-centric? Personally, I HATE the windows user interface paradigm, > but it seems to be pretty much ubiquitous regardless of your operating > system. GTK, Photon, Aqua, QT, Swing, VCL... all of them have toolbars, > menus, checkboxes, etc. They are all just variation on a theme, so to > speak. If you know of a command oriented graphical interface, i'd love to > hear about it. ;-) Do you mean "windows-centric", or "Windows-centric"? There's a difference, and Microsoft most definitely did *not* invent the concept of "windows", trademarks aside... Windows(tm) is merely a clone of other things, "a GUI with windows" is not what people mean by "Windows-centric". That term refers more to the API and the way things are set up in the GUI than to the "window icon menu pointer" (WIMP) idea itself. (And to answer the one question you might have been asking, yes, many of the frameworks have no connection to Windows(tm) at all.) -Peter From peter at engcorp.com Sat May 8 17:37:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 May 2004 17:37:07 -0400 Subject: What I don't like about wxPython In-Reply-To: References: Message-ID: j_mckitrick wrote: > Just thought I'd play devil's advocate... > > I tried wxPython briefly, and it had some nice features. > > It has a huge list of dependencies. 1. Python. 2. Windows. Unless I misunderstand, and I'm sure I do, I wouldn't call that a huge list... > I don't like the fonts (but I'd love to know how to get fixed fonts, > or at least anything that looks better on a small laptop screen. wxPython uses whatever fonts are in the system already, doesn't it? Again, I don't seem to understand... > TkInter seems much easier to use... less effort to do things. Lots of people say that. Others say things like "it doesn't fit my brain" and find more success with wxPython or other frameworks. To each her own... -Peter From alan.gauld at btinternet.com Mon May 24 02:45:36 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 May 2004 07:45:36 +0100 Subject: newbie: why it does not work: command=sys.exit? References: Message-ID: <9963b01ckb9crbiga4bpnfe4lb0r082bhm@4ax.com> On Mon, 24 May 2004 00:54:53 +0200, "Paul van Dam" wrote: > I have got a problem with een example from the book "Programming Python" - > Mark Lutz > I do not understand why it not work for Windows XP and Linux (Fedora Core > 1.0). > import sys > from Tkinter import * > widget = Button(None, text='Hello widget world', command = sys.exit) > widget.pack() > widget.mainloop() > ---------------------------------------------------------------------------- > -------- > Traceback (most recent call last): > File "I:\Python\Projecten\#Prog_in_Python\Hfst06\gui02.py", line 5, > in -toplevel- > widget.mainloop() > File "D:\Python23\lib\lib-tk\Tkinter.py", line 965, in mainloop > self.tk.mainloop(n) > File "D:\Python23\lib\lib-tk\Tkinter.py", line 1347, in __call__ > raise SystemExit, msg > SystemExit It is working, its raising SystemExit. The environment that you are running it in (Either Pythonwin or IDLE?) is catching SystemExit and displaying the message rather than actually exit - because it would be a pain having to restart IDLE everytime you ran the program. But if you run your program from Explorer as normal then it should exit just fine. Remember that Pythonwin and IDLE are development tools they are not the normal place to run programs. Because of that they sometimes behave a little differently in an attempt to make life easier for you while developing a program. HTH, Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From rxv at hotmail.com Mon May 24 08:09:54 2004 From: rxv at hotmail.com (Ike) Date: Mon, 24 May 2004 12:09:54 GMT Subject: Netbeans Message-ID: Has anyone successfully managed to use Netbeans as an editor for Jython? Any direction in this regard? Thanks, Ike From donn at drizzle.com Fri May 7 01:50:17 2004 From: donn at drizzle.com (Donn Cave) Date: Fri, 07 May 2004 05:50:17 -0000 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <1083822394.7883@yasure> <3sgl90pcsl8s7n4q65v0rnefirrog0clk1@4ax.com> Message-ID: <1083909016.13162@yasure> Quoth David MacQuigg : ... |> My own perspective is, present |> the core language and leave them to solve problems in that model, |> "bad programming" or not. | | This could be an argument for Perl. :>) Yes, Perl is really aimed straight at this kind of person, and is not a bad choice given a careful exposure. Donn Cave, donn at drizzle.com From dlissett0 at yahoo.com Thu May 13 12:15:58 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 13 May 2004 09:15:58 -0700 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> Message-ID: <6748553f.0405130815.4a69cc84@posting.google.com> Duncan Booth wrote in message news:... -snip- > Well, if I was going to do a Python implementation of this I would want to > look at what the benchmark is trying to achieve, and then program it fresh > from the ground up instead of trying to ape some other language. In > particular I expect that the classes with 'run' methods would probably > become generators with most or all of their state held as local variables. > > For example, imagining that all the 'run' methods have first been renamed > 'next', IdleTask becomes (untested): > > def IdleTask(scheduler, v1, v2): > for i in range(v2): > if v1 & 1: > v1 = (v1 >> 1) ^ 0xD008 > yield scheduler.release(DEVICEB) > else: > v1 = v1 >> 1 > yield scheduler.release(DEVICEA) > yield scheduler.holdCurrent() > > Next most obvious thing is to junk the linked lists and replace them with > ordinary Python builtin lists. Pass the relevant list around instead of the > id constants 'DEVICEA', 'DEVICEB' and you can get rid of all that lookup > overhead. This involves quite a major restructuring of the scheduler > though: hence my comment about understanding what the code is trying to > achieve and starting from the ground up. > > Packet.addTo should look more like: > > def addTo(self, queue): > queue.append(self) > > and then vapourise entirely. > > > Minor points: > > Remove the pointless use of the 'global' keyword in various places. Replace > the traceOn variable with __debug__ so you get the same benefits as > compiled languages by optimising out the test for the trace statements. Thanks, these are all interesting suggestions. > Remove the pointless set/get methods and just access the members directly. > If you are writing a benchmark they will cripple performance. > > Avoiding multiple accesses to the same instance variable, or assigning to > instance variables until you are about to return from a method: use a local > during the execution of the method. The pointless set/get methods are pointless in the other language implementations as well - that's the point. (And I'll cripple that Oberon-2 implementation real soon by enforcing privacy with modules and set/get procedures.) OTOH there's definitely a place for a truly Pythonic implementation here: http://www.lissett.com/ben/bench3.htm best wishes, Duncan From xuejm at sina.com Mon May 17 04:52:44 2004 From: xuejm at sina.com (Phipps Xue) Date: Mon, 17 May 2004 16:52:44 +0800 Subject: Is there any instruction on creating a python debugger? References: Message-ID: Sorry for the confusion. Phipps "Ben Finney" wrote in message news:slrncag9fe.21p.bignose-hates-spam at rose.localdomain.fake... > On Mon, 17 May 2004 10:08:50 +0800, Phipps Xue wrote: > > I wanna implement a python debugger, but I don't know the way exactly. > > By "implement", do you mean you want to use an existing one, or you want > to make your own? > > -- > \ "An idea isn't responsible for the people who believe in it." | > `\ -- Donald Robert Perry Marquis | > _o__) | > Ben Finney From moma at example.net Mon May 24 09:13:00 2004 From: moma at example.net (moma) Date: Mon, 24 May 2004 15:13:00 +0200 Subject: Solving the Einstein's Riddle in Python In-Reply-To: References: Message-ID: Juha Haataja wrote: > I have been learning Python since April, and would like a > few comments from the experts on list processing. > > I managed to implement a Python code for solving the > so-called Einstein's Riddle, see e.g.: > > http://www.manbottle.com/trivia/Einstein_s_Riddle.htm > > I solved the problem in two ways, first the straightforward > way by using lists and list comprehensions. Then I > refactored to code using the Python object model by > deriving new datatypes from the Python list object. The > two versions are available here: > > http://www.csc.fi/oppaat/f95/python/talot.py > http://www.csc.fi/oppaat/f95/python/talot_oo.py > > I apologize for not commenting the code. > > (I localized the data, so the nationalities are now mainly > Nordic. The input data of the first version is in Finnish. > Also, I don't like smoking, so I changed that part of the > data to different types of music.) > > Here is the final output of the OO version: > > Choices: 1 > 1 2 3 4 5 > yellow blue red green white > norway denmark finland germany sweden > water tea milk coffee beer > blues opera rock pop metal > cat horse bird fish dog > > Thus the German owns the fish in house 4. > > The OO version is somewhat slower (1.6 seconds vs. 1.2), but > easier to understand. > > I'm wondering why the code is 50% slower. In principle, the > only difference should be that in the OO versio I'm using an > __init__ method, and in the original version I was creating > lists using []. > > Please feel free to comment on the programming style. > I'm just starting to get to know the language, and my > background in Fortran 90/95 may be a handicap in learning > Python. > > Thanks, > > - JuHa Not bad, Aika hyv? ! norja = kala. From me at privacy.net Tue May 25 07:11:45 2004 From: me at privacy.net (Heather Coppersmith) Date: 25 May 2004 07:11:45 -0400 Subject: in operator for strings References: Message-ID: On Tue, 25 May 2004 08:56:19 GMT, "Moosebumps" wrote: > Wouldn't it be cool if you could do this? > ('hello','test') in 'blah blah hello blah test': > and it would say if all elements of the list are in the string? > it would be more efficient and more readable than: > 'hello' in 'blah blah hello blah test' and 'test' in 'blah blah hello blah > test' Untested: def string_contains_any_of( targets, the_string ): for target in targets: if target in the_string: return True return False string_contains_any_of( ('hello', 'test'), 'blah blah blah' ) HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From j_mckitrick at bigfoot.com Wed May 19 22:32:31 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 19 May 2004 19:32:31 -0700 Subject: Using pygtk and glade2 Message-ID: I am having a problem with combo boxes. If I am using an XML glade2 file for my gui definition, what is the command I need to use to access a given combo box and determine the currently selected item? jonathon From theller at python.net Tue May 11 05:53:19 2004 From: theller at python.net (Thomas Heller) Date: Tue, 11 May 2004 11:53:19 +0200 Subject: Shipping embedded Python project References: <40A076ED.3000107@zoran.com> Message-ID: Miki Tebeka writes: > Hello Thomas, > >> Or you use py2exe to build a zip-compatible archive, and insert it into >> sys.path in your program. Do not specify any of the console and windows >> options, and pass your 'main-module' with the --includes command line >> option. py2exe will happily create a dist directory for you, without an >> exe-file. > > Great! thanks. If this works for you, it would be great if you write up a small recipe into the py2exe wiki. Thomas From topmas38hotmailcom Mon May 31 05:55:59 2004 From: topmas38hotmailcom (MaximusBrood ({[AT]} {[DOT]})) Date: Mon, 31 May 2004 11:55:59 +0200 Subject: binhex problem Message-ID: <40bb012e$0$136$3a628fcd@reader1.nntp.hccnet.nl> Hi, Im a newcomer to Python and I've got some error that I totaly dont understand. I've made a program that is made to extract a couple of binhex files. Here is my sourccode: import binhex, os current = os.getcwd() #Gets current cwd files = os.path.join(current, "files") #joins current path with path files for filename in os.listdir(files): #checks every file in DIR: files os.chdir(files) #changes dir 2 files file2 = win32file.CreateFile(filename, win32file.GENERIC_READ, \ 0, None, win32file.OPEN_EXISTING, 0, None ) #opens hexbin file filename2 = filename+".exe" #changes filename to .exe extention binhex.HexBin(file2, filename2) #translate hexed file 2 binary If I run this one, an exeption is raised: Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 407, in ImportFile exec codeObj in __main__.__dict__ File "", line 1, in ? File "C:\WINDOWS\temp123\Stuf\all2.py", line 9, in ? binhex.HexBin(file2, filename2) #translate hexed file 2 binary TypeError: __init__() takes exactly 2 arguments (3 given) I've got only 2 arguments, but python thinks I've got there 3... Can anybody help me? (maybe its a stupid question but i'm only a newbie =) ) I'm running on Win XP Home From fgeiger at datec.at Sat May 15 02:56:06 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sat, 15 May 2004 08:56:06 +0200 Subject: book on wxPython? References: Message-ID: Mark Hammond's book "Python Programming on Win32" helped me a lot in entering wxWindows (oops, sorry, wxWidgets of course) programming. A 2nd source of "no, how?" I can recommend is the wxPython Wiki with a few essential recipies. And the wxWidget help coming with wxPython is a good resource a soon as you were able to get started. HTH Franz GEIGER "Grant Edwards" schrieb im Newsbeitrag news:slrncab3p3.ou5.grante at grante.rivatek.com... > Can anybody recommend a good book on wxPython? Are there any > books on wxPython? > > I've been trying to learn wxPython and/or wax for a few weeks, > and I'm just not getting it. [I wrote and shipped one small > wxPython app a couple years ago, and it was a cut/paste, trial > and error sort of exercise.] > > wxWindows seems to be more low-level than the other GUI > toolkits I've used (Tk, GTK, and Trestle[1]), and there are all > sorts exposed details in wxWindows/wxPython that I find weird. > > For example, I'm still confused about how to tell what the > "parent" of a widget should be. When you put a StaticBox in a > Panel, the Panel is the parent of the StaticBox. When you put > SomeOtherWidget in the StaticBox, why is the parent of > SomeOtherWidget the Panel and not the StaticBox? > > And what about sizers? They seem to be a sort of parallel, > phantom tree of widgets that's stuck on the side of the real > tree of widgets, while other GUI toolkits treat layout widgets > (grids, hboxes, vboxes, etc) as a "first-class" widgets that > reside in the same tree as the widgets that actually draw > stuff. > > Anyway, I'd really love to find a good book on wxPython. I'm > still working through wxPython tutorials, and I've read through > some of the wxWindows ones (which are of limited value for > somebody steadfastly determined to remain clueless about C++). > > I'm also still reading stuff on wiki.wxpython.org, but Wikis > always seem so fragmented... > > [1] I still think the hbox/vbox/glue abstraction used by > Trestle was one of the easiest to use. Probably because > I've been using TeX and LaTeX for 25 years. > > -- > Grant Edwards grante Yow! How do I get HOME? > at > visi.com From donn at drizzle.com Sun May 16 01:18:15 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 16 May 2004 05:18:15 -0000 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> Message-ID: <1084684694.603588@yasure> Quoth Peter Hansen : | Valentino wrote: ... | > If all you need is s-expr you maybe can look at Nevow (pronounced | > 'nuevo'), which is the new web toolkit built on top of twisted.web. | | Which raises the question, how do you pronounce "nuevo"? Good question. I thought I knew how to pronounce "nuevo", but if it could be spelled "nevow" ... is that twisted, or what? Donn From nospam at nospam.com Fri May 14 11:04:21 2004 From: nospam at nospam.com (3c273) Date: Fri, 14 May 2004 08:04:21 -0700 Subject: Logical AND question References: Message-ID: Thank you both :-) "Peter Otten" <__peter__ at web.de> wrote in message news:c808i3$aen$06$1 at news.t-online.com... > Tor Iver Wilhelmsen wrote: > > > "3c273" writes: > > > >> >>> if s and t == '': > >> print "This doesn't work!" > > > > This is really > > > > if (s) and (t == '') > > > > which evaluates to false since "if (s)" returns false for the empty > > string. > > The original poster probably wants > > >>> if s == t == "": > ... print "this works" > ... > this works > >>> > > or the conventional > > >>> if s == "" and t == "": > ... print "but this is more common" > ... > but this is more common > >>> > > Peter > From dygimailNo at SPAMpoczta.fm Fri May 21 04:47:26 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 21 May 2004 08:47:26 GMT Subject: Unknown Tkinter bug References: Message-ID: klappnase at web.de (klappnase) wrote in news:a7a67196.0405201330.1e436630 at posting.google.com: > you actually use a couple of other variables that are not defined, > too, so I think this is maybe not the complete code ? Yes. > Maybe you should have a look at the rest of the code if you have > problems. This piece of code generates a bug. > BTW, the traceback you posted seems to look like an IDLE problem > rather than a Tkinter bug I think (at least PyShell.py is the main > file that runs IDLE's Shell window). You were right. Restart the shell and the pc helped. -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From RolleXu at msn.com Sat May 22 11:34:15 2004 From: RolleXu at msn.com (RolleXu) Date: Sat, 22 May 2004 23:34:15 +0800 Subject: wxPython about event function Message-ID: class container(wxPanel): self.compnt is a control the event func: EVT_LEFT_DOWN(self,self.OnLeftDown) when click container self.OnLeftDown will be called when click self.compnt self.OnLeftDown won't be called please tell me why? and how to call the func, both case? thanks From FBatista at uniFON.com.ar Mon May 3 08:26:17 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 3 May 2004 09:26:17 -0300 Subject: Looking at the next element in a for loop Message-ID: [madsurfer2000 at hotmail.com] #- Is there a way I can get the next element in the loop? #- Something like this: #- #- for a in b: #- if a == 1: #- print >>> lista = ['1', 'g', 6, 'p', 2, 'l', 8, 'a'] >>> for (i, c) in enumerate(lista): if isinstance(c, int): print lista[i+1] p l a Of course, you need to definy what happens when the match is the last element: >>> lista = ['1', 'g', 6, 'p', 2, 'l', 8] >>> for (i, c) in enumerate(lista): if isinstance(c, int): print lista[i+1] p l Traceback (most recent call last): File "", line 3, in -toplevel- print lista[i+1] IndexError: list index out of range . Facundo From paul at boddie.net Tue May 18 05:01:49 2004 From: paul at boddie.net (Paul Boddie) Date: 18 May 2004 02:01:49 -0700 Subject: Python - open forever ? References: Message-ID: <23891c90.0405180101.7b8df4e3@posting.google.com> "Hornberger, Chris" wrote in message news:... > > This poor guy (the original poster) is simply falling victim, as many of > us do, to the whims and paranoia of middle management. I can imagine "Remember RedHat?" being a bullet-point on a PowerPoint slide. "Yes," says some manager. "I remember that they still let us in for the free lunch, but what really annoyed me was when they wouldn't let us take the buffet cart away with us any more." Paul From ville at spammers.com Wed May 26 13:00:17 2004 From: ville at spammers.com (Ville Vainio) Date: 26 May 2004 20:00:17 +0300 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: >>>>> "Ryan" == Ryan Paul writes: Ryan> the line. It's a good OO strategy. I do understand your Ryan> dislike of 'self'. It does seem like clutter. In my code, I Ryan> shorten it to 's'. In ruby, class variables are prefixed Ryan> with an '@', which makes them easier to discern in code, and Ryan> it is easier than typing 'self'. I wish python had something Prefixing names with symbols like $ and @ is a great idea - it makes the "nouns" (variables) stand out from "verbs", and makes the code flow like a natural language, making reading it easy and writing it fun! On a more serious note, you could consider creating a binding for @ that inserts "self.". @ is almost never used in Python, so it should be pretty safe. Ryan> like that. I also think that having to specify the class Ryan> variable in every function definition is a bit silly. Ruby Ryan> gets rid of that too. You might want to create a preprocessor that adds "self" to all in-class definitions that have @, and convert @hei to self.hei. Voila, Ruby non-silliness. The idea could be extended to provide a "Python shorthand", which would expand to full-blown Python: d hello x y: -> def hello(x,y): c hello baseclass: d init arg1 arg2: # expand to __init__ .x = arg1 .y = arg2 d sayhi: p "hi!" .x = 555 o = hello 12 13 p o.x + o.y # prints 25 o.sayhi p o.x # prints 555 Actually, while this would make zero sense for language-as-such, it might turn out to be a fun way to hammer out that first ultra-rapid prototype. At the moment something comes up that needs the explicitness of Python (say, after 45 minutes of hacking), the shorthand can be expanded to Python (optimally with M-x py-expand-shorthand). I find that I write Python code quite fast already, but some phases of the coding process (esp. the implementation of classes) could be further accelerated by this shorthand, mostly due to alleviating the need to use the shift-key. ":" should still be there to enable the use of python-mode.el. The implementation of the shorthand could be pretty ad-hoc, with possibly ambigous grammar. The shorthand would never be shipped unexpanded anyway. -- Ville Vainio http://tinyurl.com/2prnb From wjb131 at web.de Sun May 23 04:28:24 2004 From: wjb131 at web.de (Wolfgang Buechel) Date: 23 May 2004 01:28:24 -0700 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: <4629559b.0405230028.9640579@posting.google.com> wjb131 at web.de (Wolfgang Buechel) wrote in message news:<4629559b.0405101330.286ddb32 at posting.google.com>... > Hi, > > I want to iterate over all 2x2 matrices with elements in range 0..25 > (crypto-stuff). Try generators (new in Python 2.3.3). There is an example you can/must adapt: Look at your Python installation: (PythonPath)/Lib/test/test_generators.py def conjoin() and in the whatsnew-documentation: http://www.python.org/doc/2.3.3/whatsnew/section-generators.html --W. From dmq at gain.com Sun May 23 08:04:36 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 23 May 2004 05:04:36 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: On Sat, 22 May 2004 14:56:29 -0600, "Dave Brueck" wrote: >David MacQuigg wrote: >> >But the above explanation misses one very important point: one is used 99.9% >of >> >the time, the other 0.1% of the time, if that. Mentioning them side by side >> >like you do implies that they are both equially common, which is not >remotely >> >the case. >> >> I can't comment on the usage statistics you cite, but it seems to me >> that unbound methods are more important than these statistics would >> imply. > >All I'm saying is that for most programs, the bound method form is way, way, >way more commonly used than is the unbound calling form. I would agree if you cut out two of the "ways" in this sentence. :>) Still this is like saying names that start with the letter 'q' are way less common than all other names, so it is OK if we have a special form for functions with such names. To take this analogy a step further, I would say that the "no-q" programmers have somehow gotten used to this restriction, and work around it without even thinking, while new users find it annoying to have to go back and fix a few functions because they didn't remember the "no-q" rule. >> They are necessary to make the language complete, so you can >> do things that would otherwise require creating an artificial instance >> just to call a method. > >I don't disagree that they are necessary to make the language complete, but >over and over again you have posted examples of the form "here's a bound method >example, here's an unbound method example. They're different". Yes, they're >different, but presenting them that way makes it sound like you normally have >an equal mix of bound and unbound method calls, and that the difference is so >subtle that confusion abounds. Neither is true in practice. I've never stated or implied that unbound methods are as common as bound methods. Nor would I say that confusion abounds. The different calling sequences are just an unnecessary complexity that trips up some new users, especially those that don't have experience in some other OOP language. >> >> I know this is not terribly >> >> difficult to understand -- one is a bound method, the other unbound. >> >> Still it is a problem for beginners, and it leads to unecessary >> >> complexities like static methods. >> > >> >I don't see how this is at all related to static methods. A method is some >> >piece of functionality that is specific to a particular class. If you have >some >> >function already lying around, why would you want it as a method, much less >a >> >static method? (I can think of a couple of rather contrived examples, but >> >nothing compelling or common in a normal application - help me out here) >> >> Here is an example from our CDP ( Circuit Design Platform ): >> >> class Bag: >> def __init__(self, **kwargs): >> self.__dict__.update(kwargs) >> >> def load(infile): >> strng = infile.read() >> exec( 'bag = Bag(\n' + strng + ')' ) >> return bag >> load = staticmethod(load) >> >> We need to load a "statefile" with a deeply nested hierarchy of >> parameters, which will then be represented by a "Bag" of parameters at >> each level of the hierarchy. The load method needs to be called >> before any Bag exists, so we add the magic "staticmethod" line, and >> don't worry about 'self'. Sure, we could move the load function >> outside of the Bag class, but that would disrupt the natural structure >> of the program. The load function is unique to Bags, and it belongs >> in the Bag class. > > I know what static methods are _for_, but I don't see what is >necessarily complex about them, nor how your proposed unification would help - >in fact, ISTM that it would make it much more confusing because both the >implementor and caller of the code would never be quite sure if the method was >a static one or not, and that's something that needs to be known by both >parties. I think you have not understood the proposal. It is *not* necessary in the new syntax to know the difference between a static and non-static method. There *is* no difference. A "static method" (a function without instance variables) simply ignores __self__. >Perhaps we both dislike the current staticmethod syntax of Python, but IMO >making a static method look the same as a non-static method seems like a very >wrong thing to do. They are quite different in purpose and construction, so to >me it doesn't make sense that they should look the same in implementation OR in >usage. See, to me it makes sense that there's no 'self' in a static method - >since there's no instance for it to refer to. Likewise, it makes sense to me >that there _is_ a self in a bound method, else member variable lookup would be >magical (certainly more magical than the fact that a bound method knows what >instance it belongs to). The differences are an artifact of the syntax, not any fundamental difference in purpose. Normal methods have a special first argument. Static methods do not. That's all there is to it. That's the way I think when I write a program, and the way I will minimize the complexity for my students. I still don't know what "static" means in this context, but it doesn't matter. It's just a wart I need to add after I've written a method definition, if it happens that the method needs to be called without 'self'. If there is were some fundamental purpose to static methods, there would be something they can do that can't be done with the proposed simpler syntax? Can you think of any example? >> See the thread "classes vs dicts" and the discussion following my post >> on 5/13 for more on statefiles and Bags. See also >> http://www.ece.arizona.edu/~edatools/Python/Statefiles for the latest >> on our solution to the statefile problem (how to handle thousands of >> deeply-nested setup parameters). > >Yes - I suggested the basis for your current solution. :) And I greatly appreciate that suggestion. The statefile format is now readable enough that we will avoid having to write our own parser. By the way, I wasn't the only one who missed the obvious solution. An experienced Python programmer was going down the wrong path with me. >> >What kind of an instructor would bring this up in an introductory >programming >> >course? If you're short on time, there are oodles and oodles of more >commonly >> >used topics to cover. >> >> Seems like my challenging statement was misleading. I have no >> intention of bringing up strange binding problems in an introductory >> class. This was a challenge to those who think that Python's binding >> syntax is simple. > >I'd say that first and foremost, it's powerful, and then simple. The example >IMO shows an abuse of the power without a good reason to do so (my reaction to >the example as "you're doing something odd for no good reason, and you get odd >behavior, so what?"). The proposed unification does not seem to take into >account the benefits of the current design - whether by choice or ignorance I >don't know. I may be wrong, but it looks to me like there *are* no benefits of the current binding syntax over the proposed syntax. I don't know the reason behind the "Method Binding Confusion" example, so I would hesitate to tell someone they don't need to do that. I assume it was distilled from a much larger program. It does look simple enough that I can imagine someone stumbling upon it in the course of writing an ordinary program. In any case, the proposed syntax can do this without any special effort. What are the benefits of the current design? What can you do in the current syntax that can't be done more easily in the proposed syntax? Show me some code, and I will show you the equivalent in "Python 3". >> Have you read the proposal at >> http://www.ece.arizona.edu/~edatools/Python ?? > >Yep. > >> When you say the distinction between methods and functions makes >> sense, I assume you mean it has some value to the user. I would like >> to hear more about this, because I am assuming just the opposite. > >Yes it has some value, but more than that: it fits the brain quite well. IMO it >adheres to the principle of least surprise, The Principle of Least Surprise has always been one of my favorites. It's a shame this principle offers us so little guidance in resolving a simple issue like this unification question. It seems to be leading us in opposite directions. I think the difference may be in our backgrounds. You seem quite comfortable with Java, so I would guess these different method forms fit with what you have learned there. I'm coming at it from a different direction -- no CIS background at all. I see more beauty, more simplicity, and less surprise in having just one form of function/method -- unless there is something these various method forms can do, that I can't do with a simpler syntax, then I would change my mind, and *highlight* the differences with keywords like "staticmethod" and "lambda". With the new syntax, I wouldn't even use the word "method". >if you are really thinking about >what is going on (and this is why I haven't found it to be a problem for >newbies, because they usually _aren't_ that interested in precisely what is >going on). And if you're not really thinking about what is going on, it places >a pretty minimal burden on you - there's only a handful of rules a blissfully >ignorant programmer needs to adhere to, and that's pretty amazing. But once you >do understand what is going on, then you can do some pretty powerful things >that you can't do in e.g. Java (at least not directly and not without a lot of >work). I need to feel like I understand what is going on. I'm not comfortable with a bunch of arbitrary rules, especially if I frequently run into cases where forgetting the rules can cause a problem. With the proposed syntax, I understand binding completely. I don't even see any wierd little edge cases, like the example from the "binding confusion" thread. In that example, it should not matter if we are calling a normal function, a built-in function, a normal method, or a static method. If the function contains instance variables ( with a leading dot ), it will look for __self__. If that variable is not set, you will get an exception. That's all there is to binding. It doesn't even matter if the function is defined inside a class, or at the module level. That choice can be determined by whatever is the best organization of the program. >> >Most importantly, I've yet to see it cause any real or lasting problems for >> >beginners - either (1) nobody cares unless you point it out and make an >issue >> >out of it, or (2) they ask, you take 30 seconds to explain it, and they say, >> >"oh, ok" and move on. Occasionally someone particularly bright (and/or with >> >experience in certain other languages) will really grasp the 'why' behind >the >> >difference, and you'll see the light go on as they begin to understand the >> >power available to them. >> >> I think there is a tendency to assume that whatever you have learned >> is just the way things have to be. > >Maybe, but I'm not arguing that the way things are is the way things have to >be - I'm arguing that (1) the current way is better than all other proposals to >date and (2) the specific proposal you've put forward introduces more problems >than it solves and possibly results in a less powerful language (but I'm not >sure because I haven't seen examples of how all calling use cases would be >affected). I need specific examples of problems introduced by the new syntax, or of something the old syntax can do better. We can argue general principles forever, but one good example will settle this question. Some of the highly-touted benefits of Prothon, I have concluded are bunk, and I have eliminated them from my proposal. The total elimination of all class-like behavior (getting rid of the "two-tier" class/instance object model) is a case in point. In most programs, two tiers are very useful. Nobody has even offered a use-case for the 'one-tier" object model of Prothon. As far as I can tell, none of the "one-tier" advocates have even looked at Michele Simionato's implementation of prototypes in Python. (comp.lang.python 4/28/04). In spite of the bunk, we should not dismiss all the ideas in Prothon. In my opinion, this unification of methods and functions is the one gem we can distill from the mess. We can learn a lot by looking at how languages designed *after* Python have tried to improve on it. >> The best introductory text on Python is Mark Lutz' Learning Python, >> 2nd ed. He takes 96 pages to cover OOP, and he doesn't waste time on >> unnecessary topics like metaclasses. I believe an improvement in >> Python's syntax could make it possible to cut the number of pages in >> half, and still reach the same level of proficiency in solving real-world >problems > >But has Mark told you that his goal was brevity? I bet you could cut the pages >in half without ANY changes to the language, not because he did a poor job (he >obviously didn't) but because you have different goals in mind. I assume his goal, like mine, is to teach basic Python with the minimum time and effort. Brevity is not a goal in itself. There is an optimum number of pages to explain a given set of topics, and I think Learning Python is pretty close to that optimum. The reduction in pages has to come from a reduction in the number of topics. >> Why is it we can see there is clutter in Perl, but we can't see it in Python? > >Nobody is taking that stance, as far as I can tell. Nobody seems to understand that lambda functions, static methods, etc. are clutter. -- Dave From tzot at sil-tec.gr Fri May 14 03:55:03 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 14 May 2004 10:55:03 +0300 Subject: Speed up properties?! References: Message-ID: On Fri, 14 May 2004 08:53:30 +0200, in comp.lang.python Peter Otten wrote: [comparing direct attribute access and indirect through property get] A slight addition to your code for another alternative (2.4 only) of property gets (the z property): class C(object): def __init__(self): self.setX(5) def setX(self, x): if not 0 <= x <= 5: raise ValueError self.x = x # for speed comparison only: y = property(lambda s: s.x) from operator import attrgetter z = property(attrgetter("x")) o = C() yields (on my laptop): C:\Temp>timeit -s "from propspeed import o" o.x 1000000 loops, best of 3: 0.655 usec per loop C:\Temp>timeit -s "from propspeed import o" o.y 100000 loops, best of 3: 2.36 usec per loop C:\Temp>timeit -s "from propspeed import o" o.z 1000000 loops, best of 3: 1.51 usec per loop -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From peter at engcorp.com Tue May 25 09:55:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 May 2004 09:55:57 -0400 Subject: why i In-Reply-To: References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: Richard Brodie wrote: > "Peter Hansen" wrote in message news:N9KdnVD1v92IlS7d4p2dnA at powergate.ca... >>The idea that 'i' is mnemonic for 'integer' is interesting, though. >>If the mathematical field is really the origin, rather than FORTRAN, >>it would be interesting to know if that was how "they" picked it. >> >>Googling to little avail, the best I could find to help was Hilbert's >>1900 address on "23 Mathematical Problems" which he gave to the Int'l >>Congress of Mathematics in Paris, proving a usage which predates >>FORTRAN by 50-some years. > > I would assume vector algeba was the origin; Google can go back > to 1843 on that line: http://www.wordiq.com/definition/Quaternion > > That suggests that i, j, k notation is an extension of complex notation > so i must be the Euler i (1777) presumably standing for imaginary. I'm not sure we should consider that early usage to be of the same type. The Hilbert usage is as a subscript, which corresponds to (I think) the reason for using i,j,k as indices in a program loop: to index into a vector, as in M[i] and such. -Peter From lbates at swamisoft.com Tue May 4 14:29:39 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 4 May 2004 13:29:39 -0500 Subject: printing float as formatted dollars References: Message-ID: Here is a function I wrote and use. Note: floats have rounding "issues" when they get very large. def fmt_wcommas(amount): # # This function will take the number passed to it and format it with # spaces as thousands separators. # # If I got zero return zero (0.00) # if not amount: return '$0.00' # # Handle negative numbers # if amount < 0: sign="-" else: sign="" # # Split into fractional and whole parts # whole_part=abs(long(amount)) fractional_part=abs(amount)-whole_part #print "whole_part=",whole_part," fractional_part=",fractional_part # # Convert to string # temp="%i" % whole_part # # Convert the digits to a list # digits=list(temp) #print "digits=", digits # # Calculate the pad length to fill out a complete thousand and add # the pad characters (space(s)) to the beginning of the string. # padchars=3-(len(digits)%3) #print "padchars=",padchars if padchars != 3: digits=tuple(padchars*[' ']+digits) else: digits=tuple(digits) #print "digits='%s'" % str(digits) # # Create the mask for formatting the string # sections=len(digits)/3 mask=sections*",%s%s%s" outstring=mask % digits # # Drop off the leading comma and add currency and sign # outstring=sign+"$"+outstring[1:].lstrip() #print "outstring (int)=", outstring # # Add back the fractional part # outstring+=("%.2f" % fractional_part)[1:] # return outstring if __name__=="__main__": print "----------testing negative floats------------------------------" sign=-1 invalue=0L for j in range(2): for i in range(1,10): invalue=invalue*10+i print fmt_wcommas(float(sign*invalue)-.01) print "----------testing positive floats------------------------------" sign=1 invalue=0L for j in range(2): for i in range(1,10): invalue=invalue*10+i print fmt_wcommas(float(sign*invalue)+.01) "Tim" wrote in message news:aNadndnHDepsqQjd4p2dnA at adelphia.com... > Is there a simple way to output float values as formatted dollar amounts? > i.e. 127379.42 as $127,379.42 > > Thanks, > Tim > > > > From bhoel at web.de Sat May 15 14:57:24 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sat, 15 May 2004 20:57:24 +0200 Subject: Warning when testing 2.3.4c1 Message-ID: Hello, Testing 2.3.4c1 I get: ... test_format /home/devel/compile/Python-2.3.4c1/Lib/test/test_format.py:19: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up result = formatstr % args ... Is this intended, or should it be solved? Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From juliagoolia301 at hotmail.com Wed May 5 15:56:55 2004 From: juliagoolia301 at hotmail.com (Julia Goolia) Date: 5 May 2004 12:56:55 -0700 Subject: Bit torrent swap space via python Message-ID: <79ad5955.0405051156.20d2e1b@posting.google.com> Hi, I noticed that Bit Torrent uses a lot of swap space when downloading files at a fast speed. This has quite a bad effect on my system. My applications that are running are constantly getting removed from the swap space cause Bit Torrent is downloading so much data. Everything becomes VERY choppy. At least I think that is what is going on. My question is... is there a class or function to open a file which will not do any buffering in the swap space? Peace! julia From noemail at noemail4u.com Wed May 12 11:02:33 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Wed, 12 May 2004 15:02:33 GMT Subject: Python dynamic function selection References: Message-ID: <1b58950df2f113904071845b8f2f0b4e@news.teranews.com> On 12 May 2004 01:42:02 -0700, ekoome at yahoo.com (Eric) wrote: >The following example will explain what i want to do: >>>> def func(): > print "true" >>>> rules=(func,) >>>> for rule in rules: > rule > >I expect the final function to print true, but instead i have > > >How do i get it to print true. I know if i had parameters in rule >like: >>>> def func(var): > print var >>>> rules=(func,) >>>> for rule in rules: > rule("true") >it will work. But in my case i don't need to pass any parameters. > >How do i get the former method to print instead of returning a >function? In Python, as in C and many other languages (but not BASIC or Pascal/Delphi and probably others), to call/invoke/execute a function, you need to put parentheses after the name. This is what the others' examples have shown: for rule in rules: rules() # call the function If this were not the way it worked, then in the line above it, where you have: rules=(func,) it would have (called and) printed true and returned None (implicitly), and rules would point to a (None,) tuple. --dang From sorry at but.no.spam Mon May 17 06:17:04 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Mon, 17 May 2004 13:17:04 +0300 Subject: This program makes Python segfault - no other does Message-ID: The program attached to this message makes the Python interpreter segfault randomly. I have tried both Python 2.2 which came with Debian Stable, and self-compiled Python 2.3.3 (newest I could find on www.python.org, compiled with default options (./configure && make). I'm using the pyPgSQL plugin to connect to a PostGreSQL database, and have tried the Debian and self-compiled newest versions of that as well. I'm running BitTorrent, and that works perfectly well; btlaunchmany.py has been running for months continuously without any problems. I've also run the kernel compile test (compiling the Linux kernel nonstop to find any inadequeties in processor cooling), and couldn't get any errors in 6 hours. This makes me thing I'm hitting some weird bug in the interpreter. Specifically, I'm wondering if my habit of reusing old variable names in a function once they are no longer needed might be causing the trouble; maybe it causes confusion on the variable type ? The program retrieves Usenet News messages from the database (inserted there by another Python program, which works perfectly and also uses the pyPgSQL plugin). So, here's the program. Does anyone know what's wrong with it ? #!/usr/local/bin/python2.3 # Insert message contents into the database, for each message-id already there # # Copyright 2004 by Juho Saarikko # License: GNU General Public License (GPL) version 2 # See www.gnu.org for details from pyPgSQL import libpq import nntplib import sys import string import regex import sha import imghdr import binascii import StringIO import os def strip_trailing_dots(n): tmp = [] for i in range(len(n)): if n[i][-1] == "," or n[i][-1] == ".": tmp.append(n[i][:-1]) else: tmp.append(n[i]) return tmp def findmimetype(body, filename): what = imghdr.what(StringIO.StringIO(body)) if what == "gif": return "image/gif" if what == "png": return "image/png" if what == "jpeg": return "image/jpeg" return None def try_decode_and_insert_uuencoded(conn, id): begin = regex.compile("begin [0-9]+ \(.*\)") conn.query("BEGIN") basedir = "kuvat" message = conn.query("SELECT data FROM fragments_bodies WHERE message = " + str(id) + " ORDER BY line") print message.ntuples keywords = [] picids = [] n = 0 s = "" print 'Starting message id ' + str(id) while n < message.ntuples: # print "length of row " + str(n) # print str(message.getlength(n, 0)) # print "Got length" s = str(message.getvalue(n, 0)) # print "Got s" if begin.match(s) > 0: # print "Begin matched" body = [] file = begin.group(1) # print "Starting to decode, at line " + str(n + 1) for k in range(n+1, message.ntuples): # print "Decodind row " + str(k) s = message.getvalue(k, 0) if s[:3] == "end": n = k + 1 break try: body.append(binascii.a2b_uu(libpq.PgUnquoteBytea(s))) except: bytes = (((ord(s[0])-32) & 63) * 4 + 3) / 3 body.append(binascii.a2b_uu(s[:bytes])) # print "Got to end, at line " + str(n) # print "Attempting to join body" body = string.join(body, "") # print "Attempting to hash body" hash = sha.new(body) qhash = libpq.PgQuoteBytea(hash.digest()) # qbody = libpq.PgQuoteBytea(body) # print "Attempting to find whether the pic already exists" already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) if already.ntuples == 0: # print "Attempting to find mimetype" mimetype = findmimetype(body, file) # print "Found mimetype" if mimetype != None: # o = conn.query("INSERT INTO pictures (picture, hash, mimetype) VALUES (" + qbody + ", " + qhash + ", " + libpq.PgQuoteString(mimetype) + ")") # already = conn.query("SELECT id FROM pictures WHERE OID = " + str(o.oidValue())); # already = conn.query("SELECT id FROM pictures WHERE data = " + qbody) # already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) # print "Attempting to insert hash and mimetype" conn.query("INSERT INTO pictures (hash, mimetype) VALUES (" + qhash + ", " + libpq.PgQuoteString(mimetype) + ")") # print "Attempting to get id" already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) # print "Attempting to get value" picid = already.getvalue(0, 0) # print "Attempting to OK dir" if os.access(basedir + "/tmp", os.F_OK) != 1: os.mkdir(basedir + "/tmp") fh = open(basedir + "/tmp/" + str(picid), "wb") fh.write(body) fh.close() # print "File ok" else: picid = already.getvalue(0, 0) if already.ntuples == 0: # print "already.ntuples == 0, ROLLBACKing" conn.query("ROLLBACK") return # print "Appending picid" picids.append(picid) # print "Picid appended" else: tmpkey = strip_trailing_dots(string.split(s)) if len(tmpkey) > 0: for j in range(len(tmpkey)): keywords.append(tmpkey[j]) # print "Adding 1 to n" n = n + 1 if len(picids) > 0: # print "Finding Subject" head = conn.query("SELECT contents FROM fragments_header_contents WHERE message = " + str(id) + " AND header = (SELECT id FROM fragments_header_names WHERE header ilike 'Subject')") if head.ntuples > 0: # print "Splitting Subject" blah = head.getvalue(0,0) print str(blah) blahblah = string.split(str(blah)) # print "Stripping" abctmpkey = strip_trailing_dots(blahblah) # print "Stripping done" # print "Really" tmpkey = abctmpkey #B print "Subject split" if len(tmpkey) > 0: for j in range(len(tmpkey)): keywords.append(tmpkey[j]) o = conn.query("INSERT INTO messages DEFAULT VALUES") mid = conn.query("SELECT id FROM messages WHERE OID = " + str(o.oidValue)) messageid = mid.getvalue(0, 0) if len(keywords) > 0: for x in range(len(tmpkey)): qword = libpq.PgQuoteString(str(keywords[x])) tmp = conn.query("SELECT id FROM keywords_words WHERE keyword = " + qword) if tmp.ntuples == 0: conn.query("INSERT INTO keywords_words (keyword) VALUES (" + qword + ")") tmp = conn.query("SELECT id FROM keywords_words WHERE keyword = " + qword) keyid = str(tmp.getvalue(0, 0)) for y in range(len(picids)): conn.query("INSERT INTO keywords_glue(word, picture) VALUES (" + keyid + ", " + str(picids[y]) + ")") dummyone = "SELECT fragments_header_contents.line, fragments_header_names.header," dummytwo = " fragments_header_contents.contents FROM fragments_header_names, fragments_header_contents" dummythree = " WHERE fragments_header_contents.message = " + str(id) dummyfour = " AND fragments_header_contents.header = fragments_header_names.id" head = conn.query(dummyone + dummytwo + dummythree + dummyfour) if head.ntuples > 0: for h in range(head.ntuples): qhead = libpq.PgQuoteString(str(head.getvalue(h, 1))) qcont = libpq.PgQuoteString(str(head.getvalue(h, 2))) tmp = conn.query("SELECT id FROM header_names WHERE header = " + qhead) if tmp.ntuples == 0: conn.query("INSERT INTO header_names (header) VALUES (" + qhead + ")") tmp = conn.query("SELECT id FROM header_names WHERE header = " + qhead) headid = str(tmp.getvalue(0, 0)) line = str(head.getvalue(0, 0)) conn.query("INSERT INTO header_contents (header, message, line, contents) VALUES (" + headid + ", " + str(messageid) + ", " + line + ", " + qcont + ")") conn.query("DELETE FROM fragments_header_contents WHERE message = " + str(id)) conn.query("DELETE FROM fragments_bodies WHERE message = " + str(id)) conn.query("COMMIT") tmpdir = basedir + "/tmp/" for i in range(len(picids)): picid = picids[i] if os.access(basedir + "/" + str(picid%1000), os.F_OK) != 1: os.mkdir(basedir + "/" + str(picid%1000)) os.link(tmpdir + str(picid), basedir + "/" + str(picid%1000) + "/" + str(picid)) os.unlink(tmpdir +str(picid)) else: conn.query("ROLLBACK") return database = libpq.PQconnectdb('dbname = kuvat') items = database.query("SELECT message FROM whole_attachments") # try_decode_and_insert_uuencoded(database, 1167) for i in range(items.ntuples): print 'Starting call ' + str(i) try_decode_and_insert_uuencoded(database, items.getvalue(items.ntuples - 1 - i,0)) print ' returned from call ' + str(i) # except: # print 'Some other error occurred, trying to continue...\n' From noamr at correctme.users.sourcephorge.net Wed May 26 17:30:13 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Thu, 27 May 2004 00:30:13 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Noam Raphael" wrote in message > news:c8o9vo$las$1 at news.iucc.ac.il... > >>contradicts your assumption that only 50 other people would like it. I >>don't see what brings you to think that you represent 99.99 percent of >>Python users. > > > Projecting thoughts into my brain that I never had is stupid. I really > don't like that. > When you assume that only 50 people would like my suggestion, you assume that all the other 99.99 percent of Python users wouldn't like it, just because you don't. If I am wrong - correct me. > >>Perhaps *you* could have been a bit more open to hear them... > > > Making false ad hominen comments is stupid. I don't like that either. > > I an disappointed. Sorry I took your request for comments *on the > proposal* seriously. > > Terry J. Reedy > As you may have noticed, I did take your comments seriously, and referred to every one of them. I'm sorry if my remark offended you. I will try to be more polite in my future posts. However, I did sense a tone of impatience in your reply, and I think you should try to eliminate it in your future posts. Best wishes, Noam Raphael From rana at rocketmail.com Fri May 14 17:02:03 2004 From: rana at rocketmail.com (Rana) Date: 14 May 2004 14:02:03 -0700 Subject: dns module Message-ID: <6d6e2b7c.0405141302.8f3dca2@posting.google.com> hi! is there some dns module for RedHat? or some dns functions in an existing module? It seems to be some python-dns for Debian and Mandrake, but i didn't find one for RedHat best regards, Rana From godoy at ieee.org Sun May 2 07:58:23 2004 From: godoy at ieee.org (Jorge Godoy) Date: Sun, 02 May 2004 08:58:23 -0300 Subject: Help with ConfigParser References: Message-ID: On Dom 02 Mai 2004 08:49, Stephen Boulet wrote: > I'm having a bit of trouble getting my head around the ConfigParser > module. I have a very simple configuration file; maybe the easiest thing > to do would be to show that: > > ============ > # Add a local directory to be backed up followed > # by the directory name on the FTP server. > # > # Example: /home/joe/digital photos = photos > > [Backups] > /home/stephen/photos/digital camera = photos > /home/stephen/documents/tax documents = taxes > ============ > > I just want to retrieve the information in the backups section. Thanks. Which one? ;-) There are two. You can list the keys (LHS) and the values (RHS) or both. >>> import ConfigParser >>> configFile = open('/etc/g2ctech/cvs.cf') >>> config = ConfigParser.ConfigParser() >>> config.readfp(configFile) >>> config.items('default') [('forbidden_exts', "['.doc', '.xls', '.ppt']"), ('cvsroot', '/home/cvs')] >>> config.items('get_data_from_mail') [('maildir', '/home/godoy/empresa/clientes/dataprev/cvs-import/tests/sample')] >>> config.get('default', 'cvsroot') '/home/cvs' >>> Default is a section as well as get_data_from_mail. Be seeing you, -- Godoy. From ddenholm at theworld.com Wed May 19 09:00:37 2004 From: ddenholm at theworld.com (D Denholm) Date: 19 May 2004 06:00:37 -0700 Subject: problem with PYTHONPATH on WinXP References: Message-ID: Thanks, that did the trick. I am still puzzled why the PYTHONPATH environment variable didn't work. Is it overwritten if *any* *.pth files exist? Peter Hansen wrote in message news:... > D Denholm wrote: > > > I recently installed Python 2.2 on my WinXP box. > > > > I am having problems figuring out how to create the PYTHONPATH > > correctly. > > I would suggest not using PYTHONPATH, but instead use the .pth > file capability defined in and used by site.py. Check the > comments at the top of that file in your python/lib folder, > and make a .pth file with the appropriate contents instead > of mucking with environment variables. One thing to note: > the file extension must be lower case or site.py won't > find the file. > > -Peter From lennaert.goris at ellips.ws Wed May 12 13:42:45 2004 From: lennaert.goris at ellips.ws (Lennaert Goris) Date: Wed, 12 May 2004 19:42:45 +0200 Subject: Python+SQL References: Message-ID: Op Wed, 12 May 2004 17:02:28 +0100, schreef Chris Stiles: > What are my options for using Python and SQL - specifically mysql ? So far > I've found pysqldb and python-mysql on sourceforge, but the official > references don't seem to include anything. > > Is there an API that supports the 'table row expressed/mapped to object' > paradigm ? if i remember correctly python has an sql api. A google on python sql api gave me the following two adresses. http://www.amk.ca/python/writing/DB-API.html http://www.wellho.net/forum/Programming-in-Python-and-Ruby/ Python-and-SQL-the-DB-API-and-Gadfly.html First adres seems to be the most promissing. hope I was of some help. From newsgroups at jhrothjr.com Fri May 7 17:31:15 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 May 2004 17:31:15 -0400 Subject: Distutils help needed! Message-ID: <109o01v7s4lm2bd@news.supernews.com> I'm trying to put together a distribution for Python FIT 0.4a1 (the first version I'm actually distributing), and distutils is giving me a slight problem. It seems to be building OK and both the manifest file and the .zip file have all the right directories and contents. The install seems to work and it's putting the fit directory in the right place, but the result is missing directories that don't contain at least one Python module. (and one directory that does contain a Python module, but it doesn't contain a __init__.py - the module is a script, not something to import.) This is on Windows. Here's the setup.py file: --------------------------------------------------- # Distutils setup file. from distutils.core import setup setup(name="PyFIT", version="0.4a1", packages = ["fit", "fit/fat", "fit/tests", "fit/eg", "fit/eg.music"], # XXX eg.net when update author = "Ward Cunningham", author_email = "Ward at c2.com", maintainer = "John Roth", maintainer_email = "PyFit_maintainer at jhrothjr.com", url = "fit.c2.com", description = "Python language port of FIT", long_description = """ FIT is an acceptance test package originally written in Java by Ward Cunningham and ported to Python by Simon Michael. This version brings the code up to the latest Java version on fit.c2.com, and also includes changes for and interfaces to Object Mentor's Fitnesse package """, ) --------------------------------------------------- and here's the MANIFEST.in file: ------------------------------------------------- global-include *.htm *.html *.gif *.jpg *.txt ----------------------------------------------- Another question. Ward is the author of the original Java version of FIT; should I be refering to him as the author, Simon Michael (who did the original Python port), or myself, who has done a lot of work trying to make it a useful Python facility? What's the general tradition here? From mozumder at dsmpro.com Thu May 6 01:42:57 2004 From: mozumder at dsmpro.com (Bobby Mozumder) Date: Thu, 6 May 2004 01:42:57 -0400 Subject: Where is IDLE? Message-ID: <3A71B2BF-9F20-11D8-94B4-000A95C8902E@dsmpro.com> I can't find it in the 2.3.3 source tarkit. Shouldn't it be in the Tools directory? BTW I am trying to embed an IDLE-type interpreter into a Qt TextEdit widget. Has anyone done the same? -bobby From rmunn at pobox.com Mon May 10 13:10:08 2004 From: rmunn at pobox.com (Robin Munn) Date: Mon, 10 May 2004 17:10:08 GMT Subject: Unix compress (.Z) files References: Message-ID: Heiko Wundram wrote: > Am Samstag, 8. Mai 2004 01:04 schrieb Peter Smith: >> Are there any utilities in Python which can uncompress a file zipped >> on a unix system using "compress"? > > Unix "compress" uses a form of the LZW compression codec (same thing as is > used for GIFs), and because of the patent restrictions UniSys has on this > codec, it'll be hard to come across a decompressor for this kind of file, if > not the original Unix tool itself by now (which is symlinked to gzip on my > workstation installation). As far as I know, Python has no binding to an > LZW-decompression library (zlib uses something completely different), and so > you're on your own. > > But coding an LZW decompressor is not that hard... ;) Didn't that patent expire already? (Google, Google...) From http://www.unisys.com/about__unisys/lzw -- The U.S. LZW patent expired on June 20, 2003, the counterpart Canadian patent expires July 7, 2004, the counterpart patents in the United Kingdom, France, Germany and Italy expire June 18, 2004, and the Japanese counterpart patents expire June 20, 2004. The U.S. patent has expired, but you may not be able to distribute an LZW program worldwide yet. Just wait two months, though, and then you'll be able to write and distribute a Python module for LZW decompression without infringing on any patents. -- Robin Munn rmunn at pobox.com From lbates at swamisoft.com Wed May 26 19:46:57 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 26 May 2004 18:46:57 -0500 Subject: Question from a beginner References: <44c2a239.0405261525.5b22cb88@posting.google.com> Message-ID: It's all about Python's pointers and immutable objects. Test1 and Test2 point to the same vector (not copies of the same vector). You need: Test1=vector(1,0,0) Test2=vector(1,0,0) to get to "independent" instances of the vector object. All objects (that I'm aware of) in Python can be changed. You can even overwrite Python's own objects. People do it all the time when first learning. Actually this comes in handy after you grow accustomed to it. str="abc" then try to do a=str(1) and get an error because the str() function has been redefined to a string containing "abc". HTH, Larry Bates Syscon, Inc "Rodney Dunning" wrote in message news:44c2a239.0405261525.5b22cb88 at posting.google.com... > Hello, > > I've just picked up python to create some 3D visuals (using VPython) > for a physics class I'm developing. While writing a program, I > developed a "bug" that is reflected in the code below. When executed, > *both* Test1 and Test2 are changed. Can someone explain this to me? > Why is Test2 changed? > > from visual import * > from __future__ import division > > ##Variable tester > > a = vector(1,0,0) > > Test1 = a > > Test2 = a > > print "Test1 = ",Test1 > print "Test2 = ",Test2 > > Test1.x += 3 > > print "Test1 = ",Test1 > print "Test2 = ",Test2 > > ##End code > > I've programmed extensively in Fortran-90. Is there anything in python > analogous to the PARAMETER keyword in Fortran-90, such as > > integer, PARAMETER :: i = 10 !*** the value of i cannot be changed, > period. > > Thanks for your help. > > -- > Rodney Dunning > Assistant Professor of Physics > Birmingham-Southern College From sympa at ens.fr Mon May 17 04:16:55 2004 From: sympa at ens.fr (SYMPA) Date: Mon, 17 May 2004 10:16:55 +0200 (CEST) Subject: Results of your commands Message-ID: <200405170816.i4H8GtEE013589@nef.ens.fr> > Delivery Failure - Invalid mail specification Command not understood: ignoring end of message. No command found in message From irmen at -nospam-remove-this-xs4all.nl Mon May 31 10:40:55 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 31 May 2004 16:40:55 +0200 Subject: exceptions In-Reply-To: References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: <40bb43f6$0$563$e4fe514c@news.xs4all.nl> Zunbeltz Izaola wrote: > Possibly the code should be restructered, and re-designed; there is > always room for imporovement. But what I'm doing is not unittest. My > program is controling and instrument (an x-ray powder > diffractometer) and some parts of the instrument are not working for > the moment, so i want to disable all error i get from this instrument > (are coded like exceptions) What I usually do in comparable situations is to write STUB code for the parts of the system that don't work yet. Write your stub code so that it does nothing, but doesn't raise any exceptions too. The only thing you then have to do is write the rest of the code as you would have done, and once the Stubbed parts work, replace the stub code with the real code. --Irmen From imbosol at aerojockey.invalid Tue May 18 21:21:43 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 19 May 2004 01:21:43 GMT Subject: Python compilers? References: Message-ID: [[ Note for Peter Hansen: all uses of the word "compiler" below is understood to refer to an optimizing compiler to machine language, and I mean a real, not virtual, machine. ]] Heiko Wundram wrote: > Am Dienstag, 18. Mai 2004 13:41 schrieb Jacek Generowicz: >> Native compilers for other languages just as dynamic as Python >> exist. These compilers manage to achieve very significant speed >> increases[*]. > > You are again refering to LISP as an example of a dynamic language > which when compiled gives huge speed increases. This is true in some > respect, in others it isn't. LISP has the advantage that > type-inference may be used throughout the program to create one > version of each function, which can then be compiled. Can you give an example of a function Lisp is able to compile that Python manifestly couldn't. I don't buy it. [snip] > In Python this isn't true. Python, instead of LISP, is "completely" > dynamic, meaning that it's pretty impossible to do type-inference > for each function that is called (even checking types isn't > possible). I don't follow you. In what way is Python dynamic that Lisp isn't? And Python certainly can check types. > E.g. how do you expect type-inference to work with the pickle > module? string -> something/Error would be the best description what > pickle does. For the function which calls pickle, do you want to > create versions for each possible output of Pickle? Which outputs > of Pickle are possible? You can write pickling package in Lisp. I think the Lisp compiler would handle such a package fine, and I see no reason why a hypothetical Python compiler wouldn't. > (depends on the loaded modules, which can be loaded at runtime) > There is no (sane) way to create machine-code which calls into the > appropriate (low-level) Python-runtime functions (such as Py_List*, > Py_Dict*, etc.) for such a method, at least not at compile-time. That might be true, but pickling is only one module. The fact that I'm able to write a pickling package in Lisp doesn't make it impossible to write a Lisp compiler, and the fact that pickling module exists in Python doesn't make it impossible to write a Python compiler. What would a Lisp compiler do faced with a Lisp pickling package? > At runtime, this is possible. See what psyco does. There's a nice > presentation on the psyco-website which explains what it does, and I > guess you'll understand when you see that why writing a "compiler" > for Python is pretty impossible. Well, I don't buy it, and I don't see any fundamental between Python and Lisp dynamicism. The only thing you've demonstrated is that there is some code in Python that could make optimizing difficult--a statement which is true of Lisp also--but it's a specific case that is not applicable generally. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From peter at engcorp.com Sat May 15 00:13:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 00:13:23 -0400 Subject: smptlib frustration! In-Reply-To: <560d84ab.0405141057.23ce1535@posting.google.com> References: <560d84ab.0405141057.23ce1535@posting.google.com> Message-ID: Joe wrote: > Ok I have written a perfectly well working script that uses smptlib > module to email myself if the script ended in success or failure. > However, this module automatically outputs the results to the console > to show the status of the connection/send/recieve etc... This is a > big problem for me. I am trying to run this script from Backup Exec > as a pre-processing job. This causes my script to always fail because > Backup Exec pre-processing jobs can not output to a console! What am > I to do? Is there a way to stop this module from outputing the status > to the console without having to actually modify the standard module? If you must do this from within the program rather than being able to do the simplest thing, which is to use redirection to dump the output to nowhere... (/dev/null or >nil depending on your OS, if it's Linux or Win32)... then you can use something like this: import sys class Sink: def write_null(self, *pargs): pass sys.stdout = sys.stderr = Sink() There may be a simplification possible, but it's been a while since I've had to do that... -Peter From calfdog at yahoo.com Tue May 25 08:22:15 2004 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 25 May 2004 05:22:15 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> Message-ID: r.gable at mchsi.com (Ralph A. Gable) wrote in message news:<22b7fd40.0405231744.50d125f1 at posting.google.com>... > I'm a newbie at this but I need to control MSIE6 using Python. I have > read the O'Reilly win32 python books and got some hints. But I need to > Navigate to a site (which I know how to do) and then I need to get at > the source code for that site inside Python (as when one used the > View|Source drop down window). Can anyone point me to some URLs that > would help out? Or just tell me how to do it? I would be very > grateful. Ralph, Check out P.A.M.I.E. (Python Automation Module for Internet Explorer) It's a class file that allows you to control IE. (automation) You can Automate things like: * Click and Image, Button or Link * Entering text into fields on a form * Select a List item * Navigate to a site etc.... The source is up on souceforge.net follow the links from http://pamie.sourceforge.net. If you check out the Class file CPamie it should help you get going! it comes with a test file an small tutorial. Best of all it's it works and it's free! Later RLM From donn at drizzle.com Mon May 24 01:54:11 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 24 May 2004 05:54:11 -0000 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> Message-ID: <1085378050.309299@yasure> Quoth Arthur : | On Sun, 23 May 2004 16:13:14 -0000, "Donn Cave" | wrote: | |> I don't know what you mean by `outside the "tuple" sense of the word", |> but in a way I think that may be nearly the problem. Of course if you |> consider these objects on their own, the contents of the tuple but |> isolated from that context, they're as homogeneous as you could want, |> in fact they would be the very same object. |> |> But (I hope) no one articulating this point of view says "homogeneous |> data", or "homogeneous contents", etc. | | | http://mail.python.org/pipermail/python-dev/2003-March/033964.html | | Qutoeth Guido: | | "Tuples are for heterogeneous data, list are for homogeneous data." | | I have been trying to stict meticulously to his terminology, because | my understanding is that is why it is being used. It's too bad if he said that. I think it has not led to mass confusion because if one interpretation of that 10 word summary makes it an utterly absurd proposition, most people are inclined to give him enough credit to look for another interpretation. I'm sure there has been enough discussion of this by now for anyone who cared, but I can't resist a final observation. Suppose we take the absurd interpretation, and further decide to implement a test for this condition, where we evaluate a sequence's homogeneity by comparing its contents object by object. Whatever the original sequence may be, I can tell you right now that the natural sequence type for object by object operations on its contents will be a list. We're going to be very nearly sorting the data, in fact might use sort() to start with if we're lazy, and that's a list operation. Now since lists are for homogeneous data, and this is clearly an application for a list, it can be seen that all sequences are homogeneous, and tuples have no valid use! There's your circular explanation. Donn Cave, donn at drizzle.com From newsgroups at jhrothjr.com Mon May 10 12:57:49 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 May 2004 12:57:49 -0400 Subject: What I don't like about wxPython References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: <109vd4hpglc5qf5@news.supernews.com> "Ryan Paul" wrote in message news:pan.2004.05.10.10.55.58.385708 at sbcglobal.net... > On Sat, 08 May 2004 17:08:59 -0700, Paul Rubin wrote: > > > > > > > If wxPython really depends on Windows, that's a huge obstacle for > > those wanting a portable system. If it doesn't literally depend on > > Windows, but uses Windows-centric interfaces and approaches, that's > > still pretty annoying for non-Windows developers. > > now i'm curious. are there ANY gui toolkits that arent blatantly > windows-centric? Personally, I HATE the windows user interface paradigm, > but it seems to be pretty much ubiquitous regardless of your operating > system. GTK, Photon, Aqua, QT, Swing, VCL... all of them have toolbars, > menus, checkboxes, etc. They are all just variation on a theme, so to > speak. If you know of a command oriented graphical interface, i'd love to > hear about it. ;-) For something completely (and in some sense mind-bogglingly) different, see: www.nakedobjects.org At least it gets rid of menus, toolbars and all that stuff. You might also want to look at the Morphic interface in Squeak. (www.squeak.org) John Roth From peter at engcorp.com Tue May 11 22:54:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 May 2004 22:54:11 -0400 Subject: sending out XML from python. In-Reply-To: <03foc.111778$Jy3.44600@fed1read03> References: <03foc.111778$Jy3.44600@fed1read03> Message-ID: <3o2dnQnr_4xJDDzdRVn_iw@powergate.ca> Sean Berry wrote: > I am going to be doing some programming with a Flash programmer in my > company. Most of the online docs about integrating Flash with another > language use PHP. I am not a fan of PHP. > > What I would really like to do is use Python to create data in the form of > XML to send back to Flash, since Flash MX has the ability to easily parse > XML to get variables and values. > > I have done some reading on XML in Python, but only stuff I have seen has > been geared toward reading in XML data, not spitting it out. > > Is there a module for doing this? I know that I can make something that > would work, but wondered if it is already done. It's often the case that the simplest thing is just to build up the strings from scratch. Constructing an awkward in-memory representation (ala DOM) just to serialize it immediately can be a trying experience. How complicated will your XML be? -Peter From has.temp2 at virgin.net Thu May 27 04:51:53 2004 From: has.temp2 at virgin.net (has) Date: 27 May 2004 01:51:53 -0700 Subject: Cleaner idiom for text processing? References: Message-ID: <69cbbef2.0405270051.50eb5513@posting.google.com> mellis at frogwing.com (Michael Ellis) wrote in message news:... > Hi, > I have some data files with lines in space-delimited > format. There are multiple name-value pairs per line. > > Is there a cleaner idiom than the following for reading each line into > an associative array for the purpose of accessing values by name? If it's terseness you want: import re for line in infile: d = dict(re.findall('([^ ]+) ([^ ]+)', line)) do_something_with_values(d['foo'], d['bar']) Hardly worth worrying about though... From alan.gauld at btinternet.com Wed May 12 10:52:23 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 May 2004 15:52:23 +0100 Subject: newbie question: should I learn TKinter or skip it and learn moreadvanced toolkit? References: Message-ID: <8de4a0p3p0okdu6p8ejaq9654tuot8tsh6@4ax.com> On Wed, 12 May 2004 08:41:32 -0400, "Hornberger, Chris" wrote: > My intent is *not* to become professional GUI developer, but simply to > get a handle on it, so if I write some utilities, I can provide some > nice GUI if required. Yet of course, since I'm learning something new, > it would be nice to learn it 'right from the start'. > > So: should I spend some time or TKinter or simply skip it and start > learning GUI with something like wx or QT? I'd go for Tkinter. If you only want to do basic GUI wrap of existing program or even simple GUI from scratch TKInter is fine. If you want a gentle intro to GUI basics with code in Tkinter and a short comparison with wxPython try the GUI page of my tutorial. It won't make you an expert but will provide enough taster to get you started. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From eppstein at ics.uci.edu Mon May 17 22:53:00 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 17 May 2004 19:53:00 -0700 Subject: bit shifting question References: <40a92d88$1@nntp0.pdx.net> Message-ID: In article <40a92d88$1 at nntp0.pdx.net>, Scott David Daniels wrote: > Unfortunately, shifting is one of those places you > can still discover the "width" with code like: > > def wordwidth(): > for shift in range(256): > if 1 << shift < 0: > return 1 + shift Of course this will give a warning in 2.3 and fail to work in 2.4... I wish I could get the 2.4 behavior now with a from __future__ import but I don't see one for this, instead I find myself doing 1L< Message-ID: "Fredrik Lundh" schrieb: > does it work? is it fast enough? > > (if the answer is yes and yes, what's wrong with you ;-) Well, um, the answer is indeed ("yes", "yes"). But if intended to write code that just works and runs fast enough I wouldn't be here. :) Just like many of us I'm quite new to Python. Learning a high level programming language is a matter of some hours nowadays. What really takes time is digging into the libraries. And that's what my question aimed at: learning some new functions and methods. Christian From guettli at thomas-guettler.de Mon May 10 10:40:38 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 10 May 2004 16:40:38 +0200 Subject: Excel database module References: Message-ID: Am Sun, 09 May 2004 18:38:04 -0400 schrieb Garret McGraw: > Has anybody heard of or know of a python module for > reading/parsing/writing microsoft excel databases? > Any response would be greatly appreciated. Hi, you can store the files as xml and process this. Maybe this helps you: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/192914 Thomas From andreas at easywebsite.se Tue May 18 09:05:08 2004 From: andreas at easywebsite.se (Andreas N) Date: 18 May 2004 15:05:08 +0200 Subject: Regexp to enclose text with P-tag Message-ID: <40aa0a04$1@news.wineasy.se> I'm looking for help writing a regexp to enclose text with a

tag. The rule is that other HTML tags in the text like and other block elements should NOT be enclosed by

. example: lorem ipsum dolor should become:

lorem ipsum

dolor

Can anyone help me with this? :) From linuxtreme3000 at hotPOP.com Sun May 2 07:17:41 2004 From: linuxtreme3000 at hotPOP.com (Nick LaForge) Date: Sun, 02 May 2004 11:17:41 +0000 Subject: Newbe-books In-Reply-To: References: Message-ID: <1083496661.19588.2.camel@localhost> On Sun, 2004-05-02 at 18:39, asdf sdf wrote: > > > > Ditto. I learned from the tutorial and DejaNews. I bought _Programming > > Python_, because I liked _Programming Perl_ so much, but I haven't had > > much use for it. I'm evaluating _Learning Python_ as a training aid. > > It's not bad, so far. I'll probably give it to our next hire. > > followup on my previous comment. in Learning Python, Lutz discusses > Tkinter at some length. This is understandable for historical reasons, > but wxPython would be the better choice. > > If LP had a couple of pages on threads and a useful discussion of > wxPython, then Learning Python would totally rock! The sun is setting > on Tkinter.) > > (are you out there, Mark? an idea for the third edition?) What about pyGTK? From lbates at swamisoft.com Fri May 21 19:24:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 21 May 2004 18:24:12 -0500 Subject: Python Newbie References: <3c0a04e4.0405211434.6667f727@posting.google.com> Message-ID: As Jorge points out, indentation matters. Try something like: import sys count=0 while 1: password = raw_input("Enter your Password (blank to exit): ") count += 1 if password == "secret": print "Welcome in." break elif not password: sys.exit() else: if count < 3: print "Wrong password" continue else: print "Please come back when you remember your Password." sys.exit() > > Ok, I know I may be way off course here but any help would be greatly > appreciated. I dont want to get frustrated and say the heck with it, > especially if it is something minor. Thanks in advance. "Brian" wrote in message news:3c0a04e4.0405211434.6667f727 at posting.google.com... > Hi I am new to this newsgroup and new to programming. I have had this > interest in learning to program because.......well just because. It's > just a curiosity that I have. The reason I am starting with Python, > well some of the websites I went to recommended Python, so here I am. > Ok on to the question. > > I am currently using the book "Python programming for absolute > beginners" by Michael Dawson. The program I am working on is a > password program....dont laugh I know it's really simple to some, but > I am kinda stuck. The book shows how to code a password program like > this: > > password = raw_input("Enter your password:") > > if password == "secret": > print "Access Granted" > else: > print "Access Denied" > > raw_input("Press the enter key to exit") > > Ok that is easy enough I understand what is going on here. As the > book goes on it also talks about elif, and while loops. At the end of > the chapter it gives various challenges that the reader is asked to > complete. One of the challenges is to take the password program from > above and change it so that the user gets only three attempts to enter > the correct password. Well I ain't got it to work yet, I thought I > came close, but no cigar. This is what I have so far: > #Limiting password atempts to three > > password = raw_input("Enter your Password: ") > count = 0 > > > while password != "secret": > print password = raw-input("Enter your Password: ") > count += 1 > > if password == "secret": > print "Welcome in." > > > elif count > 3: > print "Please come back when you remember your Password." > > else: > raw_input("Press enter to exit.") > > Ok, I know I may be way off course here but any help would be greatly > appreciated. I dont want to get frustrated and say the heck with it, > especially if it is something minor. Thanks in advance. From jdhunter at ace.bsd.uchicago.edu Tue May 25 17:30:29 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 25 May 2004 16:30:29 -0500 Subject: alter / modify a list as well as iterate on its items / objects In-Reply-To: <20040525195732.82312.qmail@web20805.mail.yahoo.com> (Derek Basch's message of "Tue, 25 May 2004 12:57:32 -0700 (PDT)") References: <20040525195732.82312.qmail@web20805.mail.yahoo.com> Message-ID: >>>>> "Derek" == Derek Basch writes: Derek> Hello, Can anyone point me towards an article or explain Derek> how to properly alter a list as well as iterate on its Derek> items? For example: Derek> input: Derek> word = ["albert", "likes", "surfing!"] Derek> for word in sentence: word += "foo" Derek> result: Derek> word = ["albertfoo", "likesfoo", "surfingfoo"] Realize that you cannot alter strings because strings are not mutable. You can, however, create a list of new strings on the fly using list comprehensions. sentence = ["albert", "likes", "surfing!"] sentence = [ word+'foo' for word in sentence] And if the list contains mutable items, you can mutate them in place. Eg, a list of lists seqseq = [ [1,2,3], [4,5,6], [7,8,9] ] for seq in seqseq: seq.append(1) print seqseq Hope this helps, JDH Derek> __________________________________ Do you Yahoo!? Friends. Derek> Fun. Try the all-new Yahoo! Messenger. Derek> http://messenger.yahoo.com/ Derek> -- http://mail.python.org/mailman/listinfo/python-list From Chris.Hornberger at blackrock.com Wed May 12 15:51:14 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 15:51:14 -0400 Subject: Why is a None appearing in my output? Message-ID: or, simply drop the "print" from your line that calls fib(50) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of David Stockwell Sent: Wednesday, May 12, 2004 3:47 PM To: python-list at python.org Subject: Why is a None appearing in my output? Hello, I'm a fairly new user of python. I am going through the tutorial on the python.org website and observed a weird thing around the 6.0 modules area. (http://docs.python.org/tut/node8.html) My python version: Python 2.2.3 (#1, Feb 26 2004, 14:37:42) [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 I entered the following text into a 'module file' and saved it: def fib6(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b else: print "done b[",b,"], n[",n,"], a[", a,"]" print "fib6:", fib6(50), "---" print "next" I then run it and get the results: fib6: 1 1 2 3 5 8 13 21 34 done b[ 55 ], n[ 50 ], a[ 34 ] None --- next The question I'm having is what is causing the 'None' to print? The example tutorial doesn't have the None, but when I run I am seeing it and I do not see what causes that. I added the 'else on the while and the "---" stuff to try to figure out what the None means. but i have no clue ... Thanks David _________________________________________________________________ Getting married? Find tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married -- http://mail.python.org/mailman/listinfo/python-list From eric at enthought.com Mon May 17 00:34:59 2004 From: eric at enthought.com (eric jones) Date: Sun, 16 May 2004 23:34:59 -0500 Subject: ANN: Job Openings at Enthought Message-ID: <40A840F3.2050608@enthought.com> Hello, This is a bit of a status report I guess for SciPy (www.scipy.org) and Enthought (www.enthought.com), but, really, it is a long winded job posting. Among other things, Enthought develops scientific software for clients. Python is central to to our strategy in this arena. We have long supported SciPy and believe strongly in Open Source Software. The purpose is to give people a feeling about what we do, the technical challenges we face, and the skills needed to meet them. SciPy ----- There has been a lot of work on SciPy lately by the Travis Oliphant, Travis Vaught, Pearu Peterson, Joe Cooper, and on the website by Jon-Eric Steinbomer and Janet Swisher. The site is now upgraded to Plone and we have a SciPy 0.3 package out. If you're interested in seeing the activity level at scipy.org, please visit. http://www.scipy.org/map?rmurl=http%3A//scipy.net/scipyusage/ It looks like we're averaging about a 100 downloads a day if you add up all source and binary distributions. When SciPy 0.1 was released a couple a years ago, I think we averaged about 10. Its extremely difficult to extrapolate a user base from such information, the obvious growth is good news. Other Stuff ----------- In addition to SciPy we have multiple projects going on right now that either already plug into or will be plugins to a Python-based scientific application framework called Envisage (sorta like an IDE for science apps) that we're working on. The idea is: (1) To lower the bar as far as work required to get a GUI put on the front end of a scientific algorithm. (2) Develop scientific plugins that can play well together so that, for instance, an electromagnetics simulator built by one person can be used in conjunction with an optimization plugin built by another person and results can be visualized with a 3D plugin. This is a hard, long path that requires much work and though. We have started the process and actually have built an app on a very early version of the Envisage framework. The app works great, but it's usage of the framework is a little mixed at this point. There were a lot of compromises we ended up making on the framework side in order to ship on time. Also, I am not sure whether "easy-to-program" and "flexible architecture for compatible plugins" are not mutually exclusive. I always have in my mind that I want a smart scientist to be able to build the GUI in a short amount of time after the algorithm (which is the "hard part") is finished. I still harbor this wish, but the lessons I've had over the last couple of years suggest that the GUI is actually the most expensive part of development for large apps. This is partially due to the fact that commercial apps are rarely built around "research" algorithms -- meaning that the algorithm code usually already exists in some form. Still, UIs take tons of time. Testing them is hard. Flexibility requires more complexity (factories, adapters, etc.) than seems necessary at first. Further, building *good* UI's is really hard. Scientist rarely have the patience or perspective for it -- and yet it is very often difficult to build a good UI for science apps without a scientist's understanding of the underlying problem. We have a number of tools along with SciPy that we're building that are pieces of this puzzle. 1. Traits -- They at the heart of everything we do. They provide some explicit typing, default GUI's, an observer event model for anything that uses them. They can also require some getting used to. 2. Kiva/Enable -- This is the generic drawing system for Python. 3. Chaco -- Interactive 2D Plotting 4. PyFace -- MVC layer on top of wxPython. Supports trees, menus, and a few other things right now. This will grow. 5. Envisage -- Plugin based GUI framework for scientific applications. Beyond the basic GUI that comes from Envisage, we already have a couple plugins for profiling code using hotshot and also searching for memory leaks. David Morrill wrote these and they are called gotcha and enroll. Martin Chilvers wrote a simple scintilla based plugin for editing scripts, and a PyCrust shell is available by default in the app (not a plugin at the moment). We would love to see a number of other plugins: a. Debugger. b. IPython-like PyCrust going. c. A more full featured script editing plugin. (there is a huge list of features here). d. Mayavi e. etc. These are all used actively in commercial products that we deliver. However, they are also in various stages of development and will continue to evolve and grow. Some are still pretty green. Portions of these are openly available now. All five of the listed tool sets will be open at some point this summer when they are cleaned up a bit. Jobs ---- All of this leads to the fact that we are hiring and looking for smart, pleasant, communicative people with integrity that are excited about building this sort of stuff. There is a lot of software architecture to be done that needs talented designers. There is UI design/development that needs scientists that care about UIs or UI developers/designers that are really quick at grasping scientific problems. We also need really strong scientists/scientific developers to do some of the backend coding for commercial products and also SciPy development. If you have a background in geophysics, electromagnetics (especially multi-pole methods) that is a big plus. For this, a PhD is helpful, but not required. Parallel computing skills wouldn't hurt. 3D visualization a la VTK/Python is a major need. So is knowledge about 2D rendering to help finish out Kiva and the Enable toolset. Strong Python skills, Python extension writing knowledge and strong C/C++ skills are a big benefit. Design/development with or of Java NetBeans or Eclipse-like architecture is great -- or any other solid GUI architecture. Dedication to writing clean/clear code meant for other humans to read is a requirement. We have 3 or 4 scientific/python positions to fill over the coming months, and we're looking for candidates that have the best mix of the above skills. You'll join our existing team of scientist/engineers, computer scientists, technical writers, and an HCI specialist. We like this mix and feel it is the best way to build this sort of software. If you are interested in working at Enthought, please send us your resume at jobs at enthought.com. If not, please send this posting to the smartest people you know that fit some part of the above description (Python experience not explicitly required). Salaries are competitive. Candidates must be willing to relocate to Austin, Tx. thanks, eric jones PS: There are additional positions listed at http://www.enthought.com/careers.htm for those interested in business application development (not necessarily with Python). From dbasch at yahoo.com Tue May 25 15:57:32 2004 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 25 May 2004 12:57:32 -0700 (PDT) Subject: alter / modify a list as well as iterate on its items / objects Message-ID: <20040525195732.82312.qmail@web20805.mail.yahoo.com> Hello, Can anyone point me towards an article or explain how to properly alter a list as well as iterate on its items? For example: input: word = ["albert", "likes", "surfing!"] for word in sentence: word += "foo" result: word = ["albertfoo", "likesfoo", "surfingfoo"] Thanks, Derek Basch __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From timr at probo.com Fri May 14 02:16:43 2004 From: timr at probo.com (Tim Roberts) Date: Thu, 13 May 2004 23:16:43 -0700 Subject: Python and Windows.Forms References: <87n08qrpcv.fsf@pobox.com> Message-ID: <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> "Larry Bates" wrote: > >You can access all the Windows common dialogs (forms?) >Python by using Win32 extensions. His specific question was about Windows.Forms, which is a .NET class in the Common Language Runtime. Hooking that is not as easy as popping into the common dialogs. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Mike at DeleteThis.Geary.com Fri May 21 20:05:37 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 21 May 2004 17:05:37 -0700 Subject: Command Prompt References: Message-ID: <10at6akh9coi4cf@corp.supernews.com> Peter Hansen wrote: > Minor issue: on Win XP, there is a "command" and a "cmd". > Here's the visible difference between the two: > > c:\>cmd > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\>command > Microsoft(R) Windows DOS > (C)Copyright Microsoft Corp 1990-2001. > > Presumably there are other, more significant differences > as well. > > Probably advisable to use "cmd" under WinXP, but that's > just a hunch. There's a huge difference between the two. cmd.exe is a 32-bit console application, and command.com is a 16-bit DOS application. You definitely want cmd.exe on the NT versions of Windows (NT, 2000, XP). -Mike From usenet_spam at janc.invalid Thu May 27 00:04:01 2004 From: usenet_spam at janc.invalid (JanC) Date: Thu, 27 May 2004 04:04:01 GMT Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: gabor schreef: > i only want to WRITE that the variable is private once... > i don't want to deal with _prefixed variables in my whole code... With the _prefix it's clear in /every/ part of the code that something is intended for local use... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From apardon at forel.vub.ac.be Thu May 6 10:54:47 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 May 2004 14:54:47 GMT Subject: Scope rule pecularities References: Message-ID: Op 2004-05-06, Yermat schreef : > Antoon Pardon wrote: >> [...] >> a1 = Int(14) >> a2 = Int(15) >> b = Int(23) >> >> print a1, a2 >> >> def foo(): >> >> a1 += b >> a2.__iadd__(b) >> >> foo() >> >> print a1, a2 >> >> >> Now the a1 += b line doesn't work, it produces the following error: >> >> UnboundLocalError: local variable 'a1' referenced before assignment. >> >> The a2.__iadd__(b) line however works without trouble. >> >> >> Now I think I understand what is causing this, but I think this >> kind of thing shouldn't happen. If a += b is just syntatic sugar >> for a.__iadd__(b) then the first should be acceptable where the >> second is acceptable. >> > > Here we are again ! > Do you mind to try : > > def foo(): > global a1, a2 > a1 += b > a2.__iadd__(b) > > Note also that the second line were not executed so you can't know if it > were working... I know it worked because I commented out the first and tried again. Beside you missed the point. I don't need solutions, I know the work arounds to make it work. The point is that although a += b is supposed to be syntactic sugar for a.__iadd__(b), you need a global (and even that won't help if you have nested functions and the a is on an intermediate level) to make the first work but not for the second. -- Antoon Pardon From elainejackson7355 at home.com Sat May 15 18:59:04 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 15 May 2004 22:59:04 GMT Subject: tkinter button widget Message-ID: I've got a script where a button gets pushed over and over: to cut down on the carpal tunnel syndrome I'd like to have the button respond to presses of the Enter key as well as mouse clicks; can somebody clue me in regarding how this is done? Muchas gracias. Peace From JBrouwers at ProphICy.com Wed May 12 17:35:41 2004 From: JBrouwers at ProphICy.com (Jean Brouwers) Date: Wed, 12 May 2004 14:35:41 -0700 Subject: __slots__ vs __dict__ References: Message-ID: <120520041435412591%JBrouwers@ProphICy.com> Well, I am not aware of function in Python which returns the current process' memory usage. Is there one? /Jean Brouwers ProphICy Semiconductor, Inc. In article , Hornberger, Chris wrote: > >PS) The tests were run on a dual 2.4 GHz Xeon system with RedHat > >8.0 and Python 2.3.2. The test script is attached but keep in mind > >that it only has been tested on Linux. It will not work elsewhere > >due to the implementation of the memory() function. > > When you're trying to eke out every last bit of performance, that's fine. > However, I tend to shy away from using VM-based solutions (Java, Python, even > .NET/C#) when they are tied to a platform. If I *must* do so, I farm out the > platform-specific pieces to a library, and my main app gets some code added > that knows how to load libraries on the fly. > > When feasible, mind you. > > -------------------------- > Chris Hornberger > Blackrock - 302.797.2318 > chris.hornberger at blackrock.com > > Card carrying MSDN member since 2004. > No, really. I've got the card to prove it. > From apardon at forel.vub.ac.be Fri May 14 06:27:29 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 May 2004 10:27:29 GMT Subject: Scope rule pecularities References: Message-ID: Op 2004-05-13, Josiah Carlson schreef : > >>The real thing to remember is that Python isn't >>you expect Python to behave like>, > > > > I think it is reasonable to expect a language to behave consistently. > > > > I would like to be able the understand what += does to > > an object without the need of knowing it is mutable or > > not. > > Well then, that is easy, += does whatever the object says it should do. > The only builtin type that is actually modified in place (via +=) are > lists. Everything else uses single name rebinding. Is that a simple > enough rule, because had you done /any/ sort of critical investigation, > you would have discovered it yourself. Your investigation would have > turned up that immutables behave as they should, and a list's __iadd__ > method is an alias for its extend method. Well I think that if you need such a critical investigation, something is wrong. I could just as well write a vector and matrix module that uses "-" for addition and if people then complain tell them that they should have done a critical investigation, then they would have found out that the "-" works as it should. > > >>>I now expect a and c still to be the same object. > >> > >>If 'a' is mutable, and 'a' has the proper __iadd__ operator, then 'a' > >>and 'c' will be the same object when you are done. However, integers, > >>strings, floats,... are immutable, so 'a' and 'c' won't be the same > >>object in those cases (Python only rebinds objects that are specified, > >>due to the whole "explicit is better than implicit" Zen). > > > > Python does more than enought things in an implicit way. > > And automatically rebinding /every/ name that references an object is > more explicit? I don't think so. I didn't say that. I just want to point out that python does enough things implicitly so that the "explicit is better than implicit" argument is invalid. > If all you can say is, "I don't like it, it should be more consistant", > then I ask, "what would be more consistant?" Should we keep a list of > every name that references an object so that functionally, everything is > passed by reference and can be modified at will? Should we force > everything to be mutable, only interning (and making immutable) objects > used as keys in a dictionary? Honestly, I don't believe either option > is a good idea. Let us look at an example and find out why. IMO python being the language that it is with immutable objects, the only consistant solution would have been to just translate a += b into something equivalent to a = a + b and leave it at that. No __ixxx__ methods, no inplace modifications. > Hmmm, dictionaries. Dictionaries are hash tables that contain a key and > value pair. In order to handle dynamic expansion of the hash table, we > must keep the key (Python keeps a pointer to the key, it is much faster > that way). I doubt it is much faster overall. The faster dictionary expansion is at the expense of having to turn your mutable objects you want to use as a key into an immutable equivallent. > Right now, only immutables are able to be keys. Why is this > so? Let us imagine that we use a mutable string as a key in a > dictionary. Everything is fine and dandy, until we modify the string. > At that point, in order for the dictionary to stay consistant, we must > make a copy of that string to keep it as a key. No big deal, right? > Wrong. What if that string were 500k? 500M? It becomes a big deal. It already is a big deal. Because you can't mutate strings, that means that every time you need a minor change to one a lot of copying will go on instead of inplace modifications. Each time you need to do something like name = name[:-3] + newsuffix you make a copy, with strings that are 500k or 500M that is just as big an issue. So either you work with mutable values and then you need to copy them into an immutable before they can be used as a key or you work with immutables and then all manipulations you do on them will involve copying. So Python uses immutables as key because that is faster, is irrelevant to me because it is just a deviation of the cost, not a reduction within the whole program. And besides you can have muttable objects within immutables. > Similarly, rebinding all names that point to an immutable, when that > immutable is modified via += is a fool's errand, /especially/ when we > can use l = 1000000*[0]. According to the rebinding method, all million > pointers would need to be rebound to the new object, which would be the > same as making an integer mutable, which has the problem described in > the previous paragraph. It would only be a problem with a specific kind of implementation. > I think you'll find Python's handling of all immutable values to > coincide with how C handles single integers (except for the > pass-by-reference in function calls). Except that if we compare with C, then Python doesn't use integers but pointers to integers with automatic referencing. And if in C I do *a += 1, then all pointers to that integer will see the new value and it wouldn't take a million rebindings in case of an array/list with a million elements. > >>and your expectations are not what > >>actually happens. What you think /should/ happen is not what /does/ > >>happen, and I am quite sure it is not what /Guido thinks should happen/. > > > > So? Is what Guido thinks should happen above criticism. I think > > that if what Guido thinks should happen makes the language > > behave inconsistenly then > > No, Guido is not above criticism. The mistakes he believes he has made > will be fixed in the 3.0 release. If you can't wait for it, then > perhaps you should write the interpreter/compiler for the language you > want to use. It seems to be in vogue these days. I sometimes dream about that, but I fear I don't have the time nor the motivation to finish such a project properly. I'll just make a choice among the languages that are available. In general I like python, the warts sometimes frustrate me, but I see that as a token of affection, e.g. I don't care about the warts of C++, because I find it so ugly and complicated I avoid using it. So I'll wait what 3.0 has is store and see what I like about it. -- Antoon Pardon From autoresponder at news.dannemann.de Wed May 19 05:25:33 2004 From: autoresponder at news.dannemann.de (autoresponder at news.dannemann.de) Date: Wed, 19 May 2004 11:25:33 +0200 (CEST) Subject: Diese Nachricht wurde Ihnen von DANNEMANN.de gesendet Message-ID: <20040519092533.3C4ADE318@news.dannemann.de> Sehr geehrte Damen und Herren, Sie haben weitere Fragen & Anregungen zu unserem Angebot? Bitte nutzen Sie daf?r den Kontakt-Button auf unserer Website http://www.dannemann.com Vielen Dank f?r Ihr Verst?ndnis! Wir wuenschen Ihnen weiterhin gute Unterhaltung. Atenciosamente DANNEMANN - El noble cigarro. Ihr DANNEMANN.de -Team From newsgroups at jhrothjr.com Tue May 4 07:54:14 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 4 May 2004 07:54:14 -0400 Subject: PEP 328 update References: <109d87iiu30ct7a@news.supernews.com> <109dr3brevocb60@news.supernews.com> Message-ID: <109f147o3e1jm9d@news.supernews.com> "Carl Banks" wrote in message news:yMClc.12854$Gq1.5974 at fe2.columbus.rr.com... > John Roth wrote: > > > > > > > > "Aahz" wrote in message > > news:c76k9g$rf0$1 at panix1.panix.com... > >> In article <109d87iiu30ct7a at news.supernews.com>, > >> John Roth wrote: > >> > > >> >I also don't particularly see the reason for banning the relative form > >> >from raw import statements. > >> > >> Did you see the rationale toward the end? > > > > Yes. From my point of view, the . is an operator or a > > decorator. It is not a part of the name; if it was, the > > system would be unable to find the module on disk, > > because that name does not have the dot. > > > > The rationale makes no sense whatsoever. > > > Look at it this way: > > If you do "import abc.def.ghi", then the module ghi gets imported > (along with packages abc and def); however, only the only symbol that > gets bound is "abc". > > If you try to do "import .ghi", well, it's obvious that you're > imporing a sister module, but it's not clear what symbol should be > bound. (Do you bind "ghi" or "abc"?) Why isn't it clear? The way it currently works, if you use import foo, the name being bound is foo. I see no reason to change that. If you want something other than the first name in the string to be bound, then you use the from syntax. > According to the Python Zen: "In the face of ambiguity, refuse the > temptation to guess." Ergo, don't allow it. What's to guess? You're just complicating things for no good reason that I can discern. > But frankly, even if it were obvious, neither option makes sense. If > "import .ghi" means to bind the symbol "abc", then the code that uses > it has to know that "ghi" is found in package "abc.def". That pretty > much defeats the purpose of relative imports. It also makes the code > incredibly unclear to the reader. Which is why I am astonished that anyone would consider that seriously for more than about 10 nanoseconds. > If "import .ghi" means to bind the symbol "ghi", well, there's already > a way to do it, namely "from . import ghi". And there should only be > one way to do it. There is a concept called "conceptual integrity." Paying close attention to it is widely regarded as one way of making things comprehensible by eliminating special cases. This is a special case that I can see no compelling reason for. The only reasons given so far don't seem credible. John Roth > > > -- > CARL BANKS http://www.aerojockey.com/software > "If you believe in yourself, drink your school, stay on drugs, and > don't do milk, you can get work." > -- Parody of Mr. T from a Robert Smigel Cartoon From googlegroups.20.meeper at spamgourmet.com Fri May 21 16:45:47 2004 From: googlegroups.20.meeper at spamgourmet.com (336699) Date: 21 May 2004 13:45:47 -0700 Subject: Deleting Directories References: Message-ID: <65a376a0.0405211245.1923199a@posting.google.com> Look at the docs for the shutil module. It has a function called rmtree() that will do what you want. "Laura McCord" wrote in message news:... > I want to delete folders in my "/var/www/html/da" directory that are > over 1 day old. > > But, when I find the folder a simple rmdir() command does not work > because the directory is not empty. What else do I need to do to delete > a directory that contains content? From dave at pythonapocrypha.com Sat May 22 16:56:29 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 22 May 2004 14:56:29 -0600 Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: <064901c4403f$415c45a0$6500a8c0@YODA> David MacQuigg wrote: > >But the above explanation misses one very important point: one is used 99.9% of > >the time, the other 0.1% of the time, if that. Mentioning them side by side > >like you do implies that they are both equially common, which is not remotely > >the case. > > I can't comment on the usage statistics you cite, but it seems to me > that unbound methods are more important than these statistics would > imply. All I'm saying is that for most programs, the bound method form is way, way, way more commonly used than is the unbound calling form. > They are necessary to make the language complete, so you can > do things that would otherwise require creating an artificial instance > just to call a method. I don't disagree that they are necessary to make the language complete, but over and over again you have posted examples of the form "here's a bound method example, here's an unbound method example. They're different". Yes, they're different, but presenting them that way makes it sound like you normally have an equal mix of bound and unbound method calls, and that the difference is so subtle that confusion abounds. Neither is true in practice. > >> I know this is not terribly > >> difficult to understand -- one is a bound method, the other unbound. > >> Still it is a problem for beginners, and it leads to unecessary > >> complexities like static methods. > > > >I don't see how this is at all related to static methods. A method is some > >piece of functionality that is specific to a particular class. If you have some > >function already lying around, why would you want it as a method, much less a > >static method? (I can think of a couple of rather contrived examples, but > >nothing compelling or common in a normal application - help me out here) > > Here is an example from our CDP ( Circuit Design Platform ): > > class Bag: > def __init__(self, **kwargs): > self.__dict__.update(kwargs) > > def load(infile): > strng = infile.read() > exec( 'bag = Bag(\n' + strng + ')' ) > return bag > load = staticmethod(load) > > We need to load a "statefile" with a deeply nested hierarchy of > parameters, which will then be represented by a "Bag" of parameters at > each level of the hierarchy. The load method needs to be called > before any Bag exists, so we add the magic "staticmethod" line, and > don't worry about 'self'. Sure, we could move the load function > outside of the Bag class, but that would disrupt the natural structure > of the program. The load function is unique to Bags, and it belongs > in the Bag class. I know what static methods are _for_, but I don't see what is necessarily complex about them, nor how your proposed unification would help - in fact, ISTM that it would make it much more confusing because both the implementor and caller of the code would never be quite sure if the method was a static one or not, and that's something that needs to be known by both parties. Perhaps we both dislike the current staticmethod syntax of Python, but IMO making a static method look the same as a non-static method seems like a very wrong thing to do. They are quite different in purpose and construction, so to me it doesn't make sense that they should look the same in implementation OR in usage. See, to me it makes sense that there's no 'self' in a static method - since there's no instance for it to refer to. Likewise, it makes sense to me that there _is_ a self in a bound method, else member variable lookup would be magical (certainly more magical than the fact that a bound method knows what instance it belongs to). > See the thread "classes vs dicts" and the discussion following my post > on 5/13 for more on statefiles and Bags. See also > http://www.ece.arizona.edu/~edatools/Python/Statefiles for the latest > on our solution to the statefile problem (how to handle thousands of > deeply-nested setup parameters). Yes - I suggested the basis for your current solution. :) > >What kind of an instructor would bring this up in an introductory programming > >course? If you're short on time, there are oodles and oodles of more commonly > >used topics to cover. > > Seems like my challenging statement was misleading. I have no > intention of bringing up strange binding problems in an introductory > class. This was a challenge to those who think that Python's binding > syntax is simple. I'd say that first and foremost, it's powerful, and then simple. The example IMO shows an abuse of the power without a good reason to do so (my reaction to the example as "you're doing something odd for no good reason, and you get odd behavior, so what?"). The proposed unification does not seem to take into account the benefits of the current design - whether by choice or ignorance I don't know. > Have you read the proposal at > http://www.ece.arizona.edu/~edatools/Python ?? Yep. > When you say the distinction between methods and functions makes > sense, I assume you mean it has some value to the user. I would like > to hear more about this, because I am assuming just the opposite. Yes it has some value, but more than that: it fits the brain quite well. IMO it adheres to the principle of least surprise, if you are really thinking about what is going on (and this is why I haven't found it to be a problem for newbies, because they usually _aren't_ that interested in precisely what is going on). And if you're not really thinking about what is going on, it places a pretty minimal burden on you - there's only a handful of rules a blissfully ignorant programmer needs to adhere to, and that's pretty amazing. But once you do understand what is going on, then you can do some pretty powerful things that you can't do in e.g. Java (at least not directly and not without a lot of work). > >Most importantly, I've yet to see it cause any real or lasting problems for > >beginners - either (1) nobody cares unless you point it out and make an issue > >out of it, or (2) they ask, you take 30 seconds to explain it, and they say, > >"oh, ok" and move on. Occasionally someone particularly bright (and/or with > >experience in certain other languages) will really grasp the 'why' behind the > >difference, and you'll see the light go on as they begin to understand the > >power available to them. > > I think there is a tendency to assume that whatever you have learned > is just the way things have to be. Maybe, but I'm not arguing that the way things are is the way things have to be - I'm arguing that (1) the current way is better than all other proposals to date and (2) the specific proposal you've put forward introduces more problems than it solves and possibly results in a less powerful language (but I'm not sure because I haven't seen examples of how all calling use cases would be affected). > The best introductory text on Python is Mark Lutz' Learning Python, > 2nd ed. He takes 96 pages to cover OOP, and he doesn't waste time on > unnecessary topics like metaclasses. I believe an improvement in > Python's syntax could make it possible to cut the number of pages in > half, and still reach the same level of proficiency in solving real-world problems But has Mark told you that his goal was brevity? I bet you could cut the pages in half without ANY changes to the language, not because he did a poor job (he obviously didn't) but because you have different goals in mind. > Why is it we can see there is clutter in Perl, but we can't see it in Python? Nobody is taking that stance, as far as I can tell. -Dave From greg at cosc.canterbury.ac.nz Thu May 6 23:48:29 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 07 May 2004 15:48:29 +1200 Subject: Unification of Methods and Functions In-Reply-To: References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> Message-ID: <2g0f8iF34iasU1@uni-berlin.de> David MacQuigg wrote: > Wow, > you mean staticmethods aren't fundamentally necessary, just a bandaid > to make up for Python's deficiencies? In Python, staticmethods are not fundamentally necessary, full stop. We keep trying to tell you that, but it seems you have your fingers in your ears. The only possible reason to use a staticmethod in Python is if you want it to be in the class's namespace. But that's not a need, it's only a want. There are other ways of resolving namespace issues. Python didn't even *have* staticmethods until very recently, and programmers got on just fine without them. The only reason they were added is that the new descriptor mechanism made it easy to do so. In the past, every now and then someone (coming from C++) would ask how to create a static method in Python. They were added simply to appease these people. Regular Python programmers just carried on as usual and ignored staticmethods. Even now, staticmethods could be removed from the language entirely and very little would be affected. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mark at prothon.org Sat May 22 21:43:00 2004 From: mark at prothon.org (Mark Hahn) Date: Sat, 22 May 2004 18:43:00 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] Message-ID: <6iTrc.9506$bF3.8687@fed1read01> There is a new release of Prothon that I think is worth mentioning here. Prothon version 0.1.0 has changed almost beyond recognition compared to what was discussed here before. For example: the "Perl-like" symbols are gone and the "self" keyword is back, replacing the period. Prothon has gotten more "python-like", simpler, and more powerful, all at the same time. There is a new tutorial that covers Prothon completely without assuming any knowledge of Python or any other language. The Prothon/Python differences page now has links to the relevant section of this tutorial. See http://prothon.org. Some of these differences are: Locals and globals are gone and replaced by a simple scheme that allows you to access any local or external variable from inside a block or function scope by name. You may also modify any existing variable outside of the current scope by simply prepending "outer" to the variable name as in "outer.x = 1". You can even do this "outer access" when the variable is in a function that has quit running, giving you "closures" with no need for a special syntax. There is a new powerful self-binding method syntax that gives you the ability to explicitly specify the "self" to bind to a function call with "obj.func{self}(args)". This allows the full power of message-passing to be used without compromising the simplicity of function calling. This powerful and general scheme also solves the problem of calling methods when there is no such thing as a class to define what a method is. Intelligent defaults for {self} allow most method calls to be the intuiitive and simple form obj.call(). The "with" keyword now just creates a new local scope instead of another "self" which was so confusing before. So "self" is now the simple meaning of the instance object inside a method as it is in Python. There is a new "object" keyword which works almost identically to the "class" keyword, yet also works as a general object creation and initialization statement. It combines object creation and the "with" statement. From buzzard at urubu.freeserve.co.uk Wed May 19 10:22:14 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 19 May 2004 15:22:14 +0100 Subject: PERT for python References: Message-ID: "Juan Antonio Dom?nguez P?rez" wrote in message news:c8fhi7$qp1$1 at news.ya.com... > Can anoyone let me know if there is a standar PERT algorithm > implementation in python? > > Thanks in advance. > > -------------------------- > > Juan Antonio Dom?nguez P?rez > http://www.dominpe.com Not as far as I know, but I will be coding one up shortly. I'll write one (probably today / tomorrow) if you promise to give me some feedback :-). Duncan From alloydflanagan at comcast.net Thu May 13 17:49:53 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 13 May 2004 14:49:53 -0700 Subject: Python - open forever ? References: Message-ID: "Romans Krjukovs" wrote in message news:... > Hi ! > > - There is a risk that Python can become closed and unsupported in the > future. > (Remember RedHat ?) Even if someone were to come out with a version of python which was closed and unsupported, they can't stop you from using the versions that have already been released -- the python license is pretty clear about that. The other response is, who would do it? A number of companies, organizations, and individuals currently develop and support python. If one came out with a version to which they made some other license claim, the rest would simply ignore that version, and you could to. > - Who can guarantee that Python will be usable and available to us if > it is > develeped and maintained by the hackers from all over the world > without > any obligations and guarantees ? Is the version of python as it is right now usable? If so, it will always be available, no matter what. > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) Doesn't IBM support python now? I'm sure a number of smaller companies do. From insert at spam.here Wed May 5 11:18:53 2004 From: insert at spam.here (Doug Holton) Date: Wed, 05 May 2004 10:18:53 -0500 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: References: <109gh8ml6lo6o7b@news.supernews.com> Message-ID: > Yes, except the official doc would then need a link > at the bottom of each page pointing to the wiki. The > PHP docs have it all there in one page, no need to look > in two locations etc. I think it would be great to have moderated commentable docs like PHP. I'm not sure what docs to start off with though. The Python reference manual isn't written in a way that separates a page for each keyword or builtin like PHP's. Or should we start off with a combination of the manuals with an automatically generated reference from the standard library like this epydoc one: http://epydoc.sourceforge.net/stdlib/ or pydoc: http://pydoc.org/ Perhaps we could take all the reference documents and convert them from html to wiki and load them into the python wiki or another wiki, with a "comments" section added at the bottom of each page. We're talking hundreds of pages though. From jsbenson at bensonsystems.com Sat May 15 15:01:28 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 15 May 2004 12:01:28 -0700 Subject: Python vs. VBScript vs. JavaScript in context of Windows Scripting Host? Message-ID: <051601c43aaf$07874590$210110ac@jsbwxp3> Hi, I'm in a tightly-secured environment where I may not be allowed to use Python for some scripting work, and may have to fall back on what came with Windows 2K. I'm cracking "VBScript in a Nutshell" from O'Reilly, and have found a number of disappointments: * can't find "Introspection" in the Index * no record types, just numerically-indexed arrays, so record handling is kludgy * zero-based array indexing (this is Basic?) * script debugger is slanted towards debugging VBScript inside Internet Explorer * "on error resume next" pretty much sums up the error handling * truly bizarre use of parentheses to override argument passing by reference in a completely nonobvious context It looks pretty weak compared to Python, but I may not have the luxury of Python in this situation. Here's the question: If JavaScript is available to me within the Windows Scripting Host, can it do everything that VBScript can? My JavaScript documentation (the O'Reilly rhino book) is "client-side scripting"-centric, and as such accepts the limitations on file manipulation imposed by the client-side security scruples. Can anyone recommend a reference on JavaScript as an expedient replacement for Python within the context of the Windows Scripting Host? I know this isn't the real concern of this forum, but I know there are a lot of experienced generalists out there whose experience I would like to tap. Thanks in advance for any responses. From siona at chiark.greenend.org.uk Wed May 12 10:34:07 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 12 May 2004 15:34:07 +0100 (BST) Subject: wxpython demo under linux References: Message-ID: C GIllespie wrote: >I have wxpython under both windows and Linux. Under Windows there is a nice >little demo, which demonstrates all the widgets (with accompanied source >code). > >I presume the same demo is under Linux, but I can't find it. Where should I >look? I'm using Debian, is it a separate package? Yes, it is: wxwin2.2-examples for stable. Do an apt-cache show on your wxPython package and it should be listed as one of the suggested packages. -- \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 jgilbert+python at uvm.edu Mon May 31 14:20:21 2004 From: jgilbert+python at uvm.edu (Josh Gilbert) Date: Mon, 31 May 2004 14:20:21 -0400 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? In-Reply-To: References: <40B3E861.29B033D5@shaw.ca> Message-ID: Ville Vainio wrote: >>>>>>"Josh" == Josh Gilbert writes: > > > Josh> Oh my. It's utterly trivial with IPython. As in the > Josh> framework is all there, > > But isn't IPython solely for interactive use? > Yes, you are correct. A decided limitation. You can automatically save the Python statements from a session and paste them into a file, but you cannot edit an existing file in an interactive mode. I'm afraid I have to admit ignorace here, does Emacs offer more? Josh. From jgilbert+comp.lang.python at uvm.edu Thu May 27 15:47:44 2004 From: jgilbert+comp.lang.python at uvm.edu (Josh Gilbert) Date: Thu, 27 May 2004 15:47:44 -0400 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ville Vainio wrote: >>>>>> "Josh" == Josh Gilbert writes: > > > Josh> Now that's a great idea! Nlanguageigils stuff, I switched > Josh> from Perl to Python for a reason, I was putting sigils in my > Josh> English, C, and so on. > > I agree - the $ @ stuff was a (bad) joke, as I said elsewhere. > > Josh> There are two paths, have the IDE convert each line to > Josh> Python when you hit '\n' or as a batch. The first method > Josh> would allow it in Python shells. > > Live conversion would probably bring less surprises. > > Josh> This is a very good idea. I wonder how hard it will be. > > At least it doesn't *seem* difficult. It might even be easy enough to > do with regexps! > > Some syntax brainstorming again: > > d f x,y,z=12: -> def f(x,y,z=12): (, is one keystroke just like > space) > > d f x,y: -> def f(self,x,y): (d with indent, add self) > > p x; r x; -> print x; return x > > > a.b 1,2 ; a..b ; .a; -> a.b(1,2); a.b ; self.a; > > Sounds like a potentially fun emacs project, and the style of > programming that could be appreci8ed by TXT MSG gener8n :-). > Oh my. It's utterly trivial with IPython. As in the framework is all there, just plug in your rules. My implementation currently uses only regex's which could lead to errors in string literals or comments. However, it works. A more interesting implementation would be to write a full-blown parser for the shorthand language with a simple lookup table to translate it to real Python. I might get around to it, but probably not. I can't think of a way to save much more typing without being overly obscure. Well that was fun. I guess the only thing left for me to say is the vague handwaving of suggesting that the script could decode to another language, any language as long as you can define a one to one correspondence of terminals. So I could write Java that looked an awful lot like Python. Probably a bad idea. Josh - -- http://www.uvm.edu/~jgilbert/public_key.gpg -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAtkX13TWYZBkZ2IsRAiylAJ9oaFGHFoN0aRE8aGWxmyZIDt2c6ACbBBfB FG/DVh1ApDQyBvKRQeTW61g= =7Nwd -----END PGP SIGNATURE----- From tim.one at comcast.net Tue May 25 11:25:09 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 May 2004 11:25:09 -0400 Subject: r'\' - python parser bug? In-Reply-To: Message-ID: [Tim Peters] >> Yup. Right now all tools (including Python itself) that scan over >> strings in Python source can (and usually do) treat backslashes >> identically, whether in loops or in regexps. [] > Or in other words, the point here is that the prefix flag (u, r, > whatever) doesn't affect how a string literal is *parsed*. When the > parser sees a backslash inside a string literal, it always skips the > next character. There's no separate grammar for "raw string literals". Indeed, and that's a helpful amplification. Let's also amplify "the parser" to "a large number of distinct parsers, in a large number of programs that parse Python source". If it was only the Python compiler's parser that needed to change, it wouldn't be a *nightmare* to change (although Guido would still reject changing it). From dotsero at qwest.net Thu May 27 00:58:37 2004 From: dotsero at qwest.net (Michael Livsey) Date: Wed, 26 May 2004 22:58:37 -0600 Subject: EvNim uses neuroevolution to evolve an ANN that plays the gameof Nim In-Reply-To: <40B4D67B.7BDE9D5B@shaw.ca> References: <40B4D67B.7BDE9D5B@shaw.ca> Message-ID: Sorry about the off topic post. My mistake. I got two articles mixed up and accidently posted this one instead of the other. Mike SeeBelow at SeeBelow.Nut wrote: > Terry Reedy wrote: > >>"Michael Livsey" wrote in message >>news:gGVsc.99$rb.92248 at news.uswest.net... >> >>>The people at ANNEvolve have been working hard again and have released >>>EvNim 1.08. ... Evnim is written in standard C >> >>Does this have anything to do with Python; if not (and I cannot see any >>connection from what you posted), this is off-topic. > > > I think this was a mistake by our reporter. We recently released a > Python program, but it was not this one. I agree that it is off-topic. > > Mitchell Timin > From aahz at pythoncraft.com Thu May 6 00:11:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2004 00:11:39 -0400 Subject: Python documentation: How about structured documentation? Looking for comments/suggestions References: Message-ID: In article , Kenneth McDonald wrote: > >Both of those depend on a "documentation markup language", which >is something Python doesn't have, and which is a pain to define >and implement. But, Python can easily define such a markup >language, it would seem, simply by defining appropriate functions. http://docutils.sourceforge.net/ Not quite ready for prime time in terms of embedded Python docs, but it's getting there. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From peter at engcorp.com Thu May 27 19:24:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 May 2004 19:24:36 -0400 Subject: Sporadic problems importing xml.dom.minidom In-Reply-To: References: Message-ID: Michael Robinson wrote: > Michael Robinson wrote: > >> Sometimes when I run a program I get the message "Import:Error No >> Moduel named dom.domino", sometimes it imports OK. It seems to depend >> on the working directory when I star the program. >> >> /home/mike/projects/xml_test/test.py: >> >> Gives an erroor, the same file luanched from >> >> /home/mike/projects/xml1/test.py: >> >> runs without a problem >> >> I am running the python 2.3 package, bundeld with Fedora Core 2. > > I think i solved the problem. I had another file in those directorys > called xml.py, I guess that was interfeering That could do it, and possibly compounding your problem was that even a leftover xml.pyc file (from your xml.py file when it was imported another time) would still cause the trouble. If you do have a problem with a name collision like that, always be sure to nuke the .py *and* the .pyc file at the same time. -Peter From usenet at ixokai.net Sun May 16 02:53:57 2004 From: usenet at ixokai.net (Ixokai) Date: Sat, 15 May 2004 23:53:57 -0700 Subject: Python for Large Projects Message-ID: <10ae406ck3q1gb1@corp.supernews.com> Hello all. :) I've been a long time Python fan, and have fairly recently (with the support of a coworker who surprised me by mentioning my pet language one day) convinced my company to begin the colossal task of basically rewriting all of our software in Python. Woohoo. Previously we used a few different development environments, mostly Borland, for different products in our 'system' of thick clients sort of operating with eachother as they dug against a database. The whole thing is woefully out of date at this point, and platform-dependant, so we needed to switch to something.. and Python won. Yay. In the new platform, we'll be building a distributed system with CORBA (omniORB + omniORBpy, etc) with Python making up most of our development for the new edition of our software. Woohoo. Much fun. My question is not 'how suitable is Python for large projects?', but instead more, 'Do you have any advice for large projects with Python?'. For example, our system will be made up of numerous applications -- three or four 'servers', multiple clients, all talking to eachother, sharing a great deal of code. Any suggestions for organization? Our current plan is to put everything under the 'site-packages' tree of a Python installation we provide/control, with a fairly deeply nested tree: apt apt\library apt\library\corba.py apt\library\database\* apt\library\controls\* apt\application\globalapp1\ apt\application\globalapp2\ apt\system\editorial\application\client\ apt\system\editorial\application\client2\ apt\system\editorial\library\elementgrid.py ... etc. You get the idea, I hope. We have apt.library where we store all of our 'global', 'shared' libraries that everything can make use of, and apt.application with some global, shared apps. Then we have 'systems', which are a collection of applications and libraries in a single domain. These mostly get sold as a single product, really. Etc, etc. I end up doing a lot of: from apt.library.corba import * from apt.library.database import Connection from apt.library import machine from apt.system.editorial.library.elementgrid import ElementGrid ... And such. When PEP328 gets in, this may become more attractive, but occasionally I'm alarmed by the depth of the whole thing. But I also want to keep stuff logical and separated. And how about distribution? Freezing and such won't work, because of the shared nature of most of this code. Currently I'm probably planning on looking into finding the build scripts for python, win32all, and wxPython and seeing if I can combine them into one single install. Don't know if that's the best thing to do or not, but expecting my customers to install this stuff... is expecting too much of them. For example: Traditionally my company has avoided installing software on a users local machine. Instead we install to a file server and have everyone run the software from there. A bit of a performance hit but the advantage of administration is very important, because our customers do not necessarily have a very strong IT staff. There is some concern that if we do this same thing with Python, the performance hit of loading an interpreted environment over the shared filesystem will be prohibitive. Some basic testing has made this seem to be the case. hmm. That's all I have for now. I think. :) Thanks in advance. --Stephen From p at ulmcnett.com Mon May 17 19:36:23 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 17 May 2004 16:36:23 -0700 Subject: Timer events In-Reply-To: <67B3A7DA6591BE439001F2736233351202B47A65@xch-nw-28.nw.nos.boeing.com> References: <67B3A7DA6591BE439001F2736233351202B47A65@xch-nw-28.nw.nos.boeing.com> Message-ID: <200405171636.23232.p@ulmcnett.com> Laughlin, Joseph V writes: > If I want a function to be called every second, how would I > do this? Would I use timer events? The simplest but least flexible method is real easy: import time def myfunc(): print "myfunc", time.ctime() while True: myfunc() time.sleep(1) -- Paul From dmq at gain.com Fri May 7 20:20:39 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 07 May 2004 17:20:39 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> Message-ID: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:... >> I don't want to argue implementation details, as I am no expert, but I >> think you are saying something is wrong at the user level, and that >> puzzles me. >> >> A global function, if I understand your terminology correctly, is one >> defined at the module level, outside of any class. Such a function >> cannot have instance variables. If you were to reference that >> function from within a class, it would just act as a normal function >> (a static method in Python terminology). I can't see the problem. >> > >Let me give an example: > >def getLength(s): return s.length > >class Foo: > length = 5 > >Foo.getLength = getLength > >foo = Foo() >print length(foo), foo.length() The last two function calls don't work. There is no such function named 'length' and foo.length is an integer, not a function. Let me try to re-write this example as I think you intended: def getLength(self): return self.length # a global function class Foo: length = 5 Foo.getLength = getLength foo = Foo() foolen = foo.getLength # a bound method FooLen = Foo.getLength # an unbound method print foolen() #=> prints '5' print FooLen(foo) #=> prints '5' The example in the proposed syntax would be the same, except there would be no 'self' in the function definition, and there would be no magic first argument 'foo' in the last call. Also, if you are calling a function that has an instance variable ( .length ) and no instance has been set by a prior binding, you would need to set __self__ manually. __self__ = foo; print FooLen() This is rarely needed. Normally a call to an unbound function would be in a context where __self__ is already set. From the Animals_2.py example: cat1.talk() calls Cat.talk() which calls Mammal.talk() __self__ is set to cat1 on the first call, and it is not changed by the call to the unbound function Mammal.talk() >A method in a class in Python is just like a global function; for a >global function to operate on an object, it must take it as an >argument. The prototype syntax would appear to break the above >example. Global functions have no instance variables, so there is no need for a special first argument. A Python method requires a special first argument (even if it is not used). In the proposed syntax, global functions and class methods would have the same calling sequence ( no special first argument ). If the method has instance variables, it will use the global __self__ object, which was set to whatever instance called the method. Again, in Animals.py: Cat.show() has no instance variables, so it just ignores __self__. Cat.talk() has instance variables .name and .sound -- so these are interpreted as __self__.name and __self__.sound >> The difference in the proposed syntax is that it doesn't need the >> staticmethod wrapper to tell the interpreter -- don't expect a special >> first argument. In the new syntax all functions/methods will have the >> same calling sequence. > >If a method doesn't operate on the data from an object then as a rule >it should be global. There are exceptions, but they generally don't >occur in Python so much as a in 'true oo' language like Java. The placement of a function at the module level or in a class should be determined by the nature of the function, not any syntax problems. If the function has characteristics unique to a class, it ought to be included with that class. The Mammal.show() function, for example, provides a display of characteristics unique to mammals, so we put it in class Mammal. We could have written a general-purpose Inventory() function to recursively walk an arbitrary class hierarchy and print the number of instances of each class. That general function would be best placed at the global level, outside of any one class. >> I've looked at a few introductions to Python, and in my opinion >> Learning Python, 2nd ed, by Mark Lutz and David Ascher is the best. >> It strikes a good balance between the minimal presentation that >> tersely covers the essentials for an experienced programmer vs the >> long, windy introductions that put you to sleep with analogies to car >> parts and other "objects". Lutz takes 95 pages to cover OOP. I think >> I could do a little better, maybe 70 pages, but that may be just my >> ego :>) >> >> When you say ten pages, you must be making some very different >> assumptions about the students or their prior background, or the >> desired level of proficiency. The least I can imagine is about 30 >> pages, if we include exercises and examples. And that 30 assumes we >> get rid of all the unneccesary complexity (static methods, lambdas, >> etc.) that currently fills the pages of Learning Python. >> > >I'm assuming they alreay know the general structures of programming in >Python, and that you can then just show them how to package data and >methods into a class with a clear example, by rewriting a program >you've shown them before. After that it's mainly a question of >explaining why you should do it, which is probably rather more >important than how. *Why* is not an issue with my students. They will have plenty of examples in our circuit design program to look at. If anyone ever asks "Why OOP", I'll just have them look at the Qt Toolkit, which will be the basis of our user interface. Enormous complexity, packaged in a very easy-to-use set of objects. I need to show them *how* to undestand the OOP structures in that program, and do it in the most efficient way. The chapter on Prototypes at http://ece.arizona.edu/~edatools/Python/ is my best effort so far. I've got the basic explanation down to 10 pages. I expect this to expand to about 30 with examples and exercises. That will be about four hours of additional work, including lecture, reading, and practice. >I've never met anyone who had difficulty in understanding anything >about the syntax of OO other than the class/object distinction. It's >fundamentally very simple once you have a basis in all the other >programming techniques. I guess you haven't met anyone learning C++. :>) >Unless you're talking about the entire programming course, 70 pages is >waaay too much - your students just will not read them, regardless of >how brilliant they are. Learning Python, 2nd ed. by Mark Lutz and David Ascher is generally considered the best introductory text on Python. 96 pages on OOP. [snip a few paragraphs where we agree !! :>) ] >> >I must note that Animals_2 is a total abuse of OOP techniques. You >> >continuously define classes to do the same thing, repeat the same code >> >in each, then give them slightly different names. >> >> This is a textbook introduction, not a real program. The purpose of >> the example is to show a complete OOP hierarchy in a small example, >> with a good selection of the method styles most needed in a real >> program. The similarity between the show() methods in different >> classes would not be so tempting to reduce to one global function if I >> had made a larger example, with more radically different outputs from >> each show function. I thought that just changing one string in each >> function would be enough to say "This function is different." > >OOP is a tool. It's abstraction makes it tempting to create arbitrary >structures as examples, but doing that looses any sense of the reason >why you would use that tool. That's why I see people with CS degrees >who can throw around objects and heirarchies at will but who can't >structure a simple program effectively. > >> You are not the only one who had this reaction. See my reply to Don >> Cave above. I guess I need to thow in a little more "meat", so that >> experienced programmers don't get distracted by the possibility of >> making the whole program simpler by taking advantage of its >> regularities. This is the same problem I've seen in many texts on >> OOP. You really can't see the advantages of OOP in a short example if >> you look at it with the attitude -- I can do that much more easily >> without classes. It's when you get to really big complex hierarchies >> that the advantages of OOP become clear. > >Learning to program is about 5% how to do something, and 95% when and >why you should do it. You seem to be focusing almost exclusively on >how, which I suspect is why we're all so upset :) you get that way >when you have to fix the code which eventually results. The OOP presentations I've seen that focus as much as 50% on *why* generally leave me bored and frustrated. I feel like screaming -- Stop talking about car parts and show me some nice code examples. If it's useful, I'm motivated. Good style is a separate issue, also best taught with good examples (and some bad for contrast). >> >Also, your show method is IMO more than dubious. show does not >> >logically belong to Feline. As a result you are using a class to >> >display data about other classes to which it is not connected. This >> >is not OOP. >> >> I thought this part was pretty clear. The show() method at each level >> calls the show() method one level up, then adds its own stuff at the >> end. Feline.show() calls Mammal.show(), which prints lots of stuff >> characteristic of mammals, all in a format unique to the Mammal class. >> Mammal.show() in turn calls Animal.show(). At each level we have some >> unique display of characteristics. The purpose is to have a call at a >> particular level show all characteristics of the animal from that >> level up. > >It is clear, just not a good idea. > >> >If I were teaching someone and they produced this structure then I'd >> >go over the rationale with them and try to figure out where they went >> >wrong in their planning of the program, and maybe go back and tutor >> >them on the basic ideas of OOP. I would not change the language to >> >make it easier to do in future. :) >> >> Both responses I have on this are basically experts saying -- you can >> solve this particular problem more easily by restructuring it. I >> should have been more clear. Imagine that each of these classes and >> methods is fully expanded with lots of parameters to make each one >> unique. Don't even think about re-structuring, unless you are trying >> to tell me that the whole idea of having these structures in any >> program is wrong. That would surprise me, since this "animals" >> example is a common illustration of OOP. >> > >OK: "The whole idea of having these structures in any program is >wrong." > >Firstly, the program uses a class hierarchy as a data structure. That >isn't what class heirarchies are designed for, and not how they should >be used IMO. But it's what any bright student will pick up from the >example. The classes contain both data and functions. The data is specific to each class. I even show an example of where the two-class first example forced us to put some data at an inappropriate level, but with a four class hierarchy, we can put each data item right where it belongs. >Secondly, it breaks the entire concept of OOP. Objects are designed >to be individual entities with side-effects restricted to their scope, >in order to modularize programs. > >In this example, you use side effects from one class to influence the >output of another; a bovine will end up influencing the output of a >cat, for example. And the effect in completely implicit. As a >result, someone who is introducing a mouse class can break another >part of your system without the faintest idea that they are affecting >it. It's a fragile structure leading to the almost inevitable >creation of the most intractable type of bug. > >The fact that Python makes it hard to do is *good*. Nothing in the Bovine class can affect anything in a Cat. Feline and Bovine are independent branches below Mammal. Adding a Mouse class anywhere other than in the chain Cat - Feline - Mammal - Animal cannot affect Cat. Could you give a specific example? I'm not sure what you mean by "side effects" here. The show() function at each level is completely independent of the show() function at another level. Chaining them together results in a sequence of calls, and a sequence of outputs that is exactly what we want. The nice thing about separating the total "show" functionality into parts specific to each class is that when we add a class in the middle, as I did with Feline, inserted between Mammal and Cat, it is real easy to change the Cat class to accomodate the insertion. Python has a 'super' function to facilitate this kind of chaining. Michele Simionato's 'prototype.py' module makes 'super' even easier to use. Instead of having Cat.show() call Mammal.show() I can now just say super.show() and it will automatically call the show() function from whatever class is the current parent. Then when I add a Feline class between Mammal and Cat, I don't even need to change the internals of Cat. >> What I'm looking for is not clever re-structuring, but just a >> straightforward translation, and some comments along the way -- oh >> yes, that is a little awkward having to use a staticmethod here. Wow, >> you mean staticmethods aren't fundamentally necessary, just a bandaid >> to make up for Python's deficiencies? That was my reaction when I >> first saw Prothon. > >Static methods are more like a band-aid to make up for the >deficiencies of OOP. Python isn't a pure OO language, and doesn't >suffer the need for them badly. In one syntax we need special "static methods" to handle calls where a specific instance is not available, or not appropriate. In another syntax we can do the same thing with one universal function form. -- Dave From danb_83 at yahoo.com Tue May 25 02:49:42 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 May 2004 23:49:42 -0700 Subject: Prothon vs. Python integers References: Message-ID: Heather Coppersmith wrote in message news:... ... > > Longs seemed like a needless exotic kludge to me in the 64-bit > > world. Surely once you get to 3.7e19 you are in floating point > > territory. I can't imagine counting anything up to 10**19. > > Beans? ;-) > > Accountants ("bean counters," in the derogatory vernacular) will > be displeased if Prothon silently loses pennies (or other small- > valued currencies) after a certain amount Or credit card numbers. They're 16 digits long, and Microsoft Excel has this inconvenient feature of displaying them with 15 significant digits. > (lira and drachma spring to mind, too). The Italian Lira and Greek Drachma have been replaced by the Euro. However, the *Turkish* lira hasn't, and I think it takes 500 000 of those just to buy a candy bar. From heikowu at ceosg.de Tue May 18 08:52:51 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 18 May 2004 14:52:51 +0200 Subject: how to keep one instance??? In-Reply-To: <20040518124627.GH14843@unpythonic.net> References: <200405180732.i4I7WGb19062@bald.unpythonic.net> <20040518124627.GH14843@unpythonic.net> Message-ID: <200405181452.51644.heikowu@ceosg.de> Am Dienstag, 18. Mai 2004 14:46 schrieb Jeff Epler: > Note that there are often race conditions here---if two copies of the > application start nearly simultaneously, both may detect that no > other copy of the app exists. If someone wants to tell me the way to > get this right in the context of Unix/X11, please speak up! Lock files in /tmp? Simply do file-based locking the daemon PID-file style... If you need code (which is race-free) to handle this, mail me, and I'll gladly send it to you. Heiko. From tjreedy at udel.edu Wed May 19 17:57:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2004 17:57:11 -0400 Subject: Scope rule pecularities References: Message-ID: "Josiah Carlson" wrote in message news:c8ge9k$7le$1 at news.service.uci.edu... > As you mentioned later, in C, you can use *a = 1 to modify a single > instance of 'a'. However, immutables in Python never do the *a = 1 > assignment. Mutables do so, I am not sure what you mean to say that mutables 'do the *a=1 assignment'. This does not strike me as a useful viewpoint for understanding Python. >which is why the final line of... > m = n = [] At this point, m is n, not merely m == n. Both names are bound to one and the same object. > m.append(7) At this point m is still n since mutation of the one and same object (a list, in this case) may bind or rebind indexed *slots* within the collection object but does not rebind either 'm', 'n', or any other name. I don't see that the C-ism '*a=1' adds anything to this explanation. > m == n Because m is n ==> m == n for anything without funny special methods that disable the implication. > For immutables, on modification, a new instance of the immutable is > created, the value being set accordingly. Since immutable objects cannot be modified, I am not sure what you are saying. In any case, name = expression always binds or rebinds name to the object calculated by expression, regardless of the mutability of the object, if any, previously bound to name. Similarly, except for possible bizarre methods, name.method(args) never rebinds name, regardless of the mutability of the associated object. (One possible exception: name is bound at global scope and method checks globals to find all names bound to self and then modifies globals to rebind all such names to something else. But no builtin method does anything like this.) > Now that we've gotten to the point, __iadd__ and friends, we know we > disagree. If you feel terribly strongly about it, post a bug report or > feature requrest to SF. No, please do not burden the volunteer developers with false bug reports or useless feature requests. The semantics of += and family were debated when added a few years ago and will not change for the foreseeable future. Keep repeated debate and explanation of such things to c.l.p. > I would venture a guess that within a week it > will be closed with a message stating, "yeah, we like it the way it is". Or it might hang around a couple of years while people focus on real problems. About dictionaries: keys must be hashable (have __hash__ method); mutability is not directly involved (and there is indeed no direct test for such). It would have been possible to key dictionaries by object id, and one can do so for user classes with def __hash__(s): return id(s). But for fairly obvious reasons, builtins are hashed and keyed by value. Perhaps less obviously, this can be true even across types. >>> d={0:'zero'} >>> d[0.0] 'zero' >>> d[0+0j] 'zero' >>> d[''] = 'empty' >>> d[u''] 'empty' Terry J. Reedy From jcarlson at uci.edu Thu May 6 11:33:57 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 06 May 2004 08:33:57 -0700 Subject: Where is IDLE? In-Reply-To: References: Message-ID: > There are lots of Python IDEs, why do you want to implement another one ? It is fun? You learn more about the language? You get fan mail? Other editors don't satisfy your needs. Pick one, all, or some other reason not listed. - Josiah From NOS at Utel.no Sun May 16 19:23:39 2004 From: NOS at Utel.no (=?iso-8859-1?q?Nils_O=2E_Sel=E5sdal?=) Date: Mon, 17 May 2004 01:23:39 +0200 Subject: sys.argv[0] and ps aux References: Message-ID: And Heiko Wundram said... > Hi all! > > Is there some way to set sys.argv[0] on a Unix platform and have the > string which is set show up in the output of ps aux? IIRC when I (re)set > argv[0] in C, the newly set string pops up in ps aux (but I may be wrong > here, it's a long time since I last programmed in C... ;)). Not any general way in python. Some have a C setproctitle function. On others you have to do arcane mangeling with the (C) argv array. In short, no. From jdhunter at ace.bsd.uchicago.edu Mon May 3 07:10:23 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 03 May 2004 06:10:23 -0500 Subject: Need Suggestions for Python/Tk/VTK In-Reply-To: <4095C545.1030907@netscape.net> (Yang Wang's message of "Mon, 03 May 2004 00:06:29 -0400") References: <4095C545.1030907@netscape.net> Message-ID: >>>>> "Yang" == Yang Wang writes: Yang> Dear All, I am totally new to Python, however had some Yang> experience with Tcl/Tk. Currently I am doing a project that Yang> will need Python/Tk as well as VTK(Visualization Toolkit) Yang> for image processing and visualization. Yang> Have anyone had any experience in this that can give me some Yang> suggestions or references? In the Examples dir of the VTK src, there are many examples that use VTK/Tk/Python. John Hunter From CousinStanley at HotMail.Com Mon May 17 02:18:48 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Sun, 16 May 2004 23:18:48 -0700 Subject: Where do I find what colors and fonts are available? References: <40A3FD3E.B1B71DA8@shaw.ca> <40A7884F.320C8D4A@shaw.ca> Message-ID: > Thanks, Couz, that's very good info. Mitchell .... You're welcome .... I'm glad I could help out a bit .... -- Cousin Stanley Human Being Phoenix, Arizona From harry.g.george at boeing.com Wed May 19 12:03:39 2004 From: harry.g.george at boeing.com (Harry George) Date: Wed, 19 May 2004 16:03:39 GMT Subject: unique number generator References: <5da2b26991d290ff30a502d392812f4b@news.teranews.com> Message-ID: "Joe Wong" writes: > Hi, > > There is a constraint that the number can be at most 8 digits, ie: > > 00000000 ~ 99999999 > > No hex decimal is allowed... > > And I am on Linux platform.. > > Any other suggestion? :-) > I hope you get to control all the generators for this number. Otherwise different algorithms may accidentally overlap even if they are properly unique in their own streams. Given that, you need a unique number up to 1e9. 1. If you can get the traditional GUID based on MAC+timestamp+random, you might hash that down to a digital signature in your number range. This increases the possibility of overlaps, but it might be acceptable in your context. E.g., do an md5 on your guid and take the lower 7 hex digits. 2. If there are characteristics of the problem space which are themselves unique, then you might do a canonical mapping from that to integers. If you are lucky, this could be a dense mapping (no skipped integers), and thus able to support a billion unique items. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From fredrik at pythonware.com Mon May 24 03:48:02 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 May 2004 09:48:02 +0200 Subject: And *this* is why you need Perl!? References: <87fzaqmm8t.fsf@strauser.com><38ec68a6.0404262308.50029919@posting.google.com><108t8pvam9q139c@corp.supernews.com> Message-ID: Peter Hansen wrote: > "Denouncing" it definitely was. I wanted to find the original > source for myself, and Google conveniently provided it. Still > fun reading, and quite relevant to the thread: > > http://slashdot.org/comments.pl?sid=19607&cid=1871619 if you're referring to the "I know, I'll use regular expressions" quote, jwz was quoting himself in that thread. from what I can tell, the original post is here (from 1997): http://groups.google.com/groups?selm=33F0C496.370D7C45%40netscape.com&output=gplain the next google hit is in this comp.lang.python-post from 1998: http://groups.google.com/groups?selm=01bd8adb%24719bd1b0%24f29b12c2%40panik.pythonware.com&output=gplain I used it again in my Standard Library book in 1999 http://effbot.org/zone/librarybook-index.htm and it has been very popular with comp.lang.python posters and Python book authors ever since. (some even remember to fix the broken attribution from my post/book, but many don't, so it's easy to see who's copying from my book ;-) From pit.grinja at gmx.de Fri May 21 14:34:25 2004 From: pit.grinja at gmx.de (Piet) Date: 21 May 2004 11:34:25 -0700 Subject: wxPython: Need method to remove items from sizer Message-ID: <39cbe663.0405211034.650b6c9d@posting.google.com> Hello wxPythoneers. I have a problem with a dialog box derived from wxFrame which has a wxComboBox as main element. Depending on the entry selected from the ComboBox, the dialog box will be populated with a number of controls. This works fine for the first selection of a combobox item, but subsequent selections from the combobox cause problems. This is because the event function for the combobox populates the sizer for the window with items though the sizer already has some items. Thus, I think that I need a method to clear the items from a sizer. Please let me know your suggestions about how to reach this goal. When you find other odds in the following script, please let me know these as well. I have described the problems with this "dyamic dialog" in two other threads, but I believe that the information supplied there was not sufficient to make the problem clear. BTW, I am aware of the Detach-Function of Sizers, but I dont think they are the solution to my problem. This method seems only to be able to remove a sizer completely (which is not want I want, because the sizer will be repopulated in the next step, and I dont want to recreate it, because the sizer has to keep its position in the dialog relative to the other sizers) or to remove the item with the specified position (which is no alternative as well, because the number of childs or controls in the sizer will vary). Many thanks in advance Piet Code: #### #-*- coding: UTF-8 -*- from wxPython.wx import * from wxPython.lib.rcsizer import RowColSizer #____________________________ class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,id, title, style=wxDEFAULT_FRAME_STYLE|wxFULL_REPAINT_ON_RESIZE) self.panel = wxPanel(self,-1) self.mainsizer = wxBoxSizer(wxVERTICAL) self.mainsizer.Add(self.panel,1,wxEXPAND|wxALL) self.ID_LBOX = 100 self.ID_CBOX_VARTYPES = 101 self.ID_CBOX_ACTIONS = 102 self.BtnSave = wxButton(self.panel,wxID_OK,"Save") self.BtnClose = wxButton(self.panel,wxID_CANCEL,"Close") self.DlgBtnSizer = wxBoxSizer(wxHORIZONTAL) self.DlgBtnSizer.Add(self.BtnSave,1,wxALIGN_CENTER|wxALL,) self.DlgBtnSizer.Add(self.BtnClose,1,wxALIGN_CENTER|wxALL) self.ControlSizer = RowColSizer() self.HeaderSizer = wxBoxSizer(wxVERTICAL) self.SubHeaderSizer = wxBoxSizer(wxVERTICAL) self.Textbox = [] self.Textlabels = [] self.MasterSizer=wxBoxSizer(wxVERTICAL) self.MasterSizer.Add(self.HeaderSizer,0,wxALIGN_CENTER) self.MasterSizer.Add(self.SubHeaderSizer,0,wxALIGN_CENTER) self.MasterSizer.AddSizer(self.ControlSizer,0,wxALIGN_CENTER) self.MasterSizer.AddSizer(self.DlgBtnSizer,0,wxALIGN_CENTER) self.ChooseAction = wxComboBox(self.panel,self.ID_CBOX_ACTIONS,"New Column",choices = ["New Database","New Table","New Column"],size=(180,-1),style=wxCB_READONLY) EVT_COMBOBOX(self,self.ID_CBOX_ACTIONS,self.OnActionsCboxChange) self.HeaderSizer.Add(wxStaticText(self.panel,-1,"Actions:",size=(200,48)),1,wxALIGN_LEFT) self.HeaderSizer.Add(self.ChooseAction,0,wxEXPAND) self.panel.SetSizer(self.MasterSizer) self.panel.SetAutoLayout(True) self.MasterSizer.Fit(self.panel) self.panel.Fit() self.Fit() self.Show(True) def OnActionsCboxChange(self,event): if self.ChooseAction.GetValue() == "New Column": self.columnTypes = wxComboBox(self.panel,self.ID_CBOX_VARTYPES,"Varchar",choices = ["Char","Varchar","Tinyint","Smallint","Mediumint","Integer","Float"],size=(180,-1),style=wxCB_READONLY) self.SubHeaderSizer.Add(wxStaticText(self.panel,-1,"Column types:",size=(200,48)),1,wxALIGN_LEFT) self.SubHeaderSizer.Add(self.columnTypes,0,wxEXPAND) controls = ["Name","Width","Decimals"] for i in range(len(controls)): self.Textlabels.append(wxStaticText(self.panel,-1,controls[i])) self.Textbox.append(wxTextCtrl(self.panel,-1,"",size=(180,-1),name=controls[i])) self.ControlSizer.Add(self.Textlabels[i],row=i+1,col=0,flag=wxALIGN_CENTER_VERTICAL|wxALL) self.ControlSizer.Add(self.Textbox[i],row=i+1,col=1,flag=wxALIGN_CENTER_VERTICAL|wxALL) self.extras = wxListBox(self.panel,self.ID_LBOX,choices=[],size=(96,96),style = wxLB_MULTIPLE) self.ControlSizer.Add(wxStaticText(self.panel,-1,"Extras"),row=4,col=0,flag=wxALIGN_CENTER_VERTICAL|wxALL) self.ControlSizer.Add(self.extras,row=4,col=1,flag=wxALIGN_TOP) self.MasterSizer.RecalcSizes() self.panel.Fit() self.Fit() #____________________________ app = wxPySimpleApp() frame = MainWindow(None, -1, "MySQL Frontend") frame.Show(1) app.MainLoop()#### From NOS at Utel.no Mon May 17 07:02:21 2004 From: NOS at Utel.no (=?iso-8859-1?q?Nils_O=2E_Sel=E5sdal?=) Date: Mon, 17 May 2004 13:02:21 +0200 Subject: What's active and worthwhile in the Python 3D world? References: Message-ID: And Kenneth McDonald said... > In fact, there seem to be quite a few--so many that I'm not really sure > what is active and growing, and what is dying off. So I was wondering if > there are Pythonistas out there with similar interests, and if so, what > you might recommend looking at? > > I realize this is broad in scope, but I really am just looking to play > right now. If I were to state a long-term interest, it might be in a > modeller that had a more command-oriented (as opposed to GUI) approach to > modelling, but there are many things I could be interested in. As you said, a broad scope. Blender (www.blender.org/www.blender3d.com) is a Python scriptable 3D Modeller/Renderer. From imbosol at aerojockey.invalid Sat May 22 01:54:24 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sat, 22 May 2004 05:54:24 GMT Subject: Python compilers? References: <38Yqc.166$eO6.128@fe2.columbus.rr.com> <7x1xlf8p9z.fsf@ruckus.brouhaha.com> <7xzn81rue6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Carl Banks writes: >> If I recall, + can work on ints, floats, bignums, rationals, and >> complex numbers, at least. What one instruction does + compile to >> here? > > Lisp supports type declarations which advise the compiler in those > situations. A few such proposals have been made for Python, but none > have taken off so far. Yes, that's been established. There's two questions remaining for me: 1. These claims that Lisp code can approach 50 percent the speed of C, is that with or without the optional type declarations? 2. If you don't use the declarations, does compiling Lisp help? If it does (and nothing I've read indicated that is doesn't), it definitely casts some doubt on the claim that compiling Python wouldn't help. That's kind of been my point all along. I think (and I'm wrapping this up, cause I think I made my point) compiling Python could help, even without type declarations, but probably not as much as in Lisp. It could still make inferences or educated guesses, like Lisp compilers do; just maybe not as often. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From rupole at hotmail.com Wed May 5 00:49:43 2004 From: rupole at hotmail.com (Roger Upole) Date: Wed, 5 May 2004 00:49:43 -0400 Subject: NT Service and -OO option ??? References: Message-ID: <40986e8c_3@127.0.0.1> You should be able to set environment var PYTHONOPTIMIZE=1 to have the same effect as -OO. I tried this with the demo pipeTestService.py, and it starts (after reboot) with only the pyo file present. hth Roger "Sylwia" wrote in message news:f6554b84.0405040319.5820a710 at posting.google.com... > Hi! > > I have the following problem and I need Your advice. > > I implement Windows NT service using Mark Hammond's win32 extensions. > I have 3 files in my service's folder: > > exampleservice.py > exampleservice.pyc > exampleservice.pyo > > At the customer the companies usually want to deliver ONLY pyo files. > > Thus the NT service written in Python should be able to run without > the exampleservice.py and the exampleservice.pyc files, but of course > after deletion of those 2 files, the start of the created > exampleservice fails. > Is it possible to start the winservice with the -OO option? If yes, > how can I do it? > > Thank You in advance for any hints. > > Best Regards, > > Niki From mhuening at zedat.fu-berlin.de Tue May 11 02:57:58 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 11 May 2004 06:57:58 GMT Subject: CGI Proplem displaying image References: Message-ID: matthiasjanes at gmx.net (matthiasjanes) wrote in news:d588131f.0405102237.15106ea5 at posting.google.com: > Some Text > > You are trying to mix HTML and the output of a Python script. That won't work. You'll have to use SSI (server side includes) to do this. With SSI you could run a script from within a HTML page and print the output of the script in that page. Another solution: use a CGI-script and let that script generate the whole HTML page. Perhaps this would help to get you starting: http://www.python.org/topics/web/ Matthias From deetsNOSPAM at web.de Tue May 18 10:57:50 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 May 2004 16:57:50 +0200 Subject: module for working with the result set References: <_wbqc.68175$eT6.35900@newssvr25.news.prodigy.com> <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> <2gu341F67e61U1@uni-berlin.de> Message-ID: <2gumojF6v4fvU1@uni-berlin.de> > myfields=mycur.description > #since I already had the data I used it. > d = dict(zip(myfields,mydata[0])) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: list objects are unhashable ah, I forgot that the description contains more than the name. But I see you figured that out yourself. > > then I'd expect your code to work but I get a list of tuples > [('csono', '5992 '), ('crevision', 'A') ......] > What I expected to see was > {'csono': '5992 '...} You most probably forgot the dict around the zip, as this works: >>> dict([('csono', '5992 '), ('crevision', 'A')]) {'csono': '5992 ', 'crevision': 'A'} The builtin dict takes a list of tuples and makes them a dictinairy with keys from the first element of the tuple and values from the second. -- Regards, Diez B. Roggisch From sdfATexpertuneDOTcom Tue May 18 12:47:58 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Tue, 18 May 2004 16:47:58 -0000 Subject: How to just wait 3 secs ? References: Message-ID: Marcello Pietrobon wrote in news:mailman.50.1084893955.6949.python-list at python.org: > I would like to make my script to wait 3 seconds ( so I can read the > output on the console ) > and then continue. > How do I do it ? from time import sleep sleep(3) From iamlevis3 at hotmail.com Mon May 17 22:26:34 2004 From: iamlevis3 at hotmail.com (Chris) Date: 17 May 2004 19:26:34 -0700 Subject: Cache a large list to disk References: <939f49f8.0405171155.1de74c2a@posting.google.com> Message-ID: <939f49f8.0405171826.15490920@posting.google.com> Ah, poifect =) This'll do just fine. Thanks, folks. Karl Chen wrote in message news:... > Use the pickle or shelve modules. > > http://www.python.org/doc/current/lib/module-pickle.html > > http://www.python.org/doc/current/lib/module-shelve.html > > >>>>> "Chris" == Chris writes: > Chris> straightforward manner. But being new to Python, I > Chris> don't know how I can (hopefully easily) write this data > Chris> to a file, and then read it out into memory on > Chris> subsequent launches. From moughanj at tcd.ie Thu May 6 11:37:50 2004 From: moughanj at tcd.ie (James Moughan) Date: 6 May 2004 08:37:50 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> Message-ID: <16752bcc.0405060737.bd43802@posting.google.com> > > The statement about global variables is the only thing that surprises > me. You mentioned them in your first post in the thread, which gave me the impression I expressed there; my bad, if that's not what you intended. >Have you read the explanations of instance variables at the end > of http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm > Does this change your thinking? > > Explanation of Simplified Instance Variables > -------------------------------------------- > """ Some of the variables inside the functions in a prototype have a > leading dot. This is to distinguish local variables in the function > from "instance variables". When a function is called from an instance > ( cat1.talk() ) a special global variable __self__ is automatically > assigned to that instance ( __self__ = cat1 ) Then when the function > needs an instance variable ( .sound ) it uses __self__ just as if you > had typed it in front of the dot ( __self__.sound ) The leading dot > is just an abbreviation to avoid typing __self__ everywhere. """ > The changes would go beyond a simple change of syntax; it would break the python functional object model, e.g. as you couldn't write a global function and assign it to a class at runtime. (I'm not saying this is a good thing to do :) I'm saying that this is not a trivial matter of syntax.) > > Python is clearly superior to C++ and Java for what I need ( teaching > EE students and professional engineers ). Still, it isn't perfect. I > believe a good presentation of OOP could be done in 50 pages ( about > half of what is now in Learning Python, 2nd ed.) I believe a good working introduction could be done in 10, at most. OOP is not complex. It's even simple enough for managers to (think they) understand, which leads the slightly bizzare state of programming today. > The key to this simplification is not having to discuss static methods > or any other method form. All methods are called just like normal > functions, which the students already understand at this point in the > course. They are already called like normal functions, though. You can copy-paste a method as a global function and it will still work. Your syntax introduces a special case which makes them distinct, by use of a specific method-only dot notation. > > --------------------------- > > I think the learning process you describe above is quite common. I > went through the same initial steps. At first I was puzzled by the > strange 'self' first argument, and annoyed at typing 'self' in so many > places. Then I understood the magic first argument, and got used to > the extra typing. It did not occur to me that there was some > unnecessary complexity yet to come. I had not yet seen how 'self' is > handled in Ruby and in Prothon. I did not learn about static methods > and other forms until much later, and 'lambdas' were something weird > related to "lambda calculus". There are static methods in Python? :) In my coding the major reason for static methods is for data encapsulation for singleton-style elements. Python has no data encapsulation worth anything, so static methods don't do much that's useful. > The second problem with the "avoidance/denial" strategy is that it > involves moving the troublesome functions outside of the class > definition. This results in a less-than-optimal structure for your > program. Look at the show() methods in Animals_2.py They must be > callable without any specific instance. Moving them outside the > appropriate classes is not good programming. When you want to change > a class later, you will need to remember to look in some other place > for any "static methods" associated with the class. > > If you could do me one more favor, please take a look at the > Animals_2.py example starting on page 7 of the Prototypes document at > http://ece.arizona.edu/~edatools/Python Can you write this in Python? > Give it a try, and let me know if you had any difficulties. Were > there any parts you had to stop and think, or look up in a manual? > I am not copy-pasting the whole thing, but I think this demonstrates the functionality you want. It ain't pretty, but I'll discuss that in a second. class static: def __init__(self, fun): self.__call__ = fun class Mammal: numMammals = 0 def __init__(self): Mammal.numMammals += 1 def show(): print "Inventory:" print " Mammals:", Mammal.numMammals show = static(show) class Feline(Mammal): numFelines = 0 def __init__(self): Feline.numFelines += 1 Mammal.__init__(self) def show(): Mammal.show() print " Felines:", Feline.numFelines show = static(show) m = Mammal() f = Feline() print Mammal.numMammals, Feline.numFelines, '\n' Feline.show() I must note that Animals_2 is a total abuse of OOP techniques. You continuously define classes to do the same thing, repeat the same code in each, then give them slightly different names. Also, your show method is IMO more than dubious. show does not logically belong to Feline. As a result you are using a class to display data about other classes to which it is not connected. This is not OOP. If I were teaching someone and they produced this structure then I'd go over the rationale with them and try to figure out where they went wrong in their planning of the program, and maybe go back and tutor them on the basic ideas of OOP. I would not change the language to make it easier to do in future. :) > I appreciate the effort it takes to thoroughly investigate this issue. > > -- Dave From fumanchu at amor.org Mon May 31 09:30:24 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 31 May 2004 06:30:24 -0700 Subject: Regexp: unexspected splitting of string in several groups Message-ID: Piet wrote: > vartype(width[,decimals]|list) further variable attributes. > Typical examples are: > char(30) binary > int(10) zerofill > float(3,2)... > I would like to extract the vartype, the bracketed string and the > further properties separately and thus defined the following regular > expression: > #snip > vartypePattern = re.compile("([a-zA-Z]+)(\(.*\))*([^(].*[^)])") > vartypeSplit = vartypePattern.match("float(3,2) not null") You might try collecting the parentheses and "further attributes" into their own group: >>> a = "char(30) binary" >>> b = "float" >>> pat = r"([a-zA-Z]+)((\(.*\))(.*))*" >>> re.match(pat, a).groups() ('char', '(30) binary', '(30)', ' binary') >>> re.match(pat, b).groups() ('float', None, None, None) Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From michela_rossi66 at hotmail.com Sat May 15 09:39:59 2004 From: michela_rossi66 at hotmail.com (michela rossi) Date: 15 May 2004 06:39:59 -0700 Subject: MailMan integrated with JSP/Servlet integration Message-ID: <1ed550fd.0405150539.3adffc13@posting.google.com> Hi, Wonder if anyone can help me. I have a client for whom we are building a website using J2SE & TOMCAT 4.1.7. (at clients request). The client also has an installation of MailMan that they would like us to use to validate registered users. All well and good, but given that the bulk of the websites code will be written using Java, and MailMan is written in Python - this seems to represent a problem or two : e.g. how will the Java code interrogate the MailMan installation to find out whether a user has validated correctly? Is there any kind of Java interface that anyone knows about? Any help would be most welcome, Thanks, Michela. From newsgroups at jhrothjr.com Mon May 3 15:42:16 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 May 2004 15:42:16 -0400 Subject: PEP 328 update References: Message-ID: <109d87iiu30ct7a@news.supernews.com> "Aahz" wrote in message news:mailman.191.1083525640.25742.python-list at python.org... > PEP 328 (``import`` changes) has been updated and is available at > http://www.python.org/peps/pep-0328.html > > Comments on the revised version are welcome. One area where feedback is > particularly desired is on the frequency of relative imports inside > packages in current code, both in absolute terms and as a percentage of > all imports. What worries me about the PEP is the way it breaks backwards compatability. I'd much rather see some kind of decorator (possibly an !) to indicate an absolute import, and leave the undecorated form exactly the way it is, at least until 3.0. I also don't particularly see the reason for banning the relative form from raw import statements. The other two changes are, of course, welcome. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "I used to have a .sig but I found it impossible to please veryone..." --SFJ > From ptmcg at austin.rr._bogus_.com Mon May 10 10:55:39 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 May 2004 14:55:39 GMT Subject: newbie question - remove a module from ram References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:c7nvr1$fsc$01$1 at news.t-online.com... > Paul McGuire wrote: > > > "john fabiani" wrote in message > > news:4AAnc.6791$dH5.4946 at newssvr27.news.prodigy.com... > >> Hi, > >> > >> I believe I have good understanding of import but it occurred to me that > >> I might want to remove an imported module. I.e I load a module into ram > >> and I no longer need the module. Modules just stays in ram? In the > >> windows world I would "thisform.release()" and the garbage collector > >> would release the ram. So did I miss something or is there no release > >> method. How about a method within a class like destroy()? > >> > >> I just got to believe it's there???? But where? > >> John > > > > Well, you were pretty close with calling something like .release(). Use > > the del statement. > > > >>>> import random > >>>> print random.random() > > 0.475899061786 > >>>> del random > >>>> print random.random() > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'random' is not defined > >>>> > > and then > > >>> import sys > >>> sys.modules["random"].random() > 0.43459738002826365 > >>> > > should make it clear that (next to) no memory is freed in the process. > > Peter > So then what if he follows up with: del sys.modules["random"] Are there any other dangling references to this module that would stymie the garbage collector (assuming that the OP hasn't saved off his own reference to the module)? -- Paul From Mike at DeleteThis.Geary.com Sat May 15 21:38:34 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 15 May 2004 18:38:34 -0700 Subject: Python vs. VBScript vs. JavaScript in context of WindowsScripting Host? References: <051601c43aaf$07874590$210110ac@jsbwxp3> Message-ID: <10adhgrlagdduc6@corp.supernews.com> > John Benson wrote: > > * no record types, just numerically-indexed arrays, so record > > handling is kludgy [in VBScript] Christopher Weimann wrote: > Scripting.Dictionary > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/jsobjDictionary.asp > > A Dictionary object is the equivalent of a PERL associative array. > Items can be any form of data, and are stored in the array. Each > item is associated with a unique key. The key is used to retrieve > an individual item and is usually an integer or a string, but can > be anything except an array. That's good to know about if you have to live with VBScript. JavaScript has dictionaries built in (a JavaScript object is a dictionary), so it's easier to use those instead. Taking the VBScript example from that page: Dim d ' Create a variable. Set d = CreateObject("Scripting.Dictionary") d.Add "a", "Athens" ' Add some keys and items. d.Add "b", "Belgrade" d.Add "c", "Cairo" In JavaScript, you could do: d = {} d.a = "Athens" d.b = "Belgrade" d.c = "Cairo" or: d = { a: "Athens", b: "Belgrade", c: "Cairo" } -Mike From thestormbringer77 at yahoo.com Sat May 29 11:55:00 2004 From: thestormbringer77 at yahoo.com (Storm) Date: 29 May 2004 08:55:00 -0700 Subject: Looking for a TCP/IP networking library/module/whatever ... Message-ID: <6c64de9a.0405290755.6a366d77@posting.google.com> ... that I would like to use in a client/server application that would : 1) detect reliably when connection is lost and try automatically to reconnect to the server and the link is declared dead (i.e. the client/server is notified) if only a reconnect was not possible for 3-4 minutes 2) perhaps have the whole link encrypter, but I see this most as a bonus Anyone knows if something like this exists ? From rzantow at ntelos.net Thu May 13 16:41:37 2004 From: rzantow at ntelos.net (rzed) Date: Thu, 13 May 2004 20:41:37 GMT Subject: things I wish python could do References: Message-ID: Daniel 'Dang' Griffith wrote in news:e2f2f1d66757198e867abb285277d0b5 at news.teranews.com: > On Thu, 13 May 2004 12:35:48 -0400, "Terry Reedy" > wrote: [...] >>Lambda expressions in Python are strictly an abbreviation for >>functions with a trivial body ('return expression'), nothing >>more. Anonymity is a wart, not a feature. The keyword is, to >>me, a mistake because of the false expectations it stimulates. > > Maybe lambda should be renamed as lameda? ;-) Or: lambada -- the forbidden function. -- rzed No more than $0.01 here. From bjg at network-theory.co.uk Wed May 12 13:52:20 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 12 May 2004 18:52:20 +0100 Subject: Python+SQL References: Message-ID: <87y8nxzg6j.fsf@network-theory.co.uk> Chris Stiles writes: > What are my options for using Python and SQL - specifically mysql ? So far > I've found pysqldb and python-mysql on sourceforge, but the official > references don't seem to include anything. The database SIG has the most official information on the DB-API and modules which conform to it: http://www.python.org/topics/database/ -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From news at bolognini.net Sun May 2 20:01:51 2004 From: news at bolognini.net (Lorenzo Bolognini) Date: Mon, 3 May 2004 02:01:51 +0200 Subject: Web development class References: Message-ID: "-" ha scritto nel messaggio news:fef0a228.0405020232.253f6b17 at posting.google.com... > "Lorenzo Bolognini" wrote in message news:... > > h1.color("red") > > I have no idea what the class you're looking for does, but this > example is better implemented with standard CSS. > Say so to Microsoft for ASP.NET... in the meanwhile a guy was so kind to post me the answer directly in my mailbox: http://www.entrian.com/PyMeld/ That's what I was looking for ;-) Lorenzo From adalke at mindspring.com Sun May 16 10:57:28 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 16 May 2004 14:57:28 GMT Subject: Guess My Number Game References: <90aea0p1sn3ehbca0tds5uuhj5brrbbdj9@4ax.com> Message-ID: Andrea Griffini > Not really python related, but... > > >On average, the shortest possible runtime (and also a deterministic runtime of > >O(log2(high-low))) will be achieved if you use interval walking. ... > supposing that guess(x) returns -1, 0 or 1 depending > if the number is too low, correct or too high. And not really an answer to the OP; here's a solution which uses the bisect module, letting it do the heavy work. It uses the same sort of guess function you have, tied to Python's __cmp__. It isn't an answer because it's rather too complicated for someone learning programming. import bisect def find(min = 1, max = 100): print "Think of a number between", min, "and", max a = range(min, max+1) try: bisect.bisect_left(a, Guess()) print "Your number isn't between", min, "and", max print "Maybe you weren't thinking of an integer?" except Done, e: print "And it only took", e.count, "guesses" class Done(Exception): def __init__(self, answer, count): self.answer = answer self.count = count class Guess: def __init__(self): self.count = 0 def __cmp__(self, val): self.count = self.count + 1 answer = raw_input("Is it %d? ([y] for yes, [<] for less than " "and [>] for greater than)? " % val) if answer == "y": raise Done(answer, self.count) if answer == "<": return -1 return 1 >>> from number_guess import find >>> find(1, 10) Think of a number between 1 and 10 Is it 6? ([y] for yes, [<] for less than and [>] for greater than)? < Is it 3? ([y] for yes, [<] for less than and [>] for greater than)? y And it only took 2 guesses >>> find(1, 100) Think of a number between 1 and 100 Is it 51? ([y] for yes, [<] for less than and [>] for greater than)? < Is it 26? ([y] for yes, [<] for less than and [>] for greater than)? > Is it 39? ([y] for yes, [<] for less than and [>] for greater than)? < Is it 33? ([y] for yes, [<] for less than and [>] for greater than)? > Is it 36? ([y] for yes, [<] for less than and [>] for greater than)? > Is it 38? ([y] for yes, [<] for less than and [>] for greater than)? y And it only took 6 guesses >>> find(1, 10) Think of a number between 1 and 10 Is it 6? ([y] for yes, [<] for less than and [>] for greater than)? n Is it 9? ([y] for yes, [<] for less than and [>] for greater than)? < Is it 8? ([y] for yes, [<] for less than and [>] for greater than)? < Is it 7? ([y] for yes, [<] for less than and [>] for greater than)? < Your number isn't between 1 and 10 Maybe you weren't thinking of an integer? >>> Andrew dalke at dalkescientific.com From __peter__ at web.de Thu May 13 05:44:54 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 May 2004 11:44:54 +0200 Subject: PEP: import version References: Message-ID: Manlio Perillo wrote: > A possible syntax is this: > import wxPython version '2.4' Why not just import wxPython2_4 as wxPython and a symlink or something equivalent pointing to the latest version to also allow import wxPython > Another case is when the module is implemented also in C: > import picke version 'C' Presenting the user with the choice of two equivalent modules is a mistake IMHO. Just rename cPickle to pickle and move pickle.py into the docs/demo/educational section. Or, more general, provide a Python version as a fallback: try # try from cPickle import * except ImportError: # python implementation Peter From jacek.generowicz at cern.ch Tue May 25 08:30:26 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 May 2004 14:30:26 +0200 Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: Jacek Generowicz writes: > Name Interpreted Compiled > > LispWorks 66 1.0 s > Clisp 41 9.5 s > CMUCL Got bored waiting 1.5 s > SBCL Compiles everything 1.6 s > Python Compiles everything 20 s > > > So, we have times of 1.0s, 1.5s, 1.6s, 9.5s and 20s. Now one of those > Common Lisp implementations does NOT compile to native; it compiles to > bytecode. Can you guess which one it is, by looking at the timings ? Just for fun, I threw all the declarations that came to my head at the Lisp function, making in look thus: (defun fib (n) (declare (fixnum n)) (declare (optimize (safety 0) (speed 3) (debug 0) (space 0) (compilation-speed 0))) (if (< n 2) 1 (the fixnum (+ (the fixnum (fib (- n 1))) (the fixnum (fib (- n 2))))))) I also tried a C version: int fib(int n) { if (n<2) { return 1; } return fib(n-1) + fib(n-2); } int main() { return fib(35); } Here's the table with the the results for the above added in: Name Interpreted Compiled With declarations LispWorks 66 1.0 1.6 Clisp 41 9.5 9.5 CMUCL Got bored waiting 1.5 0.45 SBCL Compiles everything 1.6 0.49 Python Compiles everything 20 gcc No interactivity 0.29 (I also tried it on Allegro, via their telnet prompt (telnet prompt.franz.com). The uncompiled version went beyond the CPU limit they give you; the compiled version without declarations was 400ms; with declarations was 200ms. Of course, we don't know how their processor compares to mine.) From snrkiwi-lists at yahoo.com Wed May 12 13:52:49 2004 From: snrkiwi-lists at yahoo.com (snrkiwi-lists) Date: Wed, 12 May 2004 13:52:49 -0400 Subject: Real-time graphs In-Reply-To: References: Message-ID: <2EC03AEC-A43D-11D8-88C2-000A95AA5CB4@yahoo.com> This is pretty much my plan (or to use an observer pattern). But I was wondering if anyone had used any particular graphing package to generate these types of graphs? I wouldn't think that driving gnuplot in the background would be an efficient approach, for example. On May 12, 2004, at 1:20 PM, Doug Holton wrote: > snrkiwi-lists at yahoo.com wrote: > >> I've trolled the lists, FAQs, and Net as a whole, but >> can't find anything definitive to answer this. >> We're looking for real-time graph capability (bar, >> line, etc), so that we can display telemetry from a >> robot system. There are a bunch of packages out >> there, but many seem to provide only static graphs >> (e.g. for scientific, financial data, etc). Does >> anyone currently display real-time telemetry using >> Python? Can anyone provide any suggestions? > > Unfortunately there is not anything designed specifically for > real-time graphs in python. You could create a custom control. > > My suggestion is to use a Timer (like wx.Timer in wxpython) set to a > particular "frame rate" - how many times the graph should be refreshed > per second. Everytime it fires it updates the graph (if it is a > scrolling plot, or else if the data has changed). Meanwhile in a > background thread your time-stamped data points are collected, perhaps > into two lists. If it is a scrolling plot you could discard (or log) > data that is old. > -- > http://mail.python.org/mailman/listinfo/python-list > From fperez528 at yahoo.com Sat May 15 01:03:42 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 14 May 2004 23:03:42 -0600 Subject: bug in inspect (was cgitb vs traceback) References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > ..... the above script demonstrates a bug in the inspect module's > getinnerframes function which is using the frame f_lineno instead of the > traceback's tb_lineno. Have you reported this on SF yet? I think I now realize I've been bitten by this myself recently a few times. Do you know if it's a new 2.3 bug, or has it been present since 2.2? I wonder if the fix could make it into 2.3.4 or not... Best, f From gabor at z10n.net Mon May 24 16:08:27 2004 From: gabor at z10n.net (gabor) Date: Mon, 24 May 2004 22:08:27 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <1085429307.6887.1.camel@wintermute.atriaky.sk> On Mon, 2004-05-24 at 18:10, Mark Hahn wrote: > "gabor" wrote > > > > Does any Python user have a story of regret of using an object's > attribute > > > when they should not have and encapsulation would have saved their > butts? > > > > not exactly... > > > > i don't need restriction, only a hint... > > > > if i look thru some java code, i immediately see what variables/methods > > should/can i access... it's not the same for python... > > > > for example at work where i use java, there are classes that have > > 10-15methods, but only 4public ones... it immediately gets simplier to > > understand/use the class > > I sounds to me like you want a better documentation solution, not an > encapsulation solution. Now that is something I agree with 100% and have > near the top of the list in Prothon. I personally think docs are a weak > point in Python. documentation is fine.... the more the better... but the argument that more-docs-should-be-enough-because-you-can-document-which-functions-are-private reminds me a little of the but-you-can-write-object-oriented-code-in-assembler.... or that you-can-write-object-oriented-code-in-c... yes, you can implement the needed mechanism in every language, but it's not always fun.... :) gabor From jarod68 at despammed.com Mon May 10 07:29:24 2004 From: jarod68 at despammed.com (jarod) Date: Mon, 10 May 2004 13:29:24 +0200 Subject: Python for Nokia Series 60 References: <2g7c6lF52kr4U1@uni-berlin.de> <2g7siqF57e6rU1@uni-berlin.de> Message-ID: > > Do you know nothing about Java ? > > Maybe not. Or maybe he just checked the facts before posting? > > http://groups.google.com/groups?meta=group%3Dcomp.lang.python.*&q=J2ME ;-))) ... sorry, thanks for the tips Alan. Bye Jarod From eric_brunel at despammed.com Fri May 21 04:12:42 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 21 May 2004 10:12:42 +0200 Subject: Tkinter: update_idletasks References: Message-ID: Jeffrey Barish wrote: > I'm confused about how to use the update_idletasks method. In my > program, I have a handler for a button in which execution will linger. > During that time, I would like for the GUI to continue to show signs of > life. I have a Pmw MessageBar in which I display a status message. I > figured out that if I run update_idletasks on that MessageBar, then the > MessageBar will update the display as I update the message. However, > if I cover the GUI with some other window and then expose it again, the > GUI does not refresh until the handler finishes (except for the > MessageBar). Do I have to run the update_idletasks method for every > widget in the GUI? for all the frames? for just the root frame? Or is > it impossible to get the GUI to refresh in this situation? At tcl level, update_idletasks isn't a "method", i.e. the tcl command doesn't take any parameter telling which widget to refresh. So calling the Tkinter update_idletasks method on any widget has exactly the same effect, which is to refresh the whole GUI. There are some issues on Windows however, where the newly created toplevel's may not refresh until full control is returned to the GUI. To work around this problem, use the wait_visibility method to wait until the newly created window is displayed. But be careful: wait_visibility processes events, unlike update_idletasks that does just a GUI refresh. There is apparently no simple way of updating the display of newly created toplevel's on Windows without returning full control to the GUI (at least with tk/Tkinter) I never saw the problem you describe (some windows refreshing, some not), but I mainly develop on Linux, which may show a different behaviour than the platform you're working on (which BTW you don't mention...). Maybe you can post a small piece of code showing the problem? HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From tim.one at comcast.net Sun May 16 18:42:47 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 16 May 2004 18:42:47 -0400 Subject: web security question. In-Reply-To: Message-ID: [Christos TZOTZIOY Georgiou] > This message is related: > > > > I didn't test if Tim's snippet produces a segfault, though. It won't in Python 2.4, but still will in 2.3.4 (and earlier). People *allowing* access to the buffer() builtin in Web-based code are insane, though, and the sample code referenced requires (ab)using the buffer() builtin. As a sane counterexample, Zope removes buffer() from the built-ins available to Python code running under Zope. From ajsiegel at optonline.com Mon May 24 13:01:06 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 24 May 2004 17:01:06 GMT Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> Message-ID: <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> On Mon, 24 May 2004 16:25:28 GMT, Arthur wrote: > >With some part of that dynamics, it seems to me, being that many of us >take our own understanding of the difference between tuples and lists >(some of which might be deeper than others, mine on the lighter side) >and then ascribe and reconcile that understanding with Guido's words. >Which is part of the tautaology factor. Sorry folks, the dunamics here really interest me. It is simply group dynamics in the circumstances of a strong individual leader. I don't mean to be in finger pointing, or hysterics mode. But backing up, and re-reading the python-dev thread from which this all starts, I think there is one other factor. Simply that the distinction being drawn by Guido was - I'm thinking - formed prior to new style classes, and attendent changes to the language. And that it was more meaningful once, than it is now is. Certainly a programming language like Python is tightly woven and it should be no real surprise that changes to the language as fundamental as occurred since 1.5.2 - not directly related to lists or tuples - would impact the conceptualization and language with which might most appropriate in describing these structures. I am going out of on a limb (I've long since had little to lose by doing so here) - and beyond by competence - to speculate that part of what we have here is a time warp in the direction reverse from which is normally expected of Guido. Art From richie at entrian.com Wed May 5 11:31:38 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 05 May 2004 16:31:38 +0100 Subject: OT: software like VNC In-Reply-To: References: Message-ID: <4i1i90pg7jb0bt4dqjrhhto392rnrku49i@4ax.com> [Alberto] > Do you know another software that works like VNC or PCAnywhere? [Peter] > What did Google tell you when you tried to search? And for those that haven't come across it, this is exactly the sort of question that Google Sets is designed to answer: http://labs.google.com/sets Entering "VNC" and "PC Anywhere" gives a list that includes NetMeeting, Sunbelt Remote Administrator, Netbus, SubSeven, BO2K, RemotelyAnywhere, lots of things that aren't quite relevent, and lots of other things I hadn't heard of. It didn't include WebEx, but should have. And as we all know Google Inc. are big fans of Python, which neatly brings us back on topic. 8-) -- Richie Hindle richie at entrian.com From beliavsky at 127.0.0.1 Wed May 26 17:20:21 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 26 May 2004 16:20:21 -0500 Subject: Current drive and directory References: Message-ID: <40b50a15$1_1@127.0.0.1> "EAS" wrote: >Does anyone know how to display the current directory using DOS >and/or Python? Use the getcwd() function in the os module. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From tim.golden at viacom-outdoor.co.uk Thu May 6 04:36:12 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 6 May 2004 09:36:12 +0100 Subject: Enumerating machines on the local network? Message-ID: >Hi, >I am a python newbie. I intend to create a small program that >enumerates all the machines on a computer network. How would i go >about it? Does anyone know about some specific packages that i would >need? any links or tutorials? > >And is a cross-platform solution possible? If you're on Win32, try this (shamelessly lifted from someone's python-win32 posting): http://tgolden.sc.sabren.com/python/win32_how_do_i/list_machines_in_a_domain .html Obviously (well, obviously once you've looked at it), this only covers the NT domain situation, not an arbitrary network. If you're on Unix, have a look at Zeroconf (http://www.zeroconf.org/) and Howl (http://www.porchdogsoft.com/products/howl/) which may or may not be what you're looking for. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 skip at pobox.com Sun May 9 19:24:30 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 9 May 2004 18:24:30 -0500 Subject: emacs alphabetize methods In-Reply-To: References: Message-ID: <16542.48558.687389.702601@montanaro.dyndns.org> "John Hunter" wrote: John> Using emacs python-mode with a class John> John> class C: John> def method1(self): John> pass John> John> def anothermethod(self): John> pass John> John> def method2(self): John> pass John> John> is there any way to select all the methods and have emacs order John> them alphabetically? If not, is there a good too to do so? Sort of, but there are problems. Emacs does have a sort-paragraphs function. Python-mode has a py-mark-block command. If you place the cursor at the start of the "class" line and hit C-c C-k you'll mark the class. Hit C-n C-x C-x to highlight the block except for the class line itself then M-x sort-paragraphs RET. This has a gotcha. The notion of paragraph separator is basically a blank line. To make this more effective you'd have to modify the paragraph-separate variable. If you come up with a reasonable value for Python code, send it along to python-mode at python.org and we'll update python-mode.el. Skip From mark at prothon.org Tue May 25 14:47:31 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 25 May 2004 11:47:31 -0700 Subject: Prothon should not borrow Python strings! References: <2hfv4nFch1lmU3@uni-berlin.de> Message-ID: <7xMsc.17901$bF3.7334@fed1read01> "Paul Prescod" wrote Paul et al: I have a number of wild ideas and questions about text and binary strings and also a few things to discuss about the long integers you brought up, but the Python list is not the proper place to drag these discussions out. Is there any chance I can get you (and hopefully others participating here) to join the prothon-user mailing list for a week or two to discuss these issues? The traffic is only one tenth the traffic here on c.l.p. so it won't be much burdon. Our discussions are interesting. (We have no pesky users yet :-) You can experience the warm feeling that can only be acheived by helping steer a new language away from mediocrity and towards greatness . From garabik at kassiopeia.juls.savba.sk Tue May 18 02:15:57 2004 From: garabik at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 18 May 2004 06:15:57 GMT Subject: Cache a large list to disk References: <939f49f8.0405171155.1de74c2a@posting.google.com> Message-ID: <2gto0tF6ks4fU2@uni-berlin.de> Chris wrote: > I have a set of routines, the first of which reads lots and lots of > data from disparate regions of disk. This read routine takes 40 > minutes on a P3-866 (with IDE drives). This routine populates an > array with a number of dictionaries, e.g., > > [{'el2': 0, 'el3': 0, 'el1': 0, 'el4': 0, 'el5': 0}, > {'el2': 15, 'el3': 21, 'el1': 9, 'el4': 33, 'el5': 51}, > {'el2': 35, 'el3': 49, 'el1': 21, 'el4': 77, 'el5': 119}, > {'el2': 45, 'el3': 63, 'el1': 27, 'el4': 99, 'el5': 153}] > (not actually the data i'm reading) > > This information is acted upon by subsequent routines. These routines > change very often, but the data changes very infrequently (the > opposite pattern of what I'm used to). This data changes once per > week, so I can safely cache this data to a big file on disk, and read > out of this big file -- rather than having to read about 10,000 files > -- when the program is loaded. > > Now, if this were C I'd know how to do this in a pretty > straightforward manner. But being new to Python, I don't know how I > can (hopefully easily) write this data to a file, and then read it out > into memory on subsequent launches. > > If anyone can provide some pointers, or even some sample code on how > to accomplish this, it would be greatly appreciated. as already mentioned, use cPickle or shelve However, depending how big and how many your dictionaries are, you can use *dbm databases instead of dictionaries, with numbers packed up using struct module (I found out it is sometimes much efficient than using shelve). Looking at your sample, you could even reorganize the data as: {'el2': [0, 15, 35, 45], 'el3': [0, 21, 49, 63], ... } and use one big dbm database, with lists represented as array objects - that is going to give you major memory efficiency boost. If the arrays are going to be big (like really BIG, of some tens of megabytes), you can store them one per file, and use mmap to access them - I am doing now something similar -- ----------------------------------------------------------- | 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 dmq at gain.com Thu May 13 17:59:32 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 13 May 2004 14:59:32 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> Message-ID: On Thu, 13 May 2004 10:56:58 -0400, "Terry Reedy" wrote: >"Antoon Pardon" wrote in message >news:slrnca6d58.1i9.apardon at trout.vub.ac.be... >> One could argue that all forms of methods and functions are unified. >> It is just that python does some magic so that the method you >> access from an object is not the actual function but the curried >> function with the object. > >My view is similar: in Python, a method is a dressed up (wrapped) function. >'Unification of methods and functions' reads to me like 'unification of >dressed-up bodies and naked bodies'. What would that mean? By unification, I mean making the calling sequence identical for all methods and functions. No more special syntax for lambda functions, static methods, etc. No time wasted on these topics in a text like Learning Python. A simpler presentation of OOP, based on what students already know at this point - functions, modules, and global variables. >One thing I >like about Python is that there is only function-body syntax and not a >separate, slightly different method-body syntax. To me, having only one >type of code body *is* unification. So it is hard for me to see what is >being proposed. The one fundamental difference between methods and functions is the presence of instance variables in methods. You can hide that difference with the self.var trick. You can hide it even further by not using 'self', but some other word that looks just like the other variable names in the function. None of this removes the actual difference, or makes learning about instance variables any easier for the student. The choice of how to identify instance variables is a minor issue. I think it is actually better not to *hide* the instance variables, but to *highlight* them. Ruby uses $var for instance variables. Prothon uses a leading dot, which is quite visible in most code editors. The real issue is not self.var vs .var It is the complexity resulting from having different calling sequences. Compare the 96-page presentation of OOP in Learning Python, 2nd ed. to what I have written at http://ece.arizona.edu/~edatools/Python/Prototypes.doc In 7 pages, I can present the basics of OOP. Adding examples and exercises will probably bring this to 30 pages. The key to this simplification is not having to deal with unnecessary complexities, like lambda functions, static methods, etc. >Introducing a syntax like '.var' that would only be >meaningful in a method and not a function would be dis-unification. Actually, .var could be used in a function outside a class, just as you can now use self.var in the current function syntax. Before using a function with .var, the global variable __self__ must be set. This is normally done by calling the function from an instance. Before using a function with self.var, the first argument must be set. This is normally done by calling the function fom an instance. To say that adding an instance variable to a function breaks unity is like saying that adding a global variable to a function breaks unity. Adding an instance variable to a function simply makes the function dependent on an external variable. Same with a global. -- Dave From nav+posts at bandersnatch.org Mon May 10 15:33:58 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 10 May 2004 15:33:58 -0400 Subject: Python job opening at GPO in Washington, DC References: <2g26l5F3ovo0U1@uni-berlin.de> <2g9s2hF96nhU1@uni-berlin.de> Message-ID: William Park writes: > I wish you good luck. It's shame that they don't use LaTeX or shell > scripts. Traditionally it's been SGML, currently in transition to XML, with an in-house typesetting application. Rumor has it that SVG is being considered as the new page description language, and XSLT will be the engine that drives this bus. However, I'm certainly not at a pay grade that entitles me to make any predictions about what we'll wind up working with. This wouldn't be the first place where my fondness for things that work has gotten me into trouble -- I'm used to it. 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 tmohr at s.netic.de Sun May 30 05:22:06 2004 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 30 May 2004 11:22:06 +0200 Subject: noddy example, writing C modules for python Message-ID: Hi, based on the example module "noddy" i wrote an own one and i have problems accessing the elements in the python objects. I defined the example object: typedef struct { PyObject_HEAD int num; } pmod_obj; static PyMemberDef pmod_members[] = { {"number", T_INT, offsetof(pmod_obj, num), 0, /* LINE 143 */ "pmod number"}, {NULL} }; When i compile this under Win32, i get this (in german): pmod.cc(143) : error C2552: 'pmod_members': Initialisierung nicht zusammengesetzter Typen mit Initialisierungsliste ist nicht m?glich 'PyMemberDef' : Typen mit benutzerdefinierten Konstruktoren sind nicht 'aggregate' pmod.cc(143) : error C2065: 'T_INT': nichtdeklarierter Bezeichner pmod.cc(143) : error C2275: 'pmod_obj': Ung?ltige Verwendung dieses Typs als Ausdruck pmod.cc(10): Siehe Deklaration von 'pmod_obj' pmod.cc(143) : error C2065: 'num': nichtdeklarierter Bezeichner pmod.cc(143) : error C3861: 'offsetof': Bezeichner wurde auch mit einer argumentbezogenen Suche nicht gefunden Has anybody got a hint for me? It is not obvious to me why this does not compile. Best regards, Torsten. From gdowdin at cs.clemson.edu Tue May 25 15:49:36 2004 From: gdowdin at cs.clemson.edu (Dowding George A) Date: 25 May 2004 15:49:36 -0400 Subject: Record and Playback in Tkinter Message-ID: Hi, I am trying to figure out how to to do some GUI testing using Tkinter. For a start I thought I would like to add the feature to any generic Tkinter program to record a sequence of GUI interactions and play them back with no user interaction. My first question is how to create a generic handler to be the first one to recieve all event. This handler just needs to record events then pass them on to the application to be processed as normally. -- George A. Dowding, Clemson University Computer Science Dept. G023 Jordan Hall From peter at engcorp.com Sun May 23 09:01:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 May 2004 09:01:54 -0400 Subject: Downloading SCXX In-Reply-To: References: Message-ID: Nick Jacobson wrote: > I've been trying to download SCXX, but the website > http://www.mcmillan-inc.com/ has been down for the last few days. > Where else can I find it? Thanks in advance. I believe attempts to reach mcmillan-inc.com have failed for the last few *months*, not just the last few days. I don't recall seeing any comment about it except (or did I just imagine it?) a comment from someone that Gordon was indeed alive, but occupied with other things... -Peter From mtadin66 at yahoo.com Fri May 14 02:24:24 2004 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Fri, 14 May 2004 07:24:24 +0100 Subject: Python and Windows.Forms References: <87n08qrpcv.fsf@pobox.com> Message-ID: You can script .net from python. Have a look at: http://zope.org/Members/Brian/PythonNet/ Marijan From dmq at gain.com Fri May 7 21:15:24 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 07 May 2004 18:15:24 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <2g0f8iF34iasU1@uni-berlin.de> Message-ID: On Fri, 07 May 2004 15:48:29 +1200, Greg Ewing wrote: >David MacQuigg wrote: >In Python, staticmethods are not fundamentally necessary, >full stop. We keep trying to tell you that, but it seems >you have your fingers in your ears. I will stop this subthread right here unless you change your tone. This kind of argument won't convince me you are right, or anyone else with any intelligence. -- Dave From P at draigBrady.com Fri May 21 07:04:38 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Fri, 21 May 2004 12:04:38 +0100 Subject: Using pygtk and glade2 In-Reply-To: References: <40AC9EAE.4020905@draigBrady.com> Message-ID: <40ADE246.9050502@draigBrady.com> j_mckitrick wrote: >>That's easy: text = combo.entry.get_text() > > > But when I use > > self.wTree.get_widget('Combo').entry.get_text() > > it tells me > > gtk.Bin does not have attribute 'entry' Hang on, gtk.Bin isn't even in the combo hierarchy? http://www.pygtk.org/pygtk2reference/class-gtkcombo.html Are you sure you've got the correct widget? P?draig. From amireallyfat at yahoo.com.au Fri May 28 00:58:17 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Fri, 28 May 2004 14:58:17 +1000 Subject: why learn References: Message-ID: <40b6c6e3$1_1@news.iprimus.com.au> yeah well thats k i really wouldnt bother posting more than once ;) "Tim Peters" wrote in message news:mailman.350.1085640935.6949.python-list at python.org... > [mr_vocab] > >> hey i finished working through alot of python stuff and no a fair bit > >> bout it > >> > >> now what can i do with it??? > > [Tim] > > Follow your bliss: in your case, it looks like you'd really enjoy writing > > a program to post the same question 100 times. It's a lot easier to write > > a program for that than to stay up all night doing it by hand . > > Oops! My apologies! That wasn't you. A particularly nasty piece of spam > wedged my ISP, and your message was immediately before it: every time I > downloaded mail, I got your message again, and then the connection died > while trying to transfer the ill-formed spam. > > Anyway, following your bliss remains sincere if cryptic advice. What are > you interested in? What do you love? If you're not using Python for your > job (and sometimes even if you are ...), those are the questions to answer > first. Python will then fit in or won't. You can use Python for anything a > computer has ever been used for, and for a boundless number of things nobody > has thought of yet. What do you care about? > > > From peter at engcorp.com Wed May 12 23:35:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 May 2004 23:35:56 -0400 Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> Message-ID: john fabiani wrote: > I'm guessing but I bet that simple text can be sent to a printer using > Python (looping of course). But in today's world most users want > graphics along with the data. Like an invoice with a logo, boxes around > the bill to and ship to, along with column lines. So I'm hoping that > someone has at least started a project to print reports. That would be "ReportLab", I would think... Google for it. -Peter From mir4uu at yahoo.com Mon May 24 12:29:53 2004 From: mir4uu at yahoo.com (mir nazim) Date: 24 May 2004 09:29:53 -0700 Subject: cannot fin sum() in python 2.3 Message-ID: <425cc8d1.0405240829.31e6471@posting.google.com> hi, i cannot find sum() built in fuction in 2.3 version. i built from sources python from python.org. it gives NameError. please tell me where can i find Python Imaging Library libxml2 for python2.3 all the rpms/sources work for python 2.2 From tjreedy at udel.edu Fri May 21 13:57:56 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 13:57:56 -0400 Subject: Newbie's rant's and question :) (long post) References: <1e6f6533.0405201134.138b752c@posting.google.com> Message-ID: "Hendy Teguh" wrote in message news:1e6f6533.0405201134.138b752c at posting.google.com... > Hello, > > first, a little warning, may contain negative comments, If something is so negative as to really need a warning, perhaps a rewrite is in order. > my humble opinion, please consider it as a curious comments, not > flaming or trolling Perhaps half the people who say "I am not a troll" are (a troll), like the home-improvement salesperson who came by my house a week ago looking for someone who could be conned into signing for a 40% premium without getting competitive bids ;-). So maybe better to just ask your questions and leave the subject alone. (there're tendency i read on newsgroup (especially > linux newsgroups), that newbie's opinion are often considered > trolling, especially from diehard fans :P ). Trolling is a type of fishing with a moving, typically spinning, lure. A troll is a (mythical) humanoid underground wanderer. (Both from the same root.) A newsgroup troll (not mythical) fishes for controversy and emotional reaction, with purposes that lie underneath surface appearances. Sometimes the difference between that and honest questioning and opinionating is rather subtle, especially to those less experienced with newsgroups and the particular language. There are some over-reactions, but folks here on c.l.py are pretty tolerant and slow to accuse. > And also since english > is not my native language, please forgive my bad english. Python's community, founded by a Dutchman, is quite international, with numerous people posting in English as a second (or third, or whatever) language. Your 'bad english' is no worse than that of some Americans and without your 'apology', I might not have noticed it as non-native. > Ok, a little background. This was quite helpful for understanding what followed. > After searching around, i finally decided to learn wxPython. wxPython, like many things built on top of Python, is otherwise an independent project with its own website (on SourceForge) and mailing list. If you continue with it, intermediate to advanced questions are better posted to its lists. > language). In other word, somehow python is 'teethless' in doing > something 'powerful' by itself IMHO. The fact that saber-toothed cats had fewer teeth than crocodiles hardly made them toothless. Two of Python's 'big teeth' are, in my opinion, the builtin list and dict types. Terry J. Reedy From mark at prothon.org Mon May 24 15:22:18 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 12:22:18 -0700 Subject: Prothon vs. Python integers References: Message-ID: "Heather Coppersmith" wrote in message news:m2k6z1ejcc.fsf at unique.phony.fqdn... > > Longs seemed like a needless exotic kludge to me in the 64-bit > > world. Surely once you get to 3.7e19 you are in floating point > > territory. I can't imagine counting anything up to 10**19. > > Beans? ;-) > > Accountants ("bean counters," in the derogatory vernacular) will > be displeased if Prothon silently loses pennies (or other small- > valued currencies) after a certain amount (lira and drachma spring > to mind, too). No economy is ever going to to have a gdp of 10**19 pennies. > Also, modern day cryptography applications can demand integer/ > logical operations on 256-, 512-, or more- bit (upwards of 1e150) > integers. Are Python longs being used for those? I guess even if they aren't someone might want to evaluate algorithms using longs. Ok, I'm wrong once again. I'll put implementing longs on the to-do list. From lbates at swamisoft.com Wed May 26 19:15:45 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 26 May 2004 18:15:45 -0500 Subject: Changing file names References: Message-ID: <-qSdnU-JRaqDuCjd4p2dnA@comcast.com> Sounds like you want to use os.path.walk function which recursively drills down through directories and subdirectories. Then (as everyone else has pointed out). You can use os.rename. HTH, Larry Bates Syscon, Inc. "Thomas Philips" wrote in message news:b4a8ffb6.0405261213.33b823ce at posting.google.com... > I want to get a list of all subdirectories of a given directory, and > within each directory, change the name of each file using a > predetermined rule. > > The function glob in module glob will give me a list of all the > subdirectories, and by looping over this list and repeatedly calling > glob, I can create lists of files within each directory, which are > easily edited to create lists of new filenames. > > How then can I change the existing filenames to these new filenames? > What python functions should I be using, and what modules are they > contained in? > > Thomas Philips From rodelrod at hotmail.com Fri May 28 09:08:31 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Fri, 28 May 2004 15:08:31 +0200 Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> <40b72a41$0$128$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: <1epn0wa5bqb0r$.heo8w4umjuxm$.dlg@40tude.net> Thank you all for you great tips! Matteo's list comprehension solution suits best my particular problem and I'll be using it. On Fri, 28 May 2004 10:34:15 GMT, Matteo Dell'Amico wrote: > You can express that as [s[:-1] for s in d]. It was great to know about the Numeric package, Peter, it will be really useful for some of the matrix handling I'm going to need. Anton's solution was a good brain teaser. I couldn't find in the docs what is the meaning of the asterisk in zip(*d), though. Nothing to do with C pointers, I guess? On Fri, 28 May 2004 13:58:23 +0200, Anton Vredegoor wrote: > Rodrigo Daunaravicius wrote: > >>Is there an elegant way to directly refer the 2nd dimension of a >>multi-dimensional sequence (like the nth character in a list of strings). >>An example would be deleting the newline in all the strings from a list >>obtained through readlines without recurring to 'for' loops. > > d = ['0891931243\n', '0325443777\n', '0933477028\n', > '0699624617\n', '0922210996\n'] > > #swap rows and columns, with the side effect of turning > #strings into lists, strings must be of equal length or > #else some information will be lost: > > d1 = zip(*d) Thanks again, Rodrigo Daunaravicius From mark at freelance-developer.com Fri May 14 12:17:34 2004 From: mark at freelance-developer.com (Mark J. Nenadov) Date: Fri, 14 May 2004 12:17:34 -0400 Subject: looping over the files in a directory References: Message-ID: On Fri, 14 May 2004 15:32:32 +0000, Elaine Jackson wrote: > Can anyone please tell me the actual syntax for saying something like this: > > for in : > A simple example: import os path = '/home/bob/' for f in os.listdir(path): print f -- Mark J. Nenadov Python Byte Solutions http://www.pythonbyte.com/ From winexpert at hotmail.com Wed May 26 08:57:51 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 26 May 2004 12:57:51 +0000 Subject: How to I set the "modification time" attribute of a file ? Message-ID: Try this: os.utime('c:\\temp\\spam.txt", None) # Set to current time I found this in the Python 2.1 bible (book) Good luck David Stockwell ------- Cell: http://cellphone.duneram.com/index.html >From: "fowlertrainer at anonym.hu" >To: python-list at python.org >Subject: How to I set the "modification time" attribute of a file ? >Date: Wed, 26 May 2004 14:52:01 +0200 > >Hi ! > >I want to change the "modification time" attribute of a file, after >download - from python. >But I don't find any function that do this. > >If it is don't exists in python, please write an os-specific command to >this. > >I want to use it in Linux, and test it in Windows. > >Thanx for helps: >Ft > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Watch LIVE baseball games on your computer with MLB.TV, included with MSN Premium! http://join.msn.click-url.com/go/onm00200439ave/direct/01/ From dsmith at programmablesolutions.net Wed May 12 08:19:25 2004 From: dsmith at programmablesolutions.net (David Smith) Date: Wed, 12 May 2004 07:19:25 -0500 Subject: wxpython demo under linux In-Reply-To: References: Message-ID: <1084364365.2353.6.camel@gondor> I'm not actually using Debian, however after I installed wxPython-2.4.2.4 the demo was under /usr/share/doc/wxPython-2.4.2.4/demo/demo.py. It's exactly the same as the windows demo. If this isn't the directory you can always use find or locate. David On Wed, 2004-05-12 at 03:43, C GIllespie wrote: > Dear All, > > I have wxpython under both windows and Linux. Under Windows there is a nice > little demo, which demonstrates all the widgets (with accompanied source > code). > > I presume the same demo is under Linux, but I can't find it. Where should I > look? I'm using Debian, is it a separate package? > > Thanks > > Colin > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Mon May 17 23:56:17 2004 From: jfabiani at yolo.com (john fabiani) Date: Tue, 18 May 2004 03:56:17 GMT Subject: module for working with the result set In-Reply-To: References: <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> Message-ID: Paul McNett wrote: > john fabiani writes: > > >>following your thoughts on the keys and my mistake - can you >>tell me how to get into a dict format? > > > For MySQL, there is the DictCursor class. Here's an example, > and you should even be able to use it as-is as I've opened up > public access to my MySQL database: > > >>>>import MySQLdb.cursors >>>>conn = MySQLdb.connect(host='melder.paulmcnett.com', user='dabo', passwd='dabo', db='dabotest') >>>>dictCursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) >>>>print dictCursor.execute('select * from recipes where mingred like "%coriander%"') > > 14 > >>>>recordSet = dictCursor.fetchall() >>>>for record in recordSet: > > ... print record['iid'], record['ctitle'] > ... > 184 Cucumber Salad > 186 Garlic Shrimps > 193 Chinese Salad with Crispy Won Tons > 299 Chicken Curry > 304 Kai Phat Khing > 305 Kung Tom Yam > 306 Ma Ho > 308 Yam Krachup > 332 Lentil Soup > 817 Mixed Vegetable Curry > 841 Thai Mushroom Soup > 843 Rice Noodle Salad with Ginger > 915 Santa Fe Stew > 966 Mixed Potato Soup > > I know about the MySQL Dictcusor but I'm using Postgres. I'm not married to Postgres but I had excellent success with it along with a VFP front end. BTW is the MySQL Dictclass writen in "C" (part of the driver) or a python class/module? Maybe I can copy the code if it's python. thanks John From smakhomo at webmail.co.za Sun May 16 08:58:10 2004 From: smakhomo at webmail.co.za (Selbourne makhomo) Date: Sun, 16 May 2004 14:58:10 +0200 Subject: how to write a python program tht reads (x,y) Message-ID: Could you please help me with the following graphs: 1. python graph that reads in (x,y) data from a file 2. modify the program to draw a graph of the function using wxpython 3. python graph that performs a linear least squares regression, which fits a straight line through the points 3. plot the straight line in a different colour to the original graph connecting the points. I will appreciate your assistance in this regard. Selbourne _____________________________________________________________________ For super low premiums ,click here http://www.dialdirect.co.za/quote From jbors at mail.ru Sat May 29 02:48:59 2004 From: jbors at mail.ru (Dmitry Borisov) Date: Fri, 28 May 2004 23:48:59 -0700 Subject: extracting code objects from .pyc References: <20040529060608.GA23118@unununium.org> Message-ID: <001d01c44549$064d12a0$0900a8c0@amr.corp.intel.com> Did you try this ? http://www.crazy-compilers.com/decompyle/ ----- Original Message ----- Subject: extracting code objects from .pyc > Could someone please tell me what should be done to extract a code > object from a .pyc? Poking through the source I find examples of using > PyMarshal_ReadLastObjectFromFile to get it, but when I tryed this myself > it wouldn't work, so I'm wondering what I might be doing wrong. One > difference is that the files have already been loaded to ram (by my > bootloader), so I was using PyMarshall_ReadObjectFromString instead. From newsgroups at jhrothjr.com Thu May 20 21:04:37 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 20 May 2004 21:04:37 -0400 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> <545cb8c2.0405201645.16ac3364@posting.google.com> Message-ID: <10aqle5fm6ksnf1@news.supernews.com> "Jim Hefferon" wrote in message news:545cb8c2.0405201645.16ac3364 at posting.google.com... > Peter Otten <__peter__ at web.de> wrote > > So why doesn't it just concatenate? Because there is no way of knowing how > > to properly decode chr(174) or any other non-ascii character to unicode: > > > > >>> chr(174).decode("latin1") > > u'\xae' > > >>> chr(174).decode("latin2") > > u'\u017d' > > >>> > > Forgive me, Peter, but you've only rephrased my question: I'm going to > decode them later, so why does the concatenator insist on decoding > them now? As I understand it (perhaps this is my error), > encoding/decoding is stuff that you do external to manipulating the > arrays of characters. Maybe I can simplify it? The result has to be in a single encoding, which will be UTF-8 if any of the strings is a unicode string. Ascii-7 is a proper subset of UTF-8, so there is no difficulty with the concatination. 8-bit encodings are not, so the concatination checks that any normal strings are, in fact, Ascii-7. The encoding is actually doing the validity check, not an encoding conversion. The only way the system could do a clean concatination between unicode and one of the 8-bit encodings is to know beforehand which of the 8-bit encodings it is dealing with, and there is no way that it currently has of knowing that. The people who implemented unicode (in 2.0, I believe) seem to have decided not to guess. That's in line with the "explicit is better than implicit" principle. > > Use either unicode or str, but don't mix them. That should keep you out of > > trouble. > > Well, I got this string as the filename of some kind of Macintosh file > (I'm on Linux but I'm working with an archive that contains some pre-X > Mac stuff) while calling some os and os.path functions. So I'm taking > strings from a Python library function (and using % to stuff them into > strings that will end up on the web, which should preserve > unicode-type-ness, right?) and then .join-ing them. Ah. The issue then is rather simple: what is the encoding of the normal strings? I'd presume Latin-1. So simply run the list of strings through a function that converts any normal string to unicode using the Latin-1 codec, and then they should concatinate fine. As far as the web goes, I'd suggest you make sure you specify UTF-8 in both the HTTP headers and in a tag in the HTML header, and make sure that what you write out is, indeed, UTF-8. John Roth > > I didn't go into the whole story when posting, because I tried to boil > the question down. Perhaps I should have. > > Thanks; I am often struck by how helpful this group is, > Jim From peter.maas at mplusr.de Thu May 13 03:46:59 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 13 May 2004 09:46:59 +0200 Subject: things I wish python could do In-Reply-To: References: Message-ID: Ryan Paul wrote: > 1. many keywords (eg:try/except) are strictly imperative, and cannot be > used in a functional context. > > this really should be possible: map(print,mylist) To make everything functional in Python would probably be a huge effort with cosmetic effects only. What about defining e.g. def fprint(item): print item putting all functional definitions in a module 'functional' and using it: from functional import fprint ... map(fprint, mylist) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From p_s_oberoi at hotmail.com Mon May 3 22:34:05 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Mon, 03 May 2004 21:34:05 -0500 Subject: doctest: address in output Message-ID: Recently (30 minutes ago...) I need to write a doctring of the following type: >>> import mymodule >>> mymodule.do_something() And I wanted to run doctest on this module. Now, I agree that avoiding addresses in test output is a good thing in general; but, in this case I wanted the '...' to match whatever address the object happened to be at. Here's a patch to doctest.py to enable this functionality: (against python-2.2.3) --- /usr/lib/python2.2/doctest.py 2003-10-15 22:41:35.000000000 -0500 +++ mydoctest.py 2004-05-03 21:08:55.000000000 -0500 @@ -288,6 +288,7 @@ _isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match _isEmpty = re.compile(r"\s*$").match _isComment = re.compile(r"\s*#").match +_subAddress = re.compile(r"0x[0-9a-f]*>$").sub del re from types import StringTypes as _StringTypes @@ -451,6 +452,11 @@ if verbose: out("ok\n") continue + got = _subAddress('...>', got) + if got == want: + if verbose: + out("ok\n") + continue state = FAIL assert state in (FAIL, BOOM) I was impressed by how easy it was to figure out how to make this change... I can't even *imagine* trying to fiddle with the standard library in, say, C++. In fact, it's only with python that I've really experienced the true potential of Open Source: it's invariably too much work to change a C/C++ program written by someone else. It takes too long to understand what is going on; you have to go through a lengthy compile; you have to worry about installation. Python makes it all so easy. I've hardly ever modified a C/C++ application that I've downloaded from somewhere---and I've almost always made small tweaks to the ones in python. These days I prefer python applications simply because I know I'll be able to *actually* change them to suit my needs, rather than theoretically have the ability to change them. -param From no.email at please.invalid Mon May 3 15:20:02 2004 From: no.email at please.invalid (Guido) Date: Mon, 03 May 2004 19:20:02 GMT Subject: curses and python (linux, debian) Message-ID: Hello I'm new to python and i'm trying to write a script that shows a menu. Now, I have some troubles with curses.setsyx() I do: import curses curses.setsyx(2, 20) curses.putp("TEST TITLE") curses.setsyx(25, 35) curses.putp("TEST CENTER") curses.setsyx(12, 35) curses.putp("TEST CENTER") but it just prints all the string after each other at the first lines.. can anybody help me please? thx! From jsbenson at bensonsystems.com Sat May 15 21:36:21 2004 From: jsbenson at bensonsystems.com (John Benson) Date: Sat, 15 May 2004 18:36:21 -0700 Subject: Fw: Python vs. VBScript vs. JavaScript in context of Windows Scripting Host? Message-ID: <05cd01c43ae6$319eb430$210110ac@jsbwxp3> Yes, but I was referring to VBScript apart from the runtime children like Dictionary, Network etc., like the C language apart from the Standard Library. I agree, though, Dictionaries are cool, however supplied. ----- Original Message ----- From: "Christopher Weimann" To: "John Benson" Cc: Sent: Saturday, May 15, 2004 5:13 PM Subject: Re: Python vs. VBScript vs. JavaScript in context of Windows Scripting Host? > On 05/15/2004-12:01PM, John Benson wrote: > > > > * no record types, just numerically-indexed arrays, so record handling is > > kludgy > > Scripting.Dictionary > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/jsobjDictionary.asp > > A Dictionary object is the equivalent of a PERL associative array. Items > can be any form of data, and are stored in the array. Each item is > associated with a unique key. The key is used to retrieve an individual > item and is usually an integer or a string, but can be anything except > an array. > > From andreas at kostyrka.org Sun May 16 03:18:31 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 16 May 2004 09:18:31 +0200 Subject: book on wxPython? In-Reply-To: <40a651f4$0$17265$a1866201@newsreader.visi.com> References: <40a5a851$0$8512$a18e6209@newsreader.visi.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> Message-ID: <1084691911.26864.495.camel@andi-lap> Am Sa, den 15.05.2004 schrieb Grant Edwards um 19:23: > In article , Roger Binns wrote: > > > Ok, now add printing, drag and drop and comboboxes. > > No thanks. I don't do printing or drag and drop. Or > comboboxes now that I think about it. My needs are fairly > simple, and Tkinter would suffice nicely, except that the > non-native look and feel seems to confuse Windows users. That's the price you pay for having a nice API that is implemented without "native" widgets. wxWindows (and wxPython upon it) is "more complicated" because it has to deal with a number of native implementations. By the way, wxWindows does a API model that is relativly close to Windows developement ;) > > > You'll find you can't or you have to use external libraries > > with Tkinter. > > Moot. [For me.] Not exactly. While you do not need printing and drag-n-drop, you checked the "native look" item above. So Tk is not a sensible solution for you. > > It isn't too much effort to make a higher level wrapper that > > does what you want, but in all the years that wxPython has > > been available few programmers have thought it would improve > > their productivity, quality or other code attributes. One > > example you have already seen of someone who thought it would > > is Wax. > > Like I said, I think Wax is a vast improvement. I'd like to > help out with Wax, but I'm having a tough time finding basic > documentation on wxPython so that I can figure out why some of > the Wax classes don't behave as intended. Well, read the wxWidgets docs. ;) Andreas -- Andreas Kostyrka Josef-Mayer-Strasse 5 83043 Bad Aibling From news at outbacklinux.com Thu May 20 08:06:06 2004 From: news at outbacklinux.com (Adrian Casey) Date: Thu, 20 May 2004 21:36:06 +0930 Subject: pexpect and OpenVMS Message-ID: <40ac9eaa@duster.adelaide.on.net> I have a collection of tcl expect scripts which I am converting to python using the excellent pexpect module (http://pexpect.sourceforge.net/). So far I've had great success in getting all my scripts to work with various flavours of UNIX. However, OpenVMS is causing me problems. The tcl scripts work perfectly across UNIX and VMS. I'm converting them from tcl to python simply because python is more scalable and allows for better code reuse. And it's a nicer language to code in IMHO. When running a pexpect script against a VMS system, the script only sends the first character of the command and then gets a timeout. For example, if I do "sendline('sho proc')" and then drop to interactive mode, only the 's' from 'sho' has been sent to the 'shell' prompt. Running a session in 'interactive' mode seems to work fine. By experimenting with an interactive python session, I have determined that VMS systems appear to use a different os.linesep - '\r' instead of '\n' for UNIX. So, I modified my script to set os.linesep = '\r' for VMS systems but I still get lots of timeouts. The login files to the VMS systems tend to display a lot of information, sometimes in colour meaning lots of escape characters are sent to the terminal. I'm wondering if this is confusing pexpect? However, the tcl scripts were not bothered by this at all. One workaround I'm using at the moment is to send a series of 10 or 20 return charcters seperated by a 1 second sleep. This generally works but makes dealing with VMS systems very slow... Under tcl, there is a way to slow down the rate at which characters are sent to the client. Is the same available in pexpect? Any ideas on how to make pexpect work with VMS systems? Regards. Adrian Casey. From opengeometry at yahoo.ca Fri May 7 15:33:58 2004 From: opengeometry at yahoo.ca (William Park) Date: 7 May 2004 19:33:58 GMT Subject: Python job opening at GPO in Washington, DC References: Message-ID: <2g26l5F3ovo0U1@uni-berlin.de> Nick Vargish wrote: > I've been way behind on reading this newsgroup, but I see someone > noticed the posting for someone who will be my co-worker and partner > in advocacy... > > steve at ferg.org (Stephen Ferg) writes: > > > I just saw this opening posted. It is a Federal government position > > (GS-13) at the Government Printing Office, Washington, DC, right > > across the street from where I work. > > We just got to interviewing for this position (government schedule, > obviously) and there were very few applicants with real-world Python > experience. Maybe I should have campaigned more heavily on this > newsgroup. > > I've been working to get Python accepted here at GPO, my main > arguments have been maintainability, portability, and developer > productivity. Hmmm, you're trying to convince your boss to do with less budget. So, he goes to his boss and says, "My IT budget was $10Million last year, but just give me $1Million this year. I've got Python." I don't think ANY government works this way. :-) What you should say is, "With Python (and Linux), we can outperform other departments with only %10 of our current resource. Pretty soon, we can take over their duties and their budgets. Our department will grow 5 folds in 2 years." -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From miki.tebeka at zoran.com Mon May 24 02:45:47 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 24 May 2004 08:45:47 +0200 Subject: Freeze and Resume execution In-Reply-To: <1MSdnc6R_LPYPi3dRVn-ig@powergate.ca> References: <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> <1MSdnc6R_LPYPi3dRVn-ig@powergate.ca> Message-ID: <20040524064546.GX1916@zoran.com> Hello Peter, > If you can't use threads, and you can't use Stackless, and if > exceptions don't allow restarting, and if generators preserve > only the current frame and not the entire stack (i.e. you can't > hand the generator state up to a higher level function, then > resume from there, which would be more like a coroutine I guess), > then it looks like handling this with classes/state machines is > your only option. I'm afraid that's what I'll do. Don't have time to play with stackless now although continuations seems like the right solution. BTW: I never had a good grasp on continuations in my Schemeing days. Generators are *way* simpler to understand and use. Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From mark at prothon.org Sun May 23 15:15:17 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 23 May 2004 12:15:17 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <9L6sc.11790$bF3.5202@fed1read01> "simo" wrote > One thing that might attract me from Python to Prothon is if it had > proper private medthods - i.e. not just name mangling like __myDef > which can be overridden using _myClass__myDef (as the interpreter > does). Interesting question. We don't have classes, so I'm not sure what we would be encapsulating and where we would encapsulate it. I developed Prothon so there would be a language without all this complexity and things to argue over. I guess people don't want simplicity after all. Without complexity there would be nothing to argue about on mailing lists :-) If you want to see what I mean by simplicity, check this out: http://prothon.org/tutorial/tutorial8.htm#pbp From chuck.amadi at ntlworld.com Sat May 1 08:43:18 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Sat, 01 May 2004 13:43:18 +0100 Subject: Python xmllib parser Module working Examples Message-ID: <40939B66.10706@ntlworld.com> Hi all I'm new to the list not bad at Java but limited Python (only basics) I will read my Python Book and variuos doc's but a little help is needed(Tight deadline looming). Im running Python 2.3 on Suse 9 Pro Im a Sys Admin and I have been given a task of getting Zope Survey (dmtl) web form that I have built that I have ebcapsulated with xml tags i.e I recived the Survey's via my inbox /var/spool/mail/chucka Thus I have got the mailbox Module working and I can view my mailbox running my python script. Thus I can anyone put me in the right direction or email a example of the xmllib parser Module as I need to read the emailed Survey that contain inbedded xml ie Eamil Body Message : transform thru to Python XML PASRER to popilate a PostGresql DB. Cheers Chuck I've been burning the candle at both ends lately. From Chris.Hornberger at blackrock.com Fri May 14 13:20:19 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Fri, 14 May 2004 13:20:19 -0400 Subject: Where do I find what colors and fonts are available? Message-ID: >> and font names are available on my system. I'm using Windows 2000. >I'd search for *.ttf (a particular kind of font file), and look at the >directories where several of these show up. This is, of course, a Win2K >rather than Python Question. On my installation, the fonts are in >C:\WINNT\Fonts. *nods* You mentioned that's a platform issue and not a Python issue. That's key, depending on what he's looking to do. If he's looking for platform independence (and who wouldn't be in Python?), whatever GUI manager he's using will probably have the necessary functions/libraries for enumerating the fonts that *it* knows how to deal with, which would be the more accurate way to find fonts... speaking, again, platform-independently. From bjg at network-theory.co.uk Sat May 1 08:09:06 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 01 May 2004 13:09:06 +0100 Subject: Replacing RPM with Source Install References: Message-ID: <87k6zw73j1.fsf@network-theory.co.uk> Richard Petty writes: > My first instinct was to remove the RPM version of Python but I got > a whole screenful of dependency warnings (see below). How should I > proceed? Should I go ahead and yank the RPM-based Python and then > compile/install the new version or should I try to keep both > installations? I'd recommended installing the new version separately, setting your PATH variable to use it, and leaving the system version of python unchanged. You can compile and install new versions of python in independent directories, such as /opt/python-2.3.3, with a command like: ./configure --prefix=/opt/python-2.3.3 See the README in the source for details. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From irmen at -nospam-remove-this-xs4all.nl Wed May 26 16:24:02 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 26 May 2004 22:24:02 +0200 Subject: Changing file names In-Reply-To: References: Message-ID: <40b4fce1$0$563$e4fe514c@news.xs4all.nl> Thomas Philips wrote: > How then can I change the existing filenames to these new filenames? > What python functions should I be using, and what modules are they > contained in? os.rename(oldfilename, newfilename) --Irmen From klappnase at web.de Sat May 15 21:14:37 2004 From: klappnase at web.de (klappnase) Date: 15 May 2004 18:14:37 -0700 Subject: tkinter button widget References: Message-ID: "Elaine Jackson" wrote in message news:... > I've got a script where a button gets pushed over and over: to cut down on the > carpal tunnel syndrome I'd like to have the button respond to presses of the > Enter key as well as mouse clicks; can somebody clue me in regarding how this is > done? Muchas gracias. > > Peace b = Button(master, command=do_something) b.bind('', lambda event, key='' : b.event_generate(key)) I hope this helped Michael From thelastmohiccan at yahoo.com Fri May 21 06:36:19 2004 From: thelastmohiccan at yahoo.com (lenk) Date: Fri, 21 May 2004 13:36:19 +0300 Subject: free psp host In-Reply-To: References: <2h4ijhF8g1alU1@uni-berlin.de> Message-ID: <2h644mF9e18lU1@uni-berlin.de> python server page :) Rico Huijbers wrote: > lenk wrote: > >> Hi all >> >> Where can I find ? >> >> thanks >> > Paint Shop Pro? > > I wasn't aware that application required hosting :P From peter at engcorp.com Fri May 14 07:11:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 07:11:39 -0400 Subject: Idea: PYTHONPATH_VER In-Reply-To: References: Message-ID: Pete Shinners wrote: > I've been working on systems that have multiple versions of python. > People are also trying to manage the compilation of external extension > modules. The problem is there is no easy way to control the separate > modules for each python version. > > I keep thinking having a separate PYTHONPATH environment variable for > each version of Python would really make life easier. I have heard Perl > started doing this sometime ago and it is in use on these same machines. I'm not entirely clear on the need for all this version stuff people keep talking about, but wouldn't the effect of the above be about the same as using a .pth file in the appropriate place for each different Python version on your machine? Then you can pick up different versions of different things at will depending on which version of Python is run. Having missed the discussion preceding, I'm probably off the mark, but in my experience just about everything that can be solved with PYTHONPATH can be handled with a .pth file as well, and I haven't had any need to use PYTHONPATH for quite some time as a result. -Peter From tjreedy at udel.edu Sun May 2 10:49:01 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 May 2004 10:49:01 -0400 Subject: Efficient string concatenation methods References: Message-ID: > Oliver Crow wrote: > > I found several sources with advice for how to do concatenation in a > > pythonic way (e.g. ref#1), but I hadn't seen any measurements or > > comparisons. So, I put together a little test case and ran it through > > for six different methods. Here's the results, and my conclusions: > > > > http://www.skymind.com/~ocrow/python_string/ > > > > I'd be happy to hear if anyone else has done similar tests and if > > there are any other good candidate methods that I missed. This def method4(): str_list = [] for num in xrange(loop_count): str_list.append(`num`) return ''.join(str_list) will run slightly faster modified to this: def method4(): str_list = [] append = str_list.append for num in xrange(loop_count): append(`num`) return ''.join(str_list) by factoring the method lookup out of the loop. Ditto for 3 and 5. Terry J. Reedy PS. Changing IE's View/TextSize changes size of header fonts but not body text, which your CSS apparently fixes at a size a bit small for me on current system. From dave at linux.local Sun May 2 17:03:42 2004 From: dave at linux.local (Dave) Date: Sun, 02 May 2004 22:03:42 +0100 Subject: uu.decode and 'Warning: Trailing garbage' messages Message-ID: Hi, How can I stop these messages 'Warning: Trailing garbage' being logged to the console? Dave From jfabiani at yolo.com Fri May 21 15:44:45 2004 From: jfabiani at yolo.com (john fabiani) Date: Fri, 21 May 2004 19:44:45 GMT Subject: Where's the demo for wxpython 2.5 In-Reply-To: References: Message-ID: Peter Hansen wrote: > john fabiani wrote: > >> Hi, >> I can find the demo files for the older versions of wxpython but not >> the new 2.5. Thanks > > > What platform are you on? Under Windows, a link to the demo is > put into your Start menu when you install and the code is under > site-packages/wx/demo. > > -Peter Sorry, I met the actual files (I have the old files) for download. Every time I attempt to download the file from wxpython's website it states the files are not available or corrupt. John From brent.hughes at comcast.net Sat May 22 17:23:36 2004 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Sat, 22 May 2004 21:23:36 GMT Subject: SciTE editor question Message-ID: I want to increase the number of files I can have open in the SciTE editor. The SciTEDoc.html document says to change the number of buffers in a file called SciTE.properties, but it doesn't say specifically how to specify this. So I tried putting this in the properties file: buffers=5 It didn't work. Maybe I need to qualify it in some way, like sys.buffers=5. Does anyone know about this? Brent P.S. If I'm in the wrong newsgroup for this question, please tell me which NG to use. From jfabiani at yolo.com Wed May 12 18:43:27 2004 From: jfabiani at yolo.com (john fabiani) Date: Wed, 12 May 2004 22:43:27 GMT Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: <87pt99tmyl.fsf@pobox.com> References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> Message-ID: John J. Lee wrote: > john fabiani writes: > [...] > >>I also have not discovered the way to print reports or any routines >>that will generate the detail bands etc... But I have faith that they >>are out there. I really hope that I don't have to hand code reports. > > > 'Report' is a fairly broad concept. It sounds like 'report' means > something quite specific to a VFP-er, though. If so, what would that > be? > > > John Big subject reports - in VFP we have a visual way to create printed reports. Normally, the report is associated with data (a cursor). The report form program loops thru the cursor and outputs the data to the report form to be printed either to the screen or a printer. The visual report editor allows the programmer to work with bands (detail,group, title, summary and several others). If you have worked with other report writers they generally work the same way. In a broad sense it's sort like working with a forms editor (boa). The report information is kept in a table and a report program reads the table to generate the output to the printer (along with the data). I think this how pyQT works to generate a window but pyQT uses a glade file (I think). Anyway, at the moment I don't have a way to send data to a printer. I'm guessing but I bet that simple text can be sent to a printer using Python (looping of course). But in today's world most users want graphics along with the data. Like an invoice with a logo, boxes around the bill to and ship to, along with column lines. So I'm hoping that someone has at least started a project to print reports. John From sean_berry at cox.net Fri May 14 01:16:01 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 13 May 2004 22:16:01 -0700 Subject: I need newbie help References: <10a83t8qku40d44@corp.supernews.com> Message-ID: <9CYoc.126297$Jy3.43222@fed1read03> You have to read the whole page to understand why. The title is: Python style switches. Python does not have a swith statement like many other languages. A switch statement could look like this: switch (a) case 1: do something case 2: do something else case 3: do something else default: do something else It evaluates a and checks to see if there is a matching case. If there is, it executes the code for that case. So if a==1, it would "do something." Since Python doesn't have a switch statement, you can make your own. In Python you could do something like this though: selector={ x<0 : 'return None', 0<=x<1 : 'return 1', 1<=x<2 : 'return 2', 2<=x<3 : 'return 3', 3<=x : 'return None' }[a] if a == 1, it would "return 1". "john fabiani" wrote in message news:F0Yoc.67040$Ub.57241 at newssvr25.news.prodigy.com... > Sean Berry wrote: > > > "Joseph Davidson" wrote in message > > news:10a83t8qku40d44 at corp.supernews.com... > > > >>I am an experienced perl programmer learning python ( no commente please > >>). > >> > >>In looking at a sample script at > >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708 > >> > >>I found the following code snippet. > >>-------------------------------------------------- > >>location = 'myHome' > >>fileLocation = {'myHome' :path1, > >> 'myOffice' :path2, > >> 'somewhere':path3}[location] > >> > >>----------------------------------------------------- > >> > > > > > > fileLocation takes the 'value' of the 'key' "location" > > equilvalent to: > > > > location = 'myHome' > > files = {'myHome' :path1, 'myOffice' :path2, 'somewhere':path3} > > fileLocation = files[location] > > > > > >>It seems that this is setting up fileLocation as a dictionary, but what > >>is the "[location]" doing? > >> > >>Joe Davidson > >> > >>-- > > > > > > > I'm also a newbie. Did the programmer that wrote the code not use your > way (3 statements) because his statement was faster or because it better > python? > > John From rogerb at rogerbinns.com Sat May 1 23:28:20 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 1 May 2004 20:28:20 -0700 Subject: Path ... where is my application's home dir? References: Message-ID: JanC wrote: > I guess Win9x users are more like 15-30% of the Windows-using population... Here is some stats from my web server where I host a FAQ for a US based cellphone. Obviously mileage may vary by country (and cell phone ownership :-) XP 59.3% 2000 19.3% NT 1.2% Me 2.6% CE 0.0% (45 hits total!) 98 6.7% 95 0.2% 2003 0.2% The numbers don't add up to 100, as there are hits from Mac (total 3.8%) Linux (1.2%) and Unknown (4.8%) plus a random smattering of others (eg WebTV and OS/2) You can compare with Google where you can see their worldwide figures for March: http://www.google.com/press/zeitgeist.html They have 22% for Windows 98, which seems to take proportionally from the figures in my stats. Of course we don't know what percentage of people configure their browsers to lie. Roger From michael at foord.net Wed May 26 03:39:45 2004 From: michael at foord.net (Fuzzyman) Date: 26 May 2004 00:39:45 -0700 Subject: r'\' - python parser bug? References: <5155aad2.0405250137.1cd7c53e@posting.google.com> Message-ID: <8089854e.0405252339.18e0c59d@posting.google.com> "Fredrik Lundh" wrote in message news:... > Tim Peters wrote: > > > Yup. Right now all tools (including Python itself) that scan over strings > > in Python source can (and usually do) treat backslashes identically, whether > > in loops or in regexps. > > Or in other words, the point here is that the prefix flag (u, r, whatever) doesn't > affect how a string literal is *parsed*. When the parser sees a backslash inside > a string literal, it always skips the next character. There's no separate grammar > for "raw string literals". > > Wrong, surely ? >>> print '\\' \ >>> print r'\\' \\ >>> print r'c:\subdir\' SyntaxError: EOL while scanning single-quoted string >>> > When the parser sees a backslash inside > a string literal, it always skips the next character. In the above example the parser *only* skips the next character if it is at the end of the string... surely illogical. The reason given is effectively 'raw strings were created for regular expressions, so it doesn't matter if the behaviour is illogical' (and precludes other reasonable uses!!).......... Regards, Fuzzy From segphault at sbcglobal.net Mon May 10 03:12:55 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 10 May 2004 07:12:55 GMT Subject: list comprehension References: Message-ID: On Mon, 10 May 2004 12:32:20 +1200, Guy Robinson wrote: > Hello, > > Trying to change a string(x,y values) such as : > > s = "114320,69808 114272,69920 113568,71600 113328,72272" > > into (x,-y): > > out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" > > I tried this: > > print [(a[0],-a[1] for a in x.split(',')) for x in e] > > But it doesn't work. Can anyone suggest why or suggest an alternative > way? The text strings are significantly bigger than this so performance > is important. > > TIA, > > Guy this works: s = "114320,69808 114272,69920 113568,71600 113328,72272" o = [(int(a[0]),-int(a[1])) for a in [b.split(',') for b in s.split(' ')]] print o [(114320, -69808), (114272, -69920), (113568, -71600), (113328, -72272)] From wilkSPAM at OUTflibuste.net Thu May 13 04:23:13 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 13 May 2004 10:23:13 +0200 Subject: Google and Python usage References: Message-ID: <87ad0czqfi.fsf@blakie.riol> cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > Everybody says Google uses Python, but I've never seen it... In almost all my web sites, i use only python but you'll never see a .py page... -- Wilk - http://flibuste.net From hotsnook at yahoo.com Thu May 13 01:47:17 2004 From: hotsnook at yahoo.com (Mark D) Date: 12 May 2004 22:47:17 -0700 Subject: Dabo 3-tier desktop framework for data-aware apps References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> Message-ID: <36799cf6.0405122147.6e5d93cb@posting.google.com> john fabiani wrote in message news:... > John J. Lee wrote: > > john fabiani writes: > > [...] > > > >>I also have not discovered the way to print reports or any routines > >>that will generate the detail bands etc... But I have faith that they > >>are out there. I really hope that I don't have to hand code reports. > > > > > > 'Report' is a fairly broad concept. It sounds like 'report' means > > something quite specific to a VFP-er, though. If so, what would that > > be? > > > > > > John > Big subject reports - in VFP we have a visual way to create printed > reports. Normally, the report is associated with data (a cursor). The > report form program loops thru the cursor and outputs the data to the > report form to be printed either to the screen or a printer. The visual > report editor allows the programmer to work with bands (detail,group, > title, summary and several others). If you have worked with other > report writers they generally work the same way. In a broad sense it's > sort like working with a forms editor (boa). The report information is > kept in a table and a report program reads the table to generate the > output to the printer (along with the data). I think this how pyQT > works to generate a window but pyQT uses a glade file (I think). > Anyway, at the moment I don't have a way to send data to a printer. > > I'm guessing but I bet that simple text can be sent to a printer using > Python (looping of course). But in today's world most users want > graphics along with the data. Like an invoice with a logo, boxes around > the bill to and ship to, along with column lines. So I'm hoping that > someone has at least started a project to print reports. > > > John Regarding reporting. I am new to python and have similar questions. I have briefly looked at www.reportlab.org and found their "Platypus" module very interesting and simple for creating PDF documents. A comprehnsive document framework is offered. With just a few lines of code you are able to generate professional reports. Handling tabular data via is also very easy. Have a look. Mark ps: first post (hope no blunders) From notlikely at nospam.com Fri May 21 08:02:49 2004 From: notlikely at nospam.com (John Doe) Date: Fri, 21 May 2004 08:02:49 -0400 Subject: migrating SpamBayes from Windows to Linux Message-ID: I have been trying Linux on-and-off for a couple of years but keep going back to Windows out of frustration. I have been using the Outlook plug-in for over a year and now that I am playing around with Linux again the first thing I did was install SpamBayes. I am looking for some easy way to migrate the existing database from Windows to Linux so I don't have to retrain from scratch. The Linux system is a Knoppix knx-hdinstall which is the latest Debian Sid. I also had to add the latest Python tarball for 2.3.3. And once that is done I will start working on why the SMTP proxy chokes on everything Kmail sends to it. lars(dot)kortsen(at)sympatico(dot)ca From jdhunter at ace.bsd.uchicago.edu Sun May 9 15:44:02 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 09 May 2004 14:44:02 -0500 Subject: emacs alphabetize methods Message-ID: Using emacs python-mode with a class class C: def method1(self): pass def anothermethod(self): pass def method2(self): pass is there any way to select all the methods and have emacs order them alphabetically? If not, is there a good too to do so? Thanks, John Hunter From Mike at DeleteThis.Geary.com Sat May 22 16:25:17 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 22 May 2004 13:25:17 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> <5sl4o1-crf.ln1@eskimo.tundraware.com> Message-ID: <10avdpe73rnj20d@corp.supernews.com> > Uri wrote: > > I have a file that looks like this: (but longer, no wordwrap) > > > > Name: Date: Time: Company: Employee Number: > > Jim 2.03.04 12:00 JimEnt 4 > > Steve 3.04.32 03:00 SteveEnt 5 > > > > I want to load 'Jim' and '12:00' and those types of answers into > > variables in my program, the only delimiter in the file is whitespace. > > How do I do this? > > > > I can do it with string.split(" ",[0]) type line for a file that's > > only delimited by single spaces, but when I'm searching for white > > space, how do I do it? > > > > THanks! Tim Daneliuk wrote: > Say you have read a line in the above format into variable 's'. > Then, > > l = s.split() > > will return a list containing each of the fields of the line as > an entry with the whitespace stripped out. Then, > > VarName = l[0] > VarDate = l[1] > VarTime = l[2] > VarCo = l[3] > VarEmp = l[4] D'oh! That's much better than the regular expression solution I posted. The regular expression split is good to know about for more complicated patterns, but for simple whitespace splitting there's no need for it. Thanks, -Mike From usenet at ixokai.net Thu May 20 19:39:30 2004 From: usenet at ixokai.net (Ixokai) Date: Thu, 20 May 2004 16:39:30 -0700 Subject: i18n/localization-- easily?? Message-ID: <10aqgdj5kkkmo9e@corp.supernews.com> I want to add internationalization to the software i'm writing now, but have run into a bit of a snag. It seems so darn complicated! Importing gettext, forcing it to grab the .mo from the correct location(nessecarily a bit non-standard in this situation), and using _() around my strings, those are all easy. But generating the .pot's seems impossibly complicated. Am I wrong or do I need to run pygettext on every single file in my system, manually? Then msgfmt? I was hoping that I could run it once, have it scan all of the python files referenced, and have it generate some global 'messages.pot', that I could then append to with subsequent executations (on different files). This doesn't appear to be the case. Did I miss something terribly? :) Thanks --Stephen From tzot at sil-tec.gr Mon May 24 12:02:25 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 24 May 2004 19:02:25 +0300 Subject: Solving the Einstein's Riddle in Python References: Message-ID: On Mon, 24 May 2004 14:12:38 +0300, rumours say that Juha Haataja might have written: >I have been learning Python since April, and would like a >few comments from the experts on list processing. > >I managed to implement a Python code for solving the >so-called Einstein's Riddle, see e.g.: > > http://www.manbottle.com/trivia/Einstein_s_Riddle.htm Perhaps you would like to take a look at my take on that at http://www.sil-tec.gr/~tzot/python/ (check for the logic_puzzle.py). It seems that it's slower than your version, but it's generic (ie you can describe similar combinatorial puzzles with an easy custom language). I have a couple of links in that page for the text files... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From tim.one at comcast.net Sun May 16 18:42:47 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 16 May 2004 18:42:47 -0400 Subject: web security question. In-Reply-To: Message-ID: [Christos TZOTZIOY Georgiou] > This message is related: > > > > I didn't test if Tim's snippet produces a segfault, though. It won't in Python 2.4, but still will in 2.3.4 (and earlier). People *allowing* access to the buffer() builtin in Web-based code are insane, though, and the sample code referenced requires (ab)using the buffer() builtin. As a sane counterexample, Zope removes buffer() from the built-ins available to Python code running under Zope. From mark at prothon.org Mon May 24 23:55:53 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 20:55:53 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> Message-ID: Josiah Carlson wrote: > You use inconsistant descriptions of generators here: > http://prothon.org/tutorial/tutorial11.htm#gen > > First you say that all generators must use 'gen' rather than 'def', > but > in your example you mix the two... > > gen evenOdds(max): > def evens(max): > (body contains a yield) > > Based on that same portion of your tutorial, it is not clear that your > example... > > gen evenOdds(max): > def evens(max): > num = 0 > while num < max: > yield num > num += 2 > > def odds(max): > num = 1 > while num < max: > yield num > num += 2 > > evens(max) > odds(max) > > for i in evenOdds(10): > print i, # prints 0 2 4 6 8 1 3 5 7 9 > > Actually should produce what you say it should. The code is correct and tested. My programming skills are much better than my tutorial writing skills :-) > Perhaps it is my background in Python that says unless you manually > iterate through evens(max) and odds(max), yielding values as you go > along... for i in evens(max): yield i > for i in odds(max): yield i > ...or combine and return the iterator with something like... > return itertools.chain(evens(max), odds(max)) > ..., you will get nothing when that generator function is evaluated. > > I believe that either your documentation or example needs to be fixed. I'm sure that my tutorial could be clearer, but in my defense I do say in that section: "only the one outermost "function" should use the "gen" keyword". The way it works is that the "gen" keyword is just a special flag to tell the interpreter to stop rolling up the execution frame stack when a yield keyword is encountered. This is what allows the functions to be nested. The yield keyword can be in any function whether it uses the gen keyword or the def keyword. I do think you are confusing it with Python, which cannot nest functions with yield statements as Prothon can. From tim.one at comcast.net Mon May 24 10:53:24 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 24 May 2004 10:53:24 -0400 Subject: r'\' - python parser bug? In-Reply-To: <5155aad2.0405240635.6c2915a5@posting.google.com> Message-ID: [Konstantin Veretennicov] > ActivePython 2.3.2 Build 232 > >>> '\\' > '\\' > >>> r'\' > File "", line 1 > r'\' > ^ > SyntaxError: EOL while scanning single-quoted string > > Is this a known issue? Yes, and a documented one: an r-string cannot end with an odd number of backslashes. Note that your first expression ('\\') did create a string with a single backslash, although the repr of that string may have fooled you into thinking you got two backslashes. >>> '\\' '\\' >>> len('\\') 1 >>> print '\\' \ >>> > Should i submit a bug report to development? Nope: it's not a bug, and won't change. From nomail at nospam.no Fri May 14 17:42:00 2004 From: nomail at nospam.no (Dominic) Date: Fri, 14 May 2004 23:42:00 +0200 Subject: trigger exception in generator Message-ID: I would like to trigger an exception in a generator upon return from "yield" e.g. def mySimulationTask(): while 1: try: # drive forward one simulation step yield # do some stuff except HitWall: # handle this disaster ;-) How can I possibly do this? Maybe by hacking some internal generator variables? ;-) Thanks, Dominic h i l l b r _at_ rhrk.uni-kl.de From vineet at eswap.com Thu May 27 18:28:59 2004 From: vineet at eswap.com (Vineet Jain) Date: Thu, 27 May 2004 18:28:59 -0400 Subject: Why a class when there will only be one instance? In-Reply-To: <40B66619.60108@stackless.com> Message-ID: > Just a little observation: > If you really want the class and the instance to be the same, > well, you can take a module. > In a sense, this *is* a class and the only instance. I need to use BASIC language like scripting in a python application. The users are not programmers and the scripting interface needs to be as simple as possible. The script would have a init section a run section a close section and some other parts as well. I have these sections defined as functions in a class (the class inherits from a base class) currently but have a feeling that I'm going to have to simplify things. Am not sure how users will handle class, functions, self, import, etc. I was thinking of using a module, but can I repeatedly call the module. If so how would I call it? Would I keep reloading it? Where does a module store it's state information between calls? I was thinking of supporting different sections by setting different variables which the user would access it: if init: do init code here if run: do run here if close: do close here Any other ideas? I'm trying to keep the scripting interface as simple as possible but at the same time give the users the power of python. Thanks, From dippyd at yahoo.com.au Tue May 11 23:48:53 2004 From: dippyd at yahoo.com.au (Steve) Date: Wed, 12 May 2004 13:48:53 +1000 Subject: Inverse of int(s, base)? References: <2gac73Fk1ooU1@uni-berlin.de> <7xhdungzpr.fsf@ruckus.brouhaha.com> <2gbrjqFvso5U1@uni-berlin.de> <7xu0ymn34r.fsf@ruckus.brouhaha.com> Message-ID: <40A19EA5.6050105@yahoo.com.au> Paul Rubin wrote: > Oliver Fromme writes: > >>Is creating strings really that expensive in Python? I'm >>surpised that you're saying that modifying a list and then >>calling reverse() and join() is more efficient. I thought >>that the overhead of compound objects such as lists is >>more expensive than creating strings, which I thought where >>rather "cheap and simple". > > > Actually, for these int conversions (unless they're large long ints) > it's no big deal. The concern is when you're building up a long > string (say, a 10 kilobyte html page) by concatenating a lot of short > strings. When you say "a = a + b" the cost is proportional to > len(a+b), since that many chars must get copied around. In the > extreme case, suppose you build up a 10k web page one character at a > time: [snip] This is a good time to remind newbies that the root of all evil lies in premature optimization (attributed to Donald Knuth). You could do worse than read Guido's anecdote: http://www.python.org/doc/essays/list2str.html Then, read Joel's discussion of "Shlemiel the painter's algorithm": http://www.joelonsoftware.com/articles/fog0000000319.html And an example of it here: http://lambda.weblogs.com/discuss/msgReader$3130 (see one of the last reader's comments) In conclusion: if you are absolutely positive that you are only going to be adding together a few short strings, then you gain much readability by just adding together short strings. But if you are going to be adding together lots of long strings, use lists and only convert to a string at the end. -- Steven D'Aprano From grante at visi.com Thu May 13 17:37:50 2004 From: grante at visi.com (Grant Edwards) Date: 13 May 2004 21:37:50 GMT Subject: struct doesn't handle NaN values? References: Message-ID: On 2004-05-13, David M. Cooke wrote: >> Perhaps I'm doing something wrong: the struct module docs say >> it's IEE 754, but I can't figure out how to get it to handle >> NaN values correctly (either packing or unpacking). > Doing this with the native format is no trouble: > Of course, if you want to worry about endian issues here, I think > you're SOL with using struct. Yes, I want to worry about endian issues. I'm communicating via DeviceNet, and DeviceNet specifies little-endian. I don't want to assume the host is little-endian, so I guess I'm SOL. :( OTOH, I suppose if I assume that 32-bit integers and floats have the same byte order, I can use 32-bit native integers as an intermediate format: nanString = struct.pack("f",float('nan')) nanInt, = struct.unpack("I",nanString) extNan = struct.pack(" <409ab831_3@127.0.0.1> <5_Pmc.73807$j11.882729@weber.videotron.net> Message-ID: Steve Menard writes: > thanks for your help guys. While I didnt manage to get pywin32 working > with python_d, I wrote my own little library to do the loadLibrary, > and that works. > > Thanks for the ctype hint though, I didnt know about it. Is it > portable across platforms? Yep. And it's called ctypes ;-) The windows version is stable/late-beta, non-windows is probably alpha. Let me add some further comments. IMO it pays off (if you have MSVC6) to get your whole stuff working in debug mode. At least pywin32 (if you use it), python, and your own stuff. And ctypes, of course. And it's not that complicated anymore. Here's what I do: - Install stock Python 2.3.3, from the python.org installer. - Download the Python sources, or grab them with CVS (the release-maint23 branch, if you use Python 2.3). Make a Python Debug build with VC 6, from the .dsw file. - In the PCBuild directory is a brand new pydebug.iss file (you have to get this with CVS or ViewCVS), it can be used to create a windows installer which installs the debug binaries alongside the release binaries. Use Inno Setup by double clicking the iss file to create the installer, and run it. - Grab the pywin32 source from CVS, and build it with distutils by entering 'python setup_win32all.py build' in the command prompt. This builds everything in release mode, which takes quite some time. Build in debug mode with 'python setup_win32all.py build -g'. Now create a windows installer by 'python setup_win32all.py bdist_wininst'. The installer is created in the dist subdirectory, an exe file. Run the exe file to install the stuff (will install both the release and debug build). Thomas From mark at freelance-developer.com Thu May 6 08:21:48 2004 From: mark at freelance-developer.com (Mark J. Nenadov) Date: Thu, 06 May 2004 08:21:48 -0400 Subject: linux1, linux2? References: Message-ID: On Thu, 06 May 2004 05:21:20 -0500, Stephen Boulet wrote: > What is the difference between linux1/linux2 that sys.platform returns? I would say that it is based on the Linux kernel version. -- Mark J. Nenadov From google.2.hteguh at spamgourmet.com Thu May 20 15:34:14 2004 From: google.2.hteguh at spamgourmet.com (Hendy Teguh) Date: 20 May 2004 12:34:14 -0700 Subject: Newbie's rant's and question :) (long post) Message-ID: <1e6f6533.0405201134.138b752c@posting.google.com> Hello, first, a little warning, may contain negative comments, this is truly my humble opinion, please consider it as a curious comments, not flaming or trolling (there're tendency i read on newsgroup (especially linux newsgroups), that newbie's opinion are often considered trolling, especially from diehard fans :P ). And also since english is not my native language, please forgive my bad english. Ok, a little background. i learned some programming language before, all DOS (QuickBASIC, Pascal and Assembly). But when VB 'boomed', i stopped programming (i didn't really like the way of visual programming). Lately i began to use linux and see that python is widely use in almost everywhere, i started to learn python. I've been learning python for about 2 or 3 months (not too seriously) and i've been learning from a lot of online tutorials. So far i have written 2 serious programs, one that remove certain attributes from HTML tag, the other one auto-rename all images that a page use into sequential order. All are done manually (read, parsed, edited and wrote back). I think i pretty much grabbed the basic of python language (although sometime still need to look for command reference). 1. I actually has a lot of idea of program that i want to write, but since the 'basic' python has pretty much limitation in outputing result (No GUI), so i think it's time for me to learn GUI extension. After searching around, i finally decided to learn wxPython. I try to follow the tutorial from the website, but it seemed that the tutorial is written in mind that we have learned any GUI programming before. I stopped on the middle of the tutorial since everything looks 'out of control'. I (guess i) do know what the commands do, most question is like 'where the heck does this command come from?' which lead to 'if i want to do this, what should i do?'. i tried to search for other wxPython tutorial, but it seems a little scarce. i googled around and found out that many expert always recommended to look for reference from the demo file and the help file. So, i try to learn by myself. It took me nearly 30 minutes 'wreck havocing' the demo files and wxWindow reference just to find the command to refresh the menu (which i've disabled). This is very - very discouraging for me. Am i doing something wrong here or is this the correct 'process' of learning GUI programming? I feel like there're a lot of missing step from the 'basic' python tutorial to 'expert' python tutorial. 2. so far i learned python, i got the impression that python is more like a scripting language than programming since python rely heavily on external libraries (i may be biased on this because i also currently learning Blender 3D which use python as the scripting language). In other word, somehow python is 'teethless' in doing something 'powerful' by itself IMHO. I'm planning to write a simple graphic viewer in paralel learning GUI. Since python don't support natively jpeg or png (am i right?), do i need to find library to read those file or should i find the format of each extension and decode with python by myself? if i can use library, could anyone guide me where to find supporting library for python? (I once every tried to google for zip handling library, found only zlib, seems only handling ZIP compression not the zip file itself). 3. just a curious question, why doesn't python include a basic library (GUI for example)? the library doesn't necessarily need to be optimised, just to help introducing the way python work. An example Pascal language, it included some library to handle graphic mode. Not very optimised, but it really-really help me a lot in understanding graphic mode. When i'm good enough and feel that it's very slow, i could either search for better library or just programmed it myself (in my case, i made a library from assembly). The point is that it could really - really help the beginner to learn. ok, end of my rants here :) Best regards, Hendy From peter at engcorp.com Fri May 14 17:00:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 17:00:34 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: References: Message-ID: Hornberger, Chris wrote: >>WINDOWS >>... Windows users may also be >>interested in Mark Hammond's win32all, a collection of >>Windows-specific extensions including COM support and Pythonwin, an >>IDE built using Windows components. > > PS... I have moral and ethical arguments against this. I believe it's just plain WRONG to use a language like Python or Java or even C#/.NET and RELY on platform specific "extensions". > > If it ain't cross platform, then it's VB. Oh dear, I'm so sorry. I'll stop using Python immediately and switch to Visual BASIC for my work, which relies on interfacing with DLL files provided by third parties (using ctypes and calldll) and which therefore must run on Windows. I really apologize. I had *no idea* I was committing a moral and ethical mistake in using Python for this kind of work. I have sinned. I must commit supuku. So long, world. -Peter (Was the sarcasm a little too thick there? What a ludicrous statement to make...) P.S.: I see the followup to Thomas' response. It makes no difference. You are still saying I must not use Python for Windows-only work merely because it _can_ do cross-platform work. The logic there is real, real weak. From amireallyfat at yahoo.com.au Fri May 28 00:54:46 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Fri, 28 May 2004 14:54:46 +1000 Subject: lists or tuples References: <40b2e203$1_1@news.iprimus.com.au> Message-ID: <40b6c611_1@news.iprimus.com.au> great thanks "mr_vocab" wrote in message news:40b2e203$1_1 at news.iprimus.com.au... > hey what is the many dif with them why bothere using tuples and how do you > edit a list??? > > thanks > > From theller at python.net Fri May 7 02:20:47 2004 From: theller at python.net (Thomas Heller) Date: Fri, 07 May 2004 08:20:47 +0200 Subject: Debuggin a ptyhon extension References: <409ab831_3@127.0.0.1> Message-ID: > "Steve Menard" wrote in message > news:rzxmc.26524$j11.254148 at weber.videotron.net... >> I am writing a python extension module in VC++ on windows. At some >> point, my extension crashes. >> >> Now I want to debug exactly why. I built the python projects in VC++, >> and put the resulting python_d.exe in my ptyon home directory, and >> the python23_d.dll in the windows/system32 directory. I also tried to >> put the python23_d.dll in python's home directory, to the same >> result. >> >> Problem is, running my scripts/extension with python_d.exe, it always >> complains it can't find win32api. Yes, I am using win32API to preload >> a dll, and can't really get rid of it. >> "Roger Upole" writes: > It's probably looking for the debug version of win32api > (win32api_d.pyd, which will also require a debug build of Pywintypes). > You can grab the pywin32 source and roll your own debug binaries, or > alternately you might be able to get away with creating a release > build of Python that contains debug info. If Steve only uses win32api to call LoadLibrary it is probably easier to use ctypes for that. Of course he needs a debug version of ctypes, but that should build out of the box from the sources, if he has VC. >> Are my problems caused because python 2.3.3 (and possible win32all) were >> build using VC.net? No, python 2.3 and pywin32 (formerly called win32all) are built using MSVC 6. Thomas From newsgroups at jhrothjr.com Tue May 4 21:35:02 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 4 May 2004 21:35:02 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: <109gh8ml6lo6o7b@news.supernews.com> "Stephen Ferg" wrote in message news:b16e4ef7.0405041554.33a03c05 at posting.google.com... > I've been wondering how we can improve the quality of the Python > documentation. Frankly, I think it's pretty good as it stands. There are some places where it could be improved: documenting new style classes is an outstanding example, but by and large it's better than most efforts I've seen. > The problem with the Python documentation is that it is not being > handled like an open source product. The hallmark of open-source > development is that many people contribute. The Python docs in > contrast are being maintained by a very small group. You're confusing process with result. > I'm sure that many people would like to contribute to the improvment > of the documentation... the problem is that there is no way that they > can do so easily. The solution is to move to a different model of the > documentation process, by developing a way to make it easy for > everyone in the Python community to contribute to the documentation. > > One solution is a documentation wiki: see the request (below) for a > "corresponding wikiable page for every page here in the pydocs." A > similar but better solution is to follow the model created by the PHP > community. If you follow the link to > http://us2.php.net/manual/en/function.sort.php you'll see how > impressive the results can be. Something like this is clearly what we > need. I've looked at it. I'll certainly say it's impressive, but I doubt if my impression is what you though it would be. > So I put this question to the entire Python community. Can we create > an interactive site, and the supporting organizational infrastructure, > that will enable everyone in the Python community easily to contribute > to the Python documentation? As Andrew commented, there's nothing stopping you from contributing. There's also nothing stopping you from setting up a wiki yourself so people can comment on various pages of the official documentation. John Roth > > -- Steve (Stephen Ferg ... Steve at Ferg.org) > From jhd at radix.net Thu May 13 20:15:36 2004 From: jhd at radix.net (Joseph Davidson) Date: Fri, 14 May 2004 00:15:36 -0000 Subject: I need newbie help Message-ID: <10a83t8qku40d44@corp.supernews.com> I am an experienced perl programmer learning python ( no commente please ). In looking at a sample script at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708 I found the following code snippet. -------------------------------------------------- location = 'myHome' fileLocation = {'myHome' :path1, 'myOffice' :path2, 'somewhere':path3}[location] ----------------------------------------------------- It seems that this is setting up fileLocation as a dictionary, but what is the "[location]" doing? Joe Davidson -- From jcarlson at uci.edu Mon May 24 20:06:02 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 24 May 2004 17:06:02 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <6iTrc.9506$bF3.8687@fed1read01> References: <6iTrc.9506$bF3.8687@fed1read01> Message-ID: > See http://prothon.org. You use inconsistant descriptions of generators here: http://prothon.org/tutorial/tutorial11.htm#gen First you say that all generators must use 'gen' rather than 'def', but in your example you mix the two... gen evenOdds(max): def evens(max): (body contains a yield) Based on that same portion of your tutorial, it is not clear that your example... gen evenOdds(max): def evens(max): num = 0 while num < max: yield num num += 2 def odds(max): num = 1 while num < max: yield num num += 2 evens(max) odds(max) for i in evenOdds(10): print i, # prints 0 2 4 6 8 1 3 5 7 9 Actually should produce what you say it should. Perhaps it is my background in Python that says unless you manually iterate through evens(max) and odds(max), yielding values as you go along... for i in evens(max): yield i for i in odds(max): yield i ...or combine and return the iterator with something like... return itertools.chain(evens(max), odds(max)) ..., you will get nothing when that generator function is evaluated. I believe that either your documentation or example needs to be fixed. - Josiah From peter at engcorp.com Tue May 18 21:07:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 May 2004 21:07:50 -0400 Subject: Python compilers? In-Reply-To: References: Message-ID: <6PSdnR1CG8r6LjfdRVn-hg@powergate.ca> Tor Iver Wilhelmsen wrote: > Grant Edwards writes: > >>Dude, didn't you take high-school math? 1/3 _is_ 0.33333... > > No, because at some point you will stop writing 3's, either out of > boredom, exhaustion or because you need to pee. At that instant, you > introduce a rounding error, making 3 * 1/3 = 0.99999999999... instead > of 1.0 Actually, Grant probably meant the "..." (which is an ellipsis, meaning it substitutes for something else that is left out) to represent "3 repeating to infinity", the same as putting a dot over the last 3, or a bar over the last three 3s, or whatever other convention you might have seen. Of course, it's just a convention, so perhaps someone else would think it meant "3s repeating to the limit of the computer's precision" or something like that... -Peter From loic at fejoz.net Thu May 6 10:33:55 2004 From: loic at fejoz.net (Yermat) Date: Thu, 06 May 2004 16:33:55 +0200 Subject: classes vs dicts In-Reply-To: References: <7id65haegq.fsf@enark.csis.hku.hk> Message-ID: Holger T?rk wrote: > > > Isaac To wrote: > >>>>>>> "Charlie" == Charlie writes: >> >> Charlie> Greetings, I am pretty new to Python and like it very >> much, but >> Charlie> there is one thing I can't figure out and I couldn't really >> Charlie> find anything in the docs that addresses this. >> >> Charlie> Say I want to write an address book program, what is the >> best >> Charlie> way to define a person (and the like): create a class (as I >> Charlie> would do in Java) or use a dictionary? I guess using >> Charlie> dictionaries is fastest and easiest, but is this >> recommended? >> >> >> Python is about making the complexity where it worth. If you cannot see >> that a class will help, the safe choice is to do it with a dict. >> Later, if > > > > I don't think so. If you don't want to define set... and get ... > methods, you can still misuse a class in this way: > > > class Person (object): pass > > somePerson = Person () > somePerson.name = "his name" > somePerson.address = "her address" > > > instead of > > > somePerson = {} > somePerson ["name"] = "his name" > somePerson ["address"] = "her address" > > > The first alternative is easier to read and even safer: > If you need to extend the capabilities of the class, you can > still redefine the behaviour of the data fields using > descriptors. > > Greetings, > > Holger > And do remember that actually, class ARE (kind of) dictionnary : >>> class Person(object): pass ... >>> somePerson = Person() >>> somePerson.name = "his name" >>> somePerson.address = "his address" >>> >>> somePerson.__dict__ {'name': 'his name', 'address': 'his address'} So the real question is what do you prefer to type : somePerson.name or somePerson["name"] ? -- Yermat From nospam-trice at comcast-nospam.net Fri May 7 00:59:38 2004 From: nospam-trice at comcast-nospam.net (Tim) Date: Fri, 7 May 2004 00:59:38 -0400 Subject: printing float as formatted dollars References: Message-ID: "Larry Bates" wrote in message news:YtqdnZOyj_KSfArdRVn_iw at comcast.com... > Here is a function I wrote and use. Note: floats > have rounding "issues" when they get very large. > > def fmt_wcommas(amount): > # > # This function will take the number passed to it and format it with > # spaces as thousands separators. > # > # If I got zero return zero (0.00) > # > if not amount: return '$0.00' > # > # Handle negative numbers > # > if amount < 0: sign="-" > else: sign="" > # > # Split into fractional and whole parts > # > whole_part=abs(long(amount)) > fractional_part=abs(amount)-whole_part > #print "whole_part=",whole_part," fractional_part=",fractional_part > # > # Convert to string > # > temp="%i" % whole_part > # > # Convert the digits to a list > # > digits=list(temp) > #print "digits=", digits > # > # Calculate the pad length to fill out a complete thousand and add > # the pad characters (space(s)) to the beginning of the string. > # > padchars=3-(len(digits)%3) > #print "padchars=",padchars > if padchars != 3: digits=tuple(padchars*[' ']+digits) > else: digits=tuple(digits) > #print "digits='%s'" % str(digits) > # > # Create the mask for formatting the string > # > sections=len(digits)/3 > mask=sections*",%s%s%s" > outstring=mask % digits > # > # Drop off the leading comma and add currency and sign > # > outstring=sign+"$"+outstring[1:].lstrip() > #print "outstring (int)=", outstring > # > # Add back the fractional part > # > outstring+=("%.2f" % fractional_part)[1:] > # > return outstring > > if __name__=="__main__": > > print "----------testing negative floats------------------------------" > sign=-1 > invalue=0L > for j in range(2): > for i in range(1,10): > invalue=invalue*10+i > print fmt_wcommas(float(sign*invalue)-.01) > > print "----------testing positive floats------------------------------" > sign=1 > invalue=0L > for j in range(2): > for i in range(1,10): > invalue=invalue*10+i > print fmt_wcommas(float(sign*invalue)+.01) > > > "Tim" wrote in message > news:aNadndnHDepsqQjd4p2dnA at adelphia.com... > > Is there a simple way to output float values as formatted dollar amounts? > > i.e. 127379.42 as $127,379.42 > > > > Thanks, > > Tim > > > > > > > > > > Thanks for the code!, it was a big help. I had started trying to piece together some logic (below), but I know there are holes in it (negative numbers, for one). >>> flo=1234567.89 >>> l=list(str(flo)) >>> l ['1', '2', '3', '4', '5', '6', '7', '.', '8', '9'] >>> l.reverse() >>> rl=[]; foundDecimal=0 >>> for x in l: ... if (x=="."): ... foundDecimal=1 ... rl.append(x) ... pos=0 ... elif(foundDecimal): ... pos+=1 ... rl.append(x) ... if (not(pos%3)): rl.append(',') ... else: rl.append(x) ... >>> rl ['9', '8', '.', '7', '6', '5', ',', '4', '3', '2', ',', '1'] >>> rl.append('$') >>> rl.reverse() >>> rl ['$', '1', ',', '2', '3', '4', ',', '5', '6', '7', '.', '8', '9'] >>> result="".join(rl) >>> result '$1,234,567.89' >>> From rjt-usenet at thegrindstone.me.uk Thu May 6 05:59:39 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Thu, 06 May 2004 10:59:39 +0100 Subject: rectangle layout algorithm? Message-ID: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> Hi I need an algorithm to layout a collection of rectangles (images) within a bounding rectangle (sheet of paper). I feel sure that I am not the first person faced with this problem :-) Does anyone know of a Python library that provides such a capability? (Actually building the composite image is not a problem, I am going to use PIL to do that. It is knowing where to place the images that I need to solve.) Many thanks. Richard From paul at boddie.net Thu May 27 11:06:01 2004 From: paul at boddie.net (Paul Boddie) Date: 27 May 2004 08:06:01 -0700 Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <23891c90.0405270706.311b740e@posting.google.com> Jacek Generowicz wrote in message news:... > > Ryan Paul writes in this very thread: > > > I dont understand why everybody seems to want a machinecode compiler. It > > wont make a high-level, dynamically typed language run any faster. > > I guess there are different ways of interpreting the plethora of > contributions such as the above. Maybe my I'm misunderstanding them. Then I must have misunderstood them, too. Perhaps the author could qualify his statement in light of the evidence brought to light, in addition to the existence of technologies such as Psyco. The intention may really have been to claim that even a sufficiently powerful type inferencing mechanism, acting before run-time on very general code which uses polymorphism extensively (roll out all those short code snippets), won't produce significantly faster programs; but short and snappy sweeping statements generally sacrifice meaningful qualification for the sake of leaving an impression of higher knowledge withheld from the inquiring masses. Paul From elainejackson7355 at home.com Thu May 20 22:49:15 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 21 May 2004 02:49:15 GMT Subject: terminological obscurity Message-ID: Some questions from a curious monkey. All tuple methods are also list methods, and most list methods are also tuple methods; among those that are NOT also tuple methods, there are exactly two ('count' and 'index') that do not involve mutation. Is there any special reason why they AREN'T also tuple methods? ################################################################# A question about terminology ('namespace'): >>> prince=tuple() >>> king=[prince] >>> del prince At this point, does the object formerly known as prince belong to the namespace implemented by globals()? More generally, is there a terminological way to distinguish between (1) a function from a set of names into a set of objects, and (2) the aforementioned set of objects? ################################################################# Is there a handy noun that refers to sameness of identity in the same way that 'equality' refers to sameness of value? ('Identicalness' is pretty clumsy, and 'identity' is confusing, since it already has a meaning that is closely related but needs to be kept distinct.) ################################################################# A question about terminology ('name'): Suppose X is a container that contains n items (incidentally, is 'items' the right term?) and i in an integer with 0<=i<=n. Does " X[i] " count as a 'name'? From apardon at forel.vub.ac.be Thu May 13 07:26:28 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 11:26:28 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: Op 2004-05-13, Andrew Bennetts schreef : > On Thu, May 13, 2004 at 07:58:07AM +0000, Antoon Pardon wrote: >> Op 2004-05-13, Greg Ewing schreef : > [...] >> >> > Besides, the semantics are as consistent as anything >> > else in Python, where the objects being operated on >> > get to determine the meaning of just about everything. >> >> So? Would you argue that the devellopers could just >> as easily have implemented "a += b" as equivallent to >> "a = a - b" with half of the core classes and called that >> just as consistent as choosing it equivallent to >> "a = a + b" for all core classes because the objects >> being operated on get to determine the meaning? > > Well, classes get to do whatever they think makes sense: in the end it's all > calls to methods of the object, whether via an actual method call > "obj.foo()" or by an operator "obj * 2" (which calls obj.__mul__(2)) or an > augmented assignment "obj += 'x'" (which calls obj.__iadd__('x')). It's up > to the objects to make sense, not the Python language. And how do you think objects can make sense where the language doesn't? I don't want to imply the language doesn't make sense at all, but you can't claim the responsibility is all for the objects if the language or its core classes have defiencies or are not consistent with each other. > Even though Python chooses to have some immutable builtin types (like > ints and strings) for a variety of practical reasons, augmented assignment > does what people expect in all these cases: > > s = 'abc' > s += 'd' > > i = 7 > i += 3 > > l = [1, 2, 3] > l += [4, 5, 6] > > Augmented assignments are still assignments, and that makes perfect sense to > me -- each of those behave exactly like their obvious longer versions: > > s = 'abc' > s = s + 'd' > > i = 7 > i = i + 3 > > l = [1, 2, 3] > l = l + [4, 5, 6] > > (Yes, there are tricky examples that do behave differently -- but I try to > avoid tricky things, because they tend to be hard to read. I almost only > find I want to use augmented assignment on integers and occasionally > strings.) But these things are only hard to read (to you, I don't find it so) because you are using constants in the expression. a += b, is just as hard to read whether a and b are lists or integers. The problem is that because the behaviour with strings and lists is different I can't write a program in which the behaviour of += is consistent for all classes because there will always be core classes for which the behaviour will be different. It is a bit like having some classes use "+" for substraction. In it self that wouldn't be so bad, you just have to pay attention. But then you want to write a class that will work with whatever number type and it needs to do additions. Now suddenly things get difficult because a + b doesn't behave consistently among the different number types. You have the same kind of difficulty now if you want to write a class/function/module that works with any kind of sequence. Using the "+=" operator you can't guarantee any kind of consistency. If I had code like this: a = b b += c I would have no idea at all whether a was changed or not. So writing code that can work with any sequence becomes a possible problem spot if you use these kind of operators. -- Antoon Pardon From __peter__ at web.de Fri May 28 03:14:18 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2004 09:14:18 +0200 Subject: Canvas polygon coords() using list comprehension References: Message-ID: Dave Harris wrote: > I have written a reasonably clean way to perform coordinate > transformations on a polygon, but Tkinter Canvas is not being particularly > cooperative. The following program has been distilled down to a minimum > and generates a traceback (see below) when it runs. > > It appears that the create_polygon() method is more versatile than the > coords() method. > > Could someone can suggest a way to have the list comprehension not > generate tuples, that would probably create a coordinate list acceptable > to coords()? You can explicitly flatten the list: import Tkinter from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() c = Canvas(frame, width=300, height=300) c.pack() outline1 = [(100, 0), (200, 50), (150, 150)] p1 = c.create_polygon(outline1, fill='', outline='black') p2 = c.create_polygon(outline1, fill='', outline='red') outline2 = [(x+10, y+20) for (x, y) in outline1] c.coords(p2, Tkinter._flatten(outline2)) root = Tk() app = App(root) root.mainloop() Peter From grante at visi.com Sat May 1 12:42:49 2004 From: grante at visi.com (Grant Edwards) Date: 01 May 2004 16:42:49 GMT Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: <4093d389$0$17262$a1866201@newsreader.visi.com> In article , Knio wrote: > You can't get greater then 1ms accuracy when measuring a time > on todays machines, and that will be less when measuring time > over a network... Not sure what you mean by "todays machines", but on a Pentium-class machine running Linux, you get approx 1us resolution with calls to time.time(): import time t = [] for i in range(10): t.append(time.time()) print t [1083429542.284164, 1083429542.2841799, 1083429542.2841859, 1083429542.2841921, 1083429542.284198, 1083429542.284204, 1083429542.284209, 1083429542.284215, 1083429542.2842209, 1083429542.2842269] The Linux network stack also provides timestamps on the network packets with at least 1us resolution. > calling 4 ping functions one after the other will complete in much less > then 1ms (assuming its asynchronous, or threaded). So, even if you could > manage to send 4 packets at *exactly* the same time, People, Ethernet is a _serial_ protocol. It allows exactly one packet to be transmitted at a time. There is no way to send more than one packet at a time. > it would be no more accurate. -- Grant Edwards grante Yow! As President I at have to go vacuum my coin visi.com collection! From claird at lairds.com Mon May 24 20:16:25 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 25 May 2004 00:16:25 -0000 Subject: Tkinter MDI-style widget? References: <2e363c08.0405240720.6831f33@posting.google.com> Message-ID: <10b542pii84l335@corp.supernews.com> In article <2e363c08.0405240720.6831f33 at posting.google.com>, Paul Miller wrote: >I posted a couple of days ago looking for pointers on how to create a >wiget that has a settable title and can't be moved outside the parent >widget. What I'm really looking for is a Windows-style MDI widget. >Does this exist/is it possible to make in Tkinter? > >The only thing I know of that behaves sort of the way I want is the >Tkinter canvas item. Now I know you can create new canvas items >through the tcl C interface, but would even that make it possible to >do what I want? (Not that I really want to go that route, anyway.) has several tips on the topic. George Staplin, in particular, has done nice work on this subject from a Tcl/Tk basis. -- Cameron Laird Business: http://www.Phaseit.net From gandalf at geochemsource.com Fri May 7 07:38:55 2004 From: gandalf at geochemsource.com (Gandalf) Date: Fri, 07 May 2004 13:38:55 +0200 Subject: mod_python problem In-Reply-To: References: Message-ID: <409B754F.30708@geochemsource.com> >>Apache/2.0.48 (Unix) PHP/4.3.4 mod_python/3.0.3 Python/2.3.3 >>mod_ssl/2.0.48 OpenSSL/0.9.7c Server at arwen.msnet Port 80 >> >>This is what I have in httpd.conf: >> >>LoadModule python_module libexec/apache2/mod_python.so >>AddHandler mod_python .py >>AddType applcation/x-http-python .py >> >> > >Try: > > AddHandler python-program .py > >The "AddHandler mod_python .py" version is intended to work with mod_python >3.1.3 and higher. Check out http://www.modpython.org/FAQ/faqw.py?req=all. > >For sympathy's sake, I've been using the manual released with 3.1.0a which also >uses "AddHandler mod_python" and doesn't mention python-program at all. > >Aloha, >the poiboy > God bless you! I have been trying for days without success. Now I got this error below, and I'm very happy with that. No question, I can handle from here. :-) Many thanks, G http://arwen.msnet/index.py: Mod_python error: "PythonHandler index" Traceback (most recent call last): File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 320, in HandlerDispatch module = import_module(module_name, config) File "/usr/local/lib/python2.3/site-packages/mod_python/apache.py", line 496, in import_module f, p, d = imp.find_module(parts[i], path) ImportError: No module named index -------------- next part -------------- An HTML attachment was scrubbed... URL: From fumanchu at amor.org Thu May 20 17:00:38 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 May 2004 14:00:38 -0700 Subject: Newbie's rant's and question :) (long post) Message-ID: Hendy Teguh wrote: > i tried to search for other wxPython tutorial, > but it seems a little scarce. You're right; it is scarce. > Since python don't support natively jpeg or png (am i right?), do i > need to find library to read those file or should i find the format of > each extension and decode with python by myself? Check out the Python Imaging Library: http://www.pythonware.com/products/pil/ > 3. just a curious question, why doesn't python include a basic library > (GUI for example)? If you read the Library Reference (http://docs.python.org/lib/lib.html) you'll see Section 16 titled, "Graphical User Interfaces ith Tk". If you want something even simpler, look at Steve Ferg's EasyGUI: http://www.ferg.org/easygui/ Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From Mike at DeleteThis.Geary.com Mon May 10 17:15:36 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 10 May 2004 14:15:36 -0700 Subject: What I don't like about wxPython References: <283adf56.0405100657.6f4840ef@posting.google.com> Message-ID: <109vs7p2gj3re36@corp.supernews.com> > > I'll throw a plug in here for pyFltk. It overcomes many of > > the issues you have with wxPython. It's not as heavily > > developed as the wxWin, but Andreas is doing a great job > > of updates since taking it over. > Thx for mentioning. I'd like to look into this, can I get a link? Sure: http://www.google.com/search?q=pyFltk -Mike From tim.one at comcast.net Thu May 13 22:51:09 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 13 May 2004 22:51:09 -0400 Subject: struct doesn't handle NaN values? In-Reply-To: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> Message-ID: [Grant Edwards] > My question was which "native" and "standard" mode? > There appear to be two different "modes": "byte order" and "size and > alignment". Which of the two modes determines the floating > point representation to be used? My interpretation of the doc > was the latter: use native FP representation when it says > "native" in the "size and alignment" column and use IEEE when > it says "standard" in the "size and alignment" column. Yes, that's correct. ... > In order to provide robust translation between native and IEEE > floating point formats, Python is going to have to know what > the native format is. Of course. > Recognizing and generating IEEE NaNs, infinities, 0's and- > denormals is easy enough. [etc] There's nothing new to be said about any of this, and I don't have time to pursue it regardless. If you want to commit to improving the story here, please do. Others have tried, over the course of a decade, but nothing has come of it apart from the PEP 754 reference implementation (which doesn't address struct or pickle issues). It's a large task to give Python a *good* x-platform 754 story, but it would indeed be easy to make large isolated improvements in small areas on major platforms. From ajsiegel at optonline.com Mon May 24 20:20:14 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 May 2004 00:20:14 GMT Subject: terminological obscurity References: <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> Message-ID: <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> On Mon, 24 May 2004 11:51:37 -0700, Donn Cave wrote: >That's reasonable, but can you explain your hypothesis? >Like, what is it about the current class/type structure >that has anything to do with this? I don't see it. Well for one, before new style classes, it was easier to think of an "instance" as in some sense a pseudo data type. Instances of different classes - even with no hierarchical relationship - were more conceptually homogenous. But with everything subclassable, 2 different classes, each derived from object, are conceptually distinguished more similarly to the way in which a str and int are distinguished. So in quoteth Guido from the same thread: GvR> I always think of the type of a list as "list of T" while I GvR> think of a tuple's type as "tuple of length N with items of GvR> types T1, T2, T3, ..., TN". So [1, 2] and [1, 2, 3] are both GvR> "list of int" (and "list of Number" and "list of Object", of GvR> course) while ("hello", 42) is a "2-tuple with items str and GvR> int" and (42, "hello", 3.14) is a "3-tuple with items int, GvR> str, float". He sort of stacks the cards by making his tuples of hetereogenous type, and his list easily described as a list of T. And thereby sidesteps all the ambiguities inherent in the ten word edict. Except that at the Object level, we are at lists of Objects and tuples of Objects. It detracts little from the point of the above quote, but this quote then becomes substantially weaker as support for his 10 worder. Is the best I can express it. > >As far as the group dynamics & Guido go, you can probably >forget that. There are all kinds of things going on, and >that could play a role, but only a weak one. People have >a lot of strong opinions about programming languages, and >if people here seem to find it easy to agree with Guido, >the simplest explanation is that they choose to use Python >and hang out on comp.lang.python because they like it. I like Python and choose to hang on Python list, and find it easy to disagree with Guido. But that only occurs head-on when he ventures into non-technical areas were I consider the playing field more even. And this depsite the fact I would have no problem granting him a higher IQ. Since I have lived in close quarters with higher IQs, and have a pretty developed sense, I think, of what that buys you, and what it doesn't. Art From skip at pobox.com Sat May 22 11:01:56 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 22 May 2004 10:01:56 -0500 Subject: cannot import csv In-Reply-To: <1085231221.3606.49.camel@dev.internal> References: <425cc8d1.0405220458.9668650@posting.google.com> <1085231221.3606.49.camel@dev.internal> Message-ID: <16559.27492.543541.9775@montanaro.dyndns.org> Mark> What version Python are you using? csv was introduced with 2.3 (I Mark> think). Correct. Our goal when writing it was for it to be 2.2-compatible though, so you ought to be able to grab csv.py and _csv.c from the 2.3 distro and drop it into your 2.2 distro (with suitable setup.py or Modules/Setup.local mods of course). Skip From spam at pky2k.de Sun May 23 16:53:45 2004 From: spam at pky2k.de (Philipp Kruse) Date: Sun, 23 May 2004 22:53:45 +0200 Subject: py2exe setup script problem Message-ID: <2hchapFbelulU1@uni-berlin.de> I am trying to create an executable version of a python script using py2exe 0.5 (Python 2.3.4c1). The basic script looks something like this: setup( [...] windows = [ 'src/__main__.py', { 'script': 'src/__main__.py', 'icon_resources': [(1, "data/small.ico")]} ], ) After running py2exe I try to execute the created .exe file and - nothing happens. However, I tried changing the script to this: setup( [...] console = ['src/__main__.py'], ) Suddenly everything works fine. Even so, I simply need to get rid of that console window. I tried reading through the wiki and searched this group but found nothing that could solve the problem. Does anyone have an idea? Philipp From abakhshi at legato.com Mon May 3 13:44:38 2004 From: abakhshi at legato.com (Ajay Bakhshi) Date: Mon, 3 May 2004 10:44:38 -0700 Subject: HP - fork & exec in Threads hang - intermittently Message-ID: <96F3EC4BDF504540BB9715CBE9DACB8B0A80BBBF@pa-mail1.legato.com> Hi, I am facing the following problem on HP. Background: I have a GUI (QT package) and I am running tasks in Threads. These threads spawn a process and read the output of the process and then display the O/P on the GUI. Now I can get a new process spawned by using a menu option. Now every alternate time the process hangs (spawned from the same gui): I.e. First process hangs. Second goes through fine. Third goes fine Fourth hangs. More on the problem: This is what happens, when I call os.fork() In the parent process I get the Pid of the child and the parent is fine. But in the child process (even before calling exec) my print statements work but anything os.XXX function call fails. I did a very simple stuff: before calling exec: Os.system("touch /tmp/m1") and this system call fails (for situations where the process hangs). NOTE: The hp system is: HP-UX 11.11 It has MSCS cluster installed on it. Python: 2.2.3 Has any body seen such a hanging of processes. Thanks -Ajay B -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed May 26 14:13:17 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 20:13:17 +0200 Subject: Transparent PNG and PIL References: <8a27e309.0405260724.5a9c1fdc@posting.google.com> Message-ID: R.Marquez wrote: > It would seem that using PIL would make this simmilarly simple, but so > far I have not found a simple clear explanation of how to do this. If > someone has figured this out could you post it for the benefit of > mankind. ;) if you have an 8-bit palette image (mode "P"), you can specify the transparency color (as a color index) when you save the image: im.save(filename, transparency=0) for RGB images, you can use the putalpha methods to add a transparency layer to the image (turning into a mode "RGBA" image). > Does it do this by in effect creating a proprietary PNG format? iirc, IE supports transparency masks for 8-bit palette images (mode "P"), but it does not support transparency with true color images ("RGBA"). unless you use IE-specific filters, that is: http://webfx.eae.net/dhtml/pngbehavior/pngbehavior.html From max at alcyone.com Thu May 20 21:36:44 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 May 2004 18:36:44 -0700 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> <545cb8c2.0405201645.16ac3364@posting.google.com> Message-ID: <40AD5D2C.E539EED9@alcyone.com> Jim Hefferon wrote: > Forgive me, Peter, but you've only rephrased my question: I'm going to > decode them later, so why does the concatenator insist on decoding > them now? Because you're mixing normal strings and Unicode strings. To do that, it needs to convert the normal strings to Unicode, and to do that it has to know what encoding you want. > As I understand it (perhaps this is my error), > encoding/decoding is stuff that you do external to manipulating the > arrays of characters. It's the process by which you turn an arbitrary string into a Unicode string and back. When you're adding normal strings and Unicode strings, you end up with a Unicode string, which means the normal strings have to be implicitly converted. That's why you're getting the error. Work with strings or Unicode strings, not a mixture, and you won't have this problem. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ She glanced at her watch ... It was 9:23. -- James Clavell From indigo at bitglue.com Thu May 27 16:36:16 2004 From: indigo at bitglue.com (Phil Frost) Date: Thu, 27 May 2004 16:36:16 -0400 Subject: CGI newb... redirect page In-Reply-To: References: Message-ID: <20040527203616.GA14313@unununium.org> To do a redirect, you can simply do something such as: print 'Location: http://new.absloute/url\r\n\r\n' print ''' This is some html that people will never see, but generally it should include a link to the target url''' sys.exit() Note that to be RFC compliant, you must give an absloute URL, although relative ones work usually. Furthermore, there is no reason you should have to write a script to do redirects for error pages. See the documentation on apache.org: http://httpd.apache.org/docs-2.0/mod/core.html#errordocument You can have apache use any local file, or even redirect to another server. On Thu, May 27, 2004 at 11:36:17AM -0700, Sean Berry wrote: > Hi there. I am relativly new to Python CGI and need a question answered. > > I have made custom 404 error pages and have them in various web directories. > > I have not been able to figure out a way to have apache use a file not > within it's own > home directory, so I was going to have a .py file in cgi-bin forward the > user on to the > correct error page. > > So I have say, > /usr/www/client1/not-found.shtml > and... > /usr/www/client2/not-found.shtml > > I found that cgi.print_environ() gave me the SERVER_NAME, which is what I > want. > But, this is part of a long html formatted string that cgi.print_environ() > returns. > > Is there something builtin to deal with these name, value pairs as a > dictionary? > I looked throught the docs, but did not see this functionality. > > Also, when I do extract this info... how do I actually do a redirect to a > certain page > > Example. > User goes to www.client1.com/page_not_on_server.html > The apache conf file sends the redirect to /cgi-bin/redirect.py > Redirect.py extracts the requesting server, client1.com, then > redirects them to www.client1.com/not-found.shtml. > > Thanks for your help. From me at privacy.net Wed May 12 04:40:54 2004 From: me at privacy.net (Duncan Booth) Date: 12 May 2004 08:40:54 GMT Subject: Ideas about optional filter on for loop statements References: Message-ID: bluczkie at andrew.cmu.edu (Brian L.) wrote in news:c186c44d.0405110926.5eead044 at posting.google.com: > for x in l if x is not None: > ... > > is certainly cleaner and easier to read. This clause should of course > be optional > > Thoughts? IMHO: for x in l: if x is not None: is cleaner and easier to read than forcing everything onto one line. In most cases the names or expressions would be longer (and hopefully meaningful), so you would want to split the 'for' and 'if' onto two separate lines anyway. Besides, these days you can write a generator trivially, so just put the condition inside a generator, invent a meaningful name for it and then you don't have to return None as a value at all. From richardjones at optushome.com.au Wed May 5 20:38:35 2004 From: richardjones at optushome.com.au (richard) Date: Thu, 06 May 2004 10:38:35 +1000 Subject: MySQL vrs SQLite References: Message-ID: <4099890c$0$32558$afc38c87@news.optusnet.com.au> Michael wrote: > I'm considering changing a Python program of mine, that uses MySQL as > it's db backend, to use SQLite. I'm mostly wanting something that can > make my program a complete package without requiring the user install > and configure an external db program. Has anyone experience with these? Yes, my project, the Roundup Issue Tracker (http://roundup.sf.net) has interfaces to both MySQL and SQLite (and postgresql, metakit, anydbm, ...) In short, sqlite is a *very* capable little database, as long as it only ever has one user. More than one user, and it'll block access so only one user may access it at a time. It scales very well - better than MySQL, and about equal with postgresql as far as I can tell. See: http://www.mechanicalcat.net/richard/log/Python/Roundup_benchmark_time_again for some comparative benchmarks. > They both follow the same DB-API so the code should be pretty easy to > port, right? In theory, yes. In practise, the DB-API layer simple can't hide the various little inconsistencies between databases (usually datatypes and incomplete SQL implementations). The Roundup code includes large "common" interface which covers 95% of its generic RDBMS interface, and then individual modules for each of the specific RDBMSes. Postgresql is the thinnest layer, then SQLite and then MySQL deviates the most from the common implementation. > Any draw backs to making this change? SQLite has some limitations on the SQL it implements. Then again, so does MySQL. The SQLite website has a concise page indicating the unimplement SQL features. ALTER TABLE is about the most annoying omission. On the other hand, MySQL doesn't support sub-selects, but sqlite does. SQLite treats all data as strings, but note that it does some internal "typecasting" such that a column of numbers will be sorted numerically. You will need to implement your own data conversion though. It's usually as trivial as a simple mapping containing conversion functions like (from the Roundup source): sql_to_hyperdb_value = { hyperdb.String : str, hyperdb.Date : lambda x: date.Date(str(x)), hyperdb.Link : str, hyperdb.Interval : date.Interval, hyperdb.Password : lambda x: password.Password(encrypted=x), hyperdb.Boolean : int, hyperdb.Number : rdbms_common._num_cvt, } Richard From satya at ttck.keio.ac.jp Wed May 5 11:50:04 2004 From: satya at ttck.keio.ac.jp (Satya Nanda Vel Arjunan) Date: 5 May 2004 08:50:04 -0700 Subject: py2exe excluding a module, and import it during runtime, how? Message-ID: <39d94318.0405050750.633872eb@posting.google.com> Hi, I think there must be a simple solution for this problem, but I couldn't find any example of this problem when I searched for it. I am using py2exe-0.5.0. I would like to make a simple script, test.py into an exe file, test.exe. In test.py I import a custom module called emc: import sys import os import emc def main(): aProgramName = os.path.basename( sys.argv[0] ) if __name__ == '__main__': main() I would like to exclude the emc module when creating the exe file. To do this I used the following setup.py: from distutils.core import setup import py2exe setup( windows=[ { "script": "test.py" } ], options={ 'py2exe': { 'excludes' : ['emc'] } } ) When I run the test.exe I get the following error: ImportError: No module named emc I have tried putting the module emc.py in the same directory as test.exe and but it could not load it. So far I have only been successful if I include emc.py inside the library.zip file, which I do not want to do. How do we import a module only during runtime if we exclude it when creating the exe file? I need this feature because some modules are not readily available during the creation of the exe file. Thank you for any pointers. satya From edvard+news at majakari.net Thu May 27 01:42:26 2004 From: edvard+news at majakari.net (Edvard Majakari) Date: Thu, 27 May 2004 08:42:26 +0300 Subject: Creating Python class wrapper for a command line tool References: <87aczvxuvr.fsf@titan.staselog.com> <874qq3jb38.fsf@titan.staselog.com> Message-ID: <871xl6xw71.fsf@titan.staselog.com> Peter Otten <__peter__ at web.de> writes: > You could test object identity instead. > >>>> def isbool(b): > ... return b is True or b is False Ah. Should have tried (I almost thought of that myself, but then I remembered 1 == True and thought it wouldn't work. But I forgot there's magic in Python ;) This works great with Python2.2. Thanks! -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From nemesis at nowhere.invalid Mon May 10 16:19:04 2004 From: nemesis at nowhere.invalid (Nemesis) Date: Mon, 10 May 2004 20:19:04 GMT Subject: [ANN] XPN 0.2.7 released Message-ID: XPN is an on-line newsreader with unicode support. It's written in Python using GTK+2 toolkit and works wherever Python and GTK+2 work. Changes in this release: * v0.2.7: added external editor support * v0.2.7: little change about rot13, now if there isn't selected text the whole article will be encoded/decoded. * v0.2.7: fixed a bug caused by articles with strange line-terminators. * v0.2.7: little change in connection handling. Now you can enter a group and read already read articles without having to estabilish a connection with server. * v0.2.7: fixed a bug in Import Newsrc. * v0.2.7: now the function that builds the threaded-view is much faster. You can find it on: http://sf.net/projects/xpn -- All those who believe in psychokinesis raise my hand. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From fperez528 at yahoo.com Sat May 15 00:31:44 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 14 May 2004 22:31:44 -0600 Subject: cmd Library Module trouble References: Message-ID: Juan Stang wrote: > Hope someone can help ... > > My Python sys.version prints out as follows: > '2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]' > > I'm also running Windows XP SP1 and I have installed PyGame 1.6, > wxWindows 2.5 and the latest Twisted dist. I only include these for > the sake of completeness. > > I'm trying to write something using the 'cmd' module, but I get the > error below when I run the source included at the end of this post. > It's pretty basic. This looks like a readline error, but the Python > documentation states that the cmd module should be OS independent, and > I'm not trying to use any readline features. Any ideas??? Please help! There's no native Windows readline with python. This means you have a third-party readline module somewhere. There's a readline out there (Chris ....? wrote it, can't remember the name) which is _very_ problematic: it does NOT expose the full readline API, so modules which try to import it succeed initially, only to later crash horribly because the thing is very incomplete. If you want readline support under windows, google('uncpythontools'), you'll find Gary Bishop's _excellent_ library, which adds proper ANSI color hanlding to the pathetic Windows terminal. Best, f From jfabiani at yolo.com Sun May 16 11:25:59 2004 From: jfabiani at yolo.com (john fabiani) Date: Sun, 16 May 2004 15:25:59 GMT Subject: Python for Large Projects In-Reply-To: References: <10ae406ck3q1gb1@corp.supernews.com> Message-ID: Peter Hansen wrote: > Ixokai wrote: > >> There is some concern that if we do this same >> thing with Python, the performance hit of loading an interpreted >> environment >> over the shared filesystem will be prohibitive. Some basic testing has >> made >> this seem to be the case. > > > Just focusing on this one point: it doesn't make sense to me that > this would be the case, and in my experience it is not. The > interpreter (python23.dll for example on Win32) is less than 1MB > and that's basically _tiny_ these days. We always had a single > shared instance of Python and never noticed more than a small > fraction of second delay compared to loading it locally. This > was a network with only about fifteen developers as users, and > 100MBps throughout, but I would think almost any program these > days is going to be 1MB or more, so I can't see that Python has > any disadvantage in this area. > > -Peter I'm a newbie so take what I say with a grain of salt! In the VFP (visual foxpro) world the runtime environment is loaded on the local computer (client) and the program is often loaded on to the server. I'm wondering if there would be any advanage to placing the python runtime on the clients along with the standard modules. Then placing the program code on to a server where all the clients/users would access the code. It would seem that the advanage would be that program load time would about the same but the excutions would be faster because of the local runtime. Can this even been done? Would it be faster? John From joewong at mango.cc Fri May 21 03:12:01 2004 From: joewong at mango.cc (Joe Wong) Date: Fri, 21 May 2004 15:12:01 +0800 Subject: how to terminate a process? Message-ID: <01fe01c43f02$ea28bf80$7f00a8c0@scl01.siliconcreation.com> Hi, I am developing two app on Windows, one is a GUI using wxPython and the other is like a daemon process. The GUI app will have a start/stop button to control the excution of the daemon. While I know how to use os.popen2() to start my daemon, I can't figure out a way to stop it 'nicely'... Is there anything that I can do? Regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From jepler at unpythonic.net Tue May 18 12:37:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 18 May 2004 11:37:49 -0500 Subject: how to keep one instance??? In-Reply-To: <200405181452.51644.heikowu@ceosg.de> References: <200405180732.i4I7WGb19062@bald.unpythonic.net> <20040518124627.GH14843@unpythonic.net> <200405181452.51644.heikowu@ceosg.de> Message-ID: <20040518163749.GK14843@unpythonic.net> On Tue, May 18, 2004 at 02:52:51PM +0200, Heiko Wundram wrote: > Am Dienstag, 18. Mai 2004 14:46 schrieb Jeff Epler: > > Note that there are often race conditions here---if two copies of the > > application start nearly simultaneously, both may detect that no > > other copy of the app exists. If someone wants to tell me the way to > > get this right in the context of Unix/X11, please speak up! > > Lock files in /tmp? Simply do file-based locking the daemon PID-file style... > If you need code (which is race-free) to handle this, mail me, and I'll > gladly send it to you. X presents some different challenges from making sure only one instance of a daemon is running. It mostly boils down to this: I should be able to run one instance of an application *per display*, not per machine, per user, or per home directory. Take openoffice for instance. Right now, I have an instance of openoffice running in a vnc session displaying a spreadsheet (DISPLAY=:1). If I run "DISPLAY=:0 oowrite", I'll be very surprised to see that a new window has actually been opened in the vnc session, not on the display I asked for. But "one instance of an application *per display*" is not quite right either. Metadata (bookmarks) and data (documents) exist on filesystems. So I should also be able to run one copy of oowrite on a machine with home directory A, and one copy with home directory B. So maybe the right thing is "one instance of an application per (display, home-directory) pair"? That leaves determining the canonical name for a particular display, I guess, then using a normal lockfile approach... Jeff From johnathan_doe at fastmail.com.au Mon May 24 03:53:18 2004 From: johnathan_doe at fastmail.com.au (Johnathan Doe) Date: Mon, 24 May 2004 17:53:18 +1000 Subject: Issues in compiling Python to machine code In-Reply-To: References: <40b089a5$0$16599$5a62ac22@freenews.iinet.net.au> Message-ID: <40b1a9e8$0$16606$5a62ac22@freenews.iinet.net.au> Thanks for all the links! Obviously I've just shown myself to think out loud, and not to think very much at all before doing the "out loud" part... :) I'll take a look through all these. Incidentally, this doesn't have anything to do with speeding up Python. It's already fast enough for what I want. My main issue is writing low level code in Python. It's possible to do great things like autodetect hardware in Python for an OS, e.g. Anaconda/Kudzu, but why not be able to write an OS completely in Python? I am sure it's possible somehow. Just not sure yet :) Possibly, GRUB can load the startup code, which contains an embedded Python interpeter. Then the interpreter defines the kernel_main function and takes over. I'd need some way of gluing up all the low level stuff to the interpreted Python "platform" : interrupts and page faults and whatnot. Anyway, I should talk about this on alt.os.development :) Johnathan From gh at ghaering.de Thu May 6 06:06:25 2004 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 06 May 2004 12:06:25 +0200 Subject: MySQL vrs SQLite In-Reply-To: References: Message-ID: <2fugskF2cbjnU1@uni-berlin.de> Michel Claveau/Hamster wrote: >>>>doesn't SQLite store its data in memory? > > No ! It's the database-engine who is in embeddable. The data are stored in > one file per database. You *can* also store the data in memory by specifiying :memory:, i. e.: cx = sqlite.connect(":memory:") -- Gerhard From hei123 at gamebox.net Tue May 18 20:37:52 2004 From: hei123 at gamebox.net (Adal Chiriliuc) Date: Wed, 19 May 2004 03:37:52 +0300 Subject: MFC application and Python Message-ID: <2410357897.20040519033752@smtp.myrealbox.com> Hi. I'm working on a C++ Win32 MFC application and I want to move as much code as possible to Python. At first I wanted to use a Python GUI package and keep the critical components (performance wise) in C++ extensions. The application must have a native look so this leaves us with only two choices. wxPython is way too bloated (9 MB on disk, 20MB! in memory for basic stuff) and people say buggy. PythonWin is nice and small, but lacks some features, like GDI support. So this gave me the idea of doing it the other way around: having a skeleton application which handles Win32 messages and the application threads and this will call into Python for the logic, which will call back into C++ for the critical operations and GUI updates. Since I'm new to Python, can you see any problems with this approach? Is there a better way to do it? A specific question: is it ok if C++ calls into Python which calls into C++ which calls again into Python and so on let's say 5 levels deep as reaction to a Win32 message or a thread unblocking? And another one: What are the ways to call into Python? I know of PyRun_, PyObject_Call and boost::python::call. Regards, Adal Chiriliuc From rogerb at rogerbinns.com Mon May 24 19:40:16 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 24 May 2004 16:40:16 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: > Choosing an internal encoding is actually pretty tricky because there > are space versus time tradeoffs and you need to make some guesses about > how often particular characters are likely to be useful to your users. There are two ways to deal with it. One is to convert to an internal "UNICODE" format such as utf8, or using arrays of 16 or 32 bit integers. You also have to decide if you are going to normalise the string. For example you can have characters followed by a combining accent. On display they are one character, but often there is a codepoint for the single character combined with the accent, so you could reduce the two down to one. There are also other characters such as those that specify the direction of the following text which are considered noise in some contexts. The other way of dealing with things is to keep the text as it was given, and not do any conversion or normalisation on it. This is generally more future proof, but does burden other code with having to deal with conversion issues (for example NT/2K/XP only uses 16 bits for codepoints which is less than the full range now). If you want to score extra bonus points, you should also store the locale of the string along with the encoding. I won't elaborate here why. Another design to consider is to allow tags that cover character ranges and then assign properties to those tags (such as locale, encoding), but importantly allow multiple tags per character. (If you have used the Tk text widget you'll understand what I am thinking of). > By the way, if you have the courage to distance yourself from every > other language under the sun, I would propose that you throw an > exception on unknown escape sequences. Perl did that first :-) It didn't distinguish between arrays of bytes and arrays of characters so you easily end up with humunguous amounts of warnings about invalid UTF8 stuff when dealing with bytes. (I have no idea what goes on under the hood - you just see it when installing Perl stuff like SpamAssassin). In addition to all the excellent notes from Paul, I would recommend you consult with someone familiar with the locale and encoding issues for Hebrew, Arabic and various oriental languages such as Japanese, Korean, Vietnamese and Tibetan. Bonus points for Tamil :-) Just to make life even more interesting, you should realise that there is more than one system of digits. You can see how Java handles the issue here: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/font/NumericShaper.html Since you are doing new language design, I also think there would be great value in forcing things so that you do not have strings embedded in the program, and they have to come from external resource files. This also gives you the opportunity to deal with string interpolation issues and get them right. (It also means that "Hello, World" remains one line, but also requires an external file with the message, or some other mechanism). The other Java i18n pages make for interesting reading: http://java.sun.com/j2se/corejava/intl/index.jsp Roger From cookedm+news at physics.mcmaster.ca Mon May 17 15:12:40 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 17 May 2004 15:12:40 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 References: <40A54424.808544D1@alcyone.com> Message-ID: At some point, Erik Max Francis wrote: > "Laughlin, Joseph V" wrote: > >> I would avoid installing applications that way, if only for the fact >> that you can't uninstall an application. > > How can you not install an application installed that way? > > rm -f $PREFIX/bin/python* $PREFIX/bin/pydoc $PREFIX/lib/python* and now you've removed all your pythons... You also have to remember which files it installed (Python isn't too bad, but others are worse). I like stow (http://www.gnu.org/software/stow/stow.html). I can install into $PREFIX/stow/python-2.3.4, then run stow in $PREFIX/stow. It then makes appropiate symlinks. Uninstalling is as simple as 'stow -D python-2.3.4' in $PREFIX/stow. It's written in Perl; I've had some thought to making Python version :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From greg at invalid.invalid Tue May 18 17:43:06 2004 From: greg at invalid.invalid (Greg Krohn) Date: Tue, 18 May 2004 21:43:06 GMT Subject: Making items visible in wxPython wxListCtrl In-Reply-To: <39cbe663.0405181208.1065933d@posting.google.com> References: <39cbe663.0405181208.1065933d@posting.google.com> Message-ID: Piet wrote: > Hi there. > I am trying to display tabular data in a wxListCtrl. What I get from > ... I hope this clears it up. from wxPython.wx import * class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,-1, title, style=wxDEFAULT_FRAME_STYLE) self.panel = wxPanel(self,-1) self.Lctrl = wxListCtrl(self.panel,-1, size=(200,200),style =wxLC_REPORT) # for i in range(2): # self.Lctrl.InsertColumn(i, "Column"+str(i), # format=wxLIST_FORMAT_LEFT,width=100) # self.Lctrl.SetStringItem(i,1,"Hi") # self.Lctrl.SetStringItem(i,2,"there") # self.Lctrl.SetItemData(i,1) self.Lctrl.InsertColumn(0, "Name") self.Lctrl.InsertColumn(1, "ID") self.Lctrl.InsertColumn(2, "Spam Level") people = [["George", "3t4d3", "5"], ["Beth", "34g245", "3"], ["Zaphod", "424242", "42"]] # Notice you use InsertStringItem for the first item # in the row and then use SetStringItem for the rest for index, (name, id, spam) in enumerate(people): self.Lctrl.InsertStringItem(index, name) self.Lctrl.SetStringItem(index, 1, id) self.Lctrl.SetStringItem(index, 2, spam) app = wxPySimpleApp() frame = MainWindow(None, -1, "List Control Test") frame.Show(1) app.MainLoop() > Best regards > > Peter Ditto, greg From lbates at swamisoft.com Wed May 5 20:32:00 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 5 May 2004 19:32:00 -0500 Subject: Newbie question about list method remove References: Message-ID: In Python you must think "differently" than in other programming languages. li2=[f for f in li2 if not f.endswith('.txt')] for your specific example or in Python 2.2 and earlier li2=[f for f in li2 if f.count('.txt') == 0] for the more general .txt ANYWHERE in the string or in Python 2.3 li2=[f for f in li2 if not '.txt' in f] Larry Bates Syscon, Inc. "Sean Berry" wrote in message news:myemc.69648$Jy3.5301 at fed1read03... > Why is this: > > >>> li2 =['this.txt', 'that.txt', 'April04', 'more.txt'] > >>> for item in li2: > if ".txt" in item: > li2.remove("%s" %item) > >>> li2 > ['that.txt', 'April04'] > > I would think that 'that.txt' would be removed as well. Where am I wrong? > > TIA > > From elainejackson7355 at home.com Fri May 14 21:04:40 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sat, 15 May 2004 01:04:40 GMT Subject: looping over the files in a directory References: Message-ID: Works like a charm. Thanks for the tip. "Mark J. Nenadov" wrote in message news:pan.2004.05.14.16.17.33.273871 at freelance-developer.com... | On Fri, 14 May 2004 15:32:32 +0000, Elaine Jackson wrote: | | > Can anyone please tell me the actual syntax for saying something like this: | > | > for in : | > | | A simple example: | | import os | | path = '/home/bob/' | | for f in os.listdir(path): | print f | | -- | Mark J. Nenadov | Python Byte Solutions | http://www.pythonbyte.com/ From roy at panix.com Tue May 25 21:12:13 2004 From: roy at panix.com (Roy Smith) Date: Tue, 25 May 2004 21:12:13 -0400 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: In article <40B3E861.29B033D5 at shaw.ca>, SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since a > strength of Python is rapid application development, it slows one down > to have to put in all those self.'s. The code seems much cleaner to me > without classes that have only one instance. Oh, also, all the methods > of this class will have to have the instance name prepended to them. > > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. > > Mitchell Timin Typing "self" is a mechanical process which adds very little to the development cost. Deciding which things to make classes and which not to requires significant mental effort and does add cost. It's just easier to make everything a class. More than that, most times I've decided to not bother making something a class because it was too simple, I've eventually added enough functionality to it to change my mind and have to re-do things. That's real cost. Much simplier and cheaper to just make it a class from the get-go. From benn at cenix-bioscience.com Wed May 12 11:55:47 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 12 May 2004 17:55:47 +0200 Subject: Real-time graphs In-Reply-To: <20040512152247.68328.qmail@web40001.mail.yahoo.com> References: <20040512152247.68328.qmail@web40001.mail.yahoo.com> Message-ID: <40A24903.8050607@cenix-bioscience.com> Hello, If you can use Jython then there is a fantastic java package called JFreeChart (it's open source) which can do real time graphs. It's on sourceforge. Cheers, neil snrkiwi-lists at yahoo.com wrote: >I've trolled the lists, FAQs, and Net as a whole, but >can't find anything definitive to answer this. > >We're looking for real-time graph capability (bar, >line, etc), so that we can display telemetry from a >robot system. There are a bunch of packages out >there, but many seem to provide only static graphs >(e.g. for scientific, financial data, etc). Does >anyone currently display real-time telemetry using >Python? Can anyone provide any suggestions? > >TIA >Stephen > > > -- Neil Benn Senior Automation Engineer Cenix BioScience PfotenhauerStrasse 108 D-01307 Dresden Germany Tel : +49 (351) 210 1300 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From vincent at visualtrans.de Sat May 1 02:22:25 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 01 May 2004 08:22:25 +0200 Subject: Help with C API In-Reply-To: References: Message-ID: Nick Jacobson wrote: ... > I'd like to do the reverse: take an C array (say, with 100 elements) > and copy its elements into a Python list. But I don't know where to > start...there's no PySequence_Fast_INSERT or even PySequence_Insert > function, for example. Can I create an empty list in the API or > should I just pass one in from Python? > > Can someone please help with this? Thanks in advance!! > > --Nick http://docs.python.org/api/listObjects.html is probably a good start Regards, Vincent Wehren From mwh at python.net Wed May 19 05:52:29 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 19 May 2004 09:52:29 GMT Subject: Python compilers? References: Message-ID: Svein Ove Aas writes: > What you're claiming, though, is that it's possible to write Python code > that can't easily be translated to equivalent Lisp code. Can you give an > example? class C: def __eq__(self, other): return True for example. For better or worse, Python *is* more dynamic than Common Lisp, and this *does* contribute to making it harder to make Python go fast. I wrote a rant about this subject: http://starship.python.net/crew/mwh/hacks/speeding-python.html Cheers, mwh -- Ability to type on a computer terminal is no guarantee of sanity, intelligence, or common sense. -- Gene Spafford's Axiom #2 of Usenet From pit.grinja at gmx.de Mon May 31 07:41:11 2004 From: pit.grinja at gmx.de (Piet) Date: 31 May 2004 04:41:11 -0700 Subject: Regexp: unexspected splitting of string in several groups Message-ID: <39cbe663.0405310341.430d2035@posting.google.com> Hello, I have a very strange problem with regular expressions. The problem consists of analyzing the properties of columns of a MySQL database. When I request the column type, I get back a string with the following composition: vartype(width[,decimals]|list) further variable attributes. vartype is a simple string(varchar, tinyint ...) which might be followed by a string in curved brackets. This bracketed string is either composed of a single number, two numbers separated by a comma, or a list of strings separated by a comma. After the bracketed string, there might be a list of further strings (separated by blanks) describing some more properties of the column. Typical examples are: char(30) binary int(10) zerofill float(3,2)... I would like to extract the vartype, the bracketed string and the further properties separately and thus defined the following regular expression: #snip vartypePattern = re.compile("([a-zA-Z]+)(\(.*\))*([^(].*[^)])") vartypeSplit = vartypePattern.match("float(3,2) not null") #snip That works for some expressions with a bracketed expression. E.g. the above expression gives back: vartypeSplit.groups() = ('float', '(30,2)', ' not null'). However, simple one-string expressions like vartypeSplit = vartypePattern.match("float") are always splitted into two strings. The result is: vartypeSplit.groups() = ('flo', None, 'at'). I would have either expected ('float',None,None) or ('float','',''). For other strings, the last two characters are also found in a separate group. Is this a bug or a feature? ;-) Can anybody point me in the right direction to solve the problem. Many thanks Piet From eriksp at attbi.nospam.com Sat May 15 09:44:58 2004 From: eriksp at attbi.nospam.com (EAS) Date: Sat, 15 May 2004 13:44:58 GMT Subject: Guess My Number Game Message-ID: Hey, I'm new to python (and programming in general) so I'll prolly be around here a lot... Anyways, I've found out how to make a "guess my number game" where the player guesses a number between 1 and 100, but I want to switch things around. I want to be able to put in my own number and have the computer guess it. I already know how to make it guess (by using randrange) but I'm having a hard time making it smarter. (Like guessing higher or lower based on what it's told it needs to do.) Here's the code I have right now: __________________________________________________________ import random guess = 0 tries = 0 number = input("Pick a number between 1 and 100 for the computer to guess: ") while number > 100 or number < 1: number = input("Pick a number between 1 and 100 for the computer to guess: ") while guess != number: guess = random.randrange(101) print "The computer guessed", guess tries += 1 past = guess while guess < number: guess = random.randrange(guess, 101) print "The computer guessed", guess tries += 1 while guess > number: guess = random.randrange(0, guess) print "The computer guessed", guess tries += 1 print "The computer guessed your number after", tries, "tries." raw_input("Press enter to exit.") ____________________________________________________________ As you can see, I've already made it a little smarter but I think I could still mae it better. Any ideas? Also, does anyone know a really popular python forum? From user at example.net Tue May 25 13:58:30 2004 From: user at example.net (Bertrand B) Date: Tue, 25 May 2004 19:58:30 +0200 Subject: w9xpopen.exe and Drive A: In-Reply-To: References: Message-ID: Found ! w9xpopen do something tricky (i think it use dos mode) that interact with MacAfee. If i stop virscan it's ok. Funny is n't it ? Bertrand B a ?crit : > lo' > > When i use os.popen on my W98SE I can hear my drive A: working. Sby know > what ? > > (I've not A: in PATH all my os.environ seems clean and if one w9xpopen > is running the second don't give me the same problem) > > Thank for help. From pxlpluker at cfl.rr.com Mon May 10 17:41:36 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Mon, 10 May 2004 17:41:36 -0400 Subject: How do you register cleanup code to be run after script execution? In-Reply-To: References: <20040508090936.21319.00000994@mb-m04.aol.com> Message-ID: <409FF710.8050908@cfl.rr.com> why not use try: code finally: cleanup code Peter Otten wrote: >use dmgass at hotmail dot com wrote: > > > >>I'm writing a module and when it is imported by a script I want some code >>automatically executed when the importing script is finished executing. >>I'd like it to execute before interactive mode is entered when executing >>the >>importing script from the command line. I don't want to have to impose >>that the importing script must call a function at it's end. >> >> > >I think you want atexit.register(): > > >print "in main" >import imported >raw_input("type enter to finish") > > > >import atexit > >def exitFunc(*args): > print "exitFunc callled with", args > >atexit.register(exitFunc, "with", "args") > >print "imported 'imported'" > > >$ python importing.py >in main >imported 'imported' >type enter to finish >exitFunc callled with ('with', 'args') >$ > >Peter > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From haim at babysnakes.org Thu May 6 11:42:20 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Thu, 06 May 2004 18:42:20 +0300 Subject: GUI toolkits, bidi, and i18n question Message-ID: Hi I'm writting an application that runs on windows (win2k and win98) and should have (amongst other things): 1. systray icon with menu 2. translation to hebrew (which is written right to left). since I have no experience on windows (as a user or as a developer) I thought that wxpython would be a good choice, but then I've read in some forum that it doesn't have good support for bidi. my second choice would be GTK, but it has a problem with file/directory dialogs which I think would confuse windows users, and no support for systray icon. so I thought of using GTK and taking the missing widgets from win32all (which I'm importing anyway), but the documentation is very poor and I couldn't even find an example of systray icon. my third option would be to use GTK and taking the missing widgets from wxpython, which I'll use if I have no better option. QT is not an option because it's not free for windows, and I just don't like TK. does anyone has an idea about which toolkit to use? thanx -- Haim From miki.tebeka at zoran.com Tue May 11 03:26:36 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 May 2004 09:26:36 +0200 Subject: Class update detection In-Reply-To: <109vn4b8bhe98f4@corp.supernews.com> References: <109vn4b8bhe98f4@corp.supernews.com> Message-ID: <40A0802C.5090506@zoran.com> Hello Steven, > I need to determine if > any of the class attributes have been changed to I can issue an update > query to the database with the changes. Is there a generally accepted > method to do this? Is there some way to create a checksum of the class > attributes? Do you mean something in the lines of: class C: def __init__(self, a, b): self.a, self.b = a, b self.dirty = 0 def __setattr__(self, k, v): if k in ("a", "b"): self.dirty = 1 self.__dict__[k] = v >> c = C(1,2) >>> c.dirty 0 >>> c.a = 10 >>> c.a 10 >>> c.dirty 1 >>> Another option is to generate a checksum (using md5 and str) on all the attributes you're interested in at the end of __init__ and a function `dirty' will compute this checksum and return 1 if it was changed. Note that if you have nested objects this might be a problem. HTH. Miki From asdf at asdf.com Sat May 1 00:04:44 2004 From: asdf at asdf.com (asdf sdf) Date: Sat, 01 May 2004 04:04:44 GMT Subject: calling functions at the same time In-Reply-To: References: Message-ID: sigh. i just read what you want to do. my answer was so cool too. you are doing network diagnostics. it is unlikely that a non-network guy (you) can cobble together a few lines of script and develop much in the way of detailed diagnostics. much better to find someone who already knows networking and use the great many highly sophisticated tools that are already available (and free). good luck From adalke at mindspring.com Thu May 13 02:12:27 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 13 May 2004 06:12:27 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> <8gisf1ihvc.fsf@galapagos.bx.psu.edu> Message-ID: Scott Schwartz: > 1) Python throws an error if you have less than three fields, > requiring more typing to get the same effect. The spec didn't say how to handle improperly formatted data. Suppose the code is supposed to complain and stop at that point - how much code would you need for awk to do the extra check? > 2) Python generators on stdin behave strangely. For one thing, > they're not properly line buffered, so you don't get any lines until > eof. But then, eof is handled wrongly, and the loop doesn't exit. There's a command-line flag to make stdin/stdout be unbuffered. Try your test again with 'python -u'. > 3) There is no efficient RS equivalent, in case you need to read > paragraphs. Again, not part of the spec. ;) Andrew dalke at dalkescientific.com From cliechti at gmx.net Sun May 9 09:24:27 2004 From: cliechti at gmx.net (Chris Liechti) Date: Sun, 9 May 2004 13:24:27 +0000 (UTC) Subject: Embed+extend+port References: Message-ID: Vio wrote in news:mailman.370.1084093847.25742.python-list at python.org: > My story: I played with a little embedded python > piece of code (python interpreter embedded in wxWidgets app), > and used SWIG to extend this embedded py interpreter. > I did it in Linux, after some ironing all builds and runs as expected. why someone would embedd a python interpreter but write the gui code some some other language escapes me, but well ;-) > On a particularily lazy day, I pasted these same wrapper sources to > Win32 (cygnus). After fiddling with the Makefile to point in the right > directions, compilation seems to go ok (give or take a couple of > warnings). But then the linking step chokes with unfriendly messages > like "undefined reference to _PyExit, _Py_Initialize, etc.". > > Could someone tell me what this mean? My guess is that my linker is not > pointed at the right Python library, right. you need to create an import lib for gcc. thats done with pexports and dlltool: http://docs.python.org/inst/tweak-flags.html#SECTION000622000000000000000 also remember to use -mno-cygwin for gcc if you want to make native win32 apps with cygwin. > PS I just read on the list some comments that wxWidgets+Python mix is > kinda slow. Bummer. is it too slow for _you_? there are always people that say something is slow, even if it isn't relevant in real world applications... chris -- Chris From me at privacy.net Thu May 20 06:44:38 2004 From: me at privacy.net (Duncan Booth) Date: 20 May 2004 10:44:38 GMT Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> <5155aad2.0405200230.1899e3be@posting.google.com> Message-ID: kveretennicov at yahoo.com (Konstantin Veretennicov) wrote in news:5155aad2.0405200230.1899e3be at posting.google.com: > Carl Banks wrote in message > news:<38Yqc.166$eO6.128 at fe2.columbus.rr.com>... > >> > There's more like it, e.g. the existence of the >> > locals() dictionary and the ability to modify it. >> >> New feature? I didn't think modifying the dict returned by locals >> affected the variables. >> > > Evidence of crime :) > > Python 2.3.2 >>>> x > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined >>>> locals()['x'] = 1 >>>> x > 1 > > That works because you are using locals() to access your global variables. Put the same code in a function and it behaves differently: >>> def test(): ... x = 0 ... locals()['x'] = 1 ... print x ... >>> test() 0 You cannot depend on the behaviour of modifying locals() remaining unchanged over different releases of Python. Bottom line: don't do this. From carlca at dircon.co.uk Mon May 10 15:51:06 2004 From: carlca at dircon.co.uk (Carl Caulkett) Date: Mon, 10 May 2004 20:51:06 +0100 Subject: Arachno Python IDE References: Message-ID: <1084218666.15877.0@nnrp-t71-02.news.uk.clara.net> Bror Johansson wrote: > > Follow up to myself. > I just noticed that the trial version was for Ruby only. It says that the Python version is coming out on 23rd May 2004. -- Carl From moma at example.net Sat May 15 14:23:51 2004 From: moma at example.net (moma) Date: Sat, 15 May 2004 20:23:51 +0200 Subject: Input Types In-Reply-To: References: Message-ID: Jeff Epler wrote: > Here's a function that can do the job. > > def typed_input(prompt="", convert=int, catch=ValueError, > eprompt="Invalid input."): > while 1: > s = raw_input(prompt) > try: > return convert(s) > except catch: > print eprompt > You can send functions (int, float) and exceptions as parameters? Amazing. > Usage: >>>>typed_input("Enter an integer: ") > > Enter an integer: asdf > Invalid input > Enter an integer: 3 > 3 > >>>>typed_input("Enter a number: ", float) > > Enter a number: > Invalid input > Enter a number: 3.14 > 3.1400000000000001 > > How does it work? > > 1. The "while 1" loop is repeated until the "return" statement is > successfully executed. > > 2. int(s) and float(s) convert a string argument s to the specified > type, or raise the ValueError exception > > 3. When there is a ValueError exception, the "error prompt" is printed, > and the while loop returns to the top to try again. > > You can also write your own "convert" function to restrict values to a > range, etc: > > >>>>def int_0_100(s): > > ... i = int(s) > ... if i < 0 or i > 100: > ... raise ValueError # out of range > ... return i > ... > >>>>typed_input("Enter a number from 0 to 100: ", int_0_100) > > Enter a number from 0 to 100: asdf > Invalid input. > Enter a number from 0 to 100: 101 > Invalid input. > Enter a number from 0 to 100: 37 > 37 > > You can also specify the catch= or eprompt= arguments to change the > exception that is caught or the error prompt string. > > Jeff > From josh at mri.com.au Wed May 19 21:40:20 2004 From: josh at mri.com.au (Joshua Burvill) Date: Thu, 20 May 2004 11:40:20 +1000 Subject: Sending file to print server using ftplib Message-ID: <000d01c43e0b$6a4bc750$f002a8c0@sydney.mri.com.au> Hello, I am trying to print something to a print server using the following function but I get errors, does anyone have any pointers? Rgds, Josh Traceback (most recent call last): File "", line 1, in ? mk_zeb_label() File "\\mrisydney\ZopeBBAp\Extensions\mk_zeb_label.py", line 38, in mk_zeb_label val=ftp.storlines("STOR " + portname, file_handle) File "C:\Python21\lib\ftplib.py", line 382, in storlines conn = self.transfercmd(cmd) File "C:\Python21\lib\ftplib.py", line 296, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "C:\Python21\lib\ftplib.py", line 273, in ntransfercmd host, port = parse227(self.sendcmd('PASV')) File "C:\Python21\lib\ftplib.py", line 229, in sendcmd return self.getresp() File "C:\Python21\lib\ftplib.py", line 202, in getresp raise error_perm, resp error_perm: 501 command not supported. ######################## ## SCRIPT STARTS HERE ## ######################## def mk_zeb_label(): from ftplib import FTP import string, cStringIO ## Create file-handle to a "file-like" string file_handle=cStringIO.StringIO() printserver_ip="192.168.2.15" portname="COM1" zpt_code=""" ^XA ^cfd,36,20 ^by3,,50 ^fo470,50 ^abn,48,30^fdREPAIR^fs ^fo50,150 ^fdSome text goes here.^fs ^fdSome text goes here.^fs ^fdSome text goes here.^fs ^fo50,50 ^bc^fd114567^fs ^XZ """ file_handle.write(zpt_code) ftp=FTP(printserver_ip) ftp.login("","") val=ftp.storlines("STOR " + portname, file_handle) return val From goodger at python.org Sun May 2 08:18:20 2004 From: goodger at python.org (David Goodger) Date: Sun, 02 May 2004 08:18:20 -0400 Subject: Help with ConfigParser In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I'm having a bit of trouble getting my head around the ConfigParser module. > I have a very simple configuration file; maybe the easiest thing to do > would be to show that: > > ============ > # Add a local directory to be backed up followed > # by the directory name on the FTP server. > # > # Example: /home/joe/digital photos = photos > > [Backups] > /home/stephen/photos/digital camera = photos > /home/stephen/documents/tax documents = taxes > ============ > > I just want to retrieve the information in the backups section. Thanks. What are you looking up, and what's the invariant (what's the lookup key)? I'd write the config file like this: [Backups] photos = /home/stephen/photos/digital camera taxes = /home/stephen/documents/tax documents Lookup keys are on the left, and configuration data is on the right. From your example though, it looks like you don't have specific lookup keys. You're just storing an arbitrary set of paired data. You could use an "items('Backups')" method call to get a list of (key, value) pairs which you could iterate over. -- David Goodger From michele.simionato at poste.it Sat May 15 00:53:03 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 14 May 2004 21:53:03 -0700 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> Message-ID: <95aa1afa.0405142053.76ae0818@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Regarding applications; restartable exceptions, micro-threads, > long-running-calculation restarts, migrating running code across > machines, and creating new methods of parsing all seem like experiments > that would benefit from having continuations available to ease > implementation. Any of those is a thing that an app programmer might > want/need, and be willing to have a meta-programmer create for them... > why force that work into C code needlessly? Ok, I see your point, so let me restate my doubts in this form: are you sure that you need to go to such a low level as continuations? Wouldn't generators/coroutines be enough to fullfill your needs? --- On a different note, I could notice that giving so much power to metaprogrammers may have unfortunate results. For instance, we already have three different kind of interfaces in three different frameworks (Zope, Twisted, Peak) whereas there should be only one obvious way. So, I mantain that certain things should be left to the language designer (i.e. Guido) and not to the metaprogrammer. Otherwise you ends up as in Scheme, where essentially everyone can be the designer of his own little language, with the disadvantages that you can see. I think metaprogrammers should be more humble, and think ten times before using metaprogramming features to change the language. But sometime the temptation is irrestible ;) Michele Simionato From fredrik at pythonware.com Wed May 26 17:02:08 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 23:02:08 +0200 Subject: Two questions about efficiency References: Message-ID: "Steve M" wrote: > 2. Is there any reason to prefer one of the following over the other? > Im interested in both a consensus on style and readability, and > considerations of efficiency at runtime. > > for x in L: > if f(x): > pass > > for x in L: > if f(x): > continue did you really mean to write that? as written, both constructs are pointless, and the "if f(x)"-statement can be replaced with just "f(x)" in both cases. and if you add more code inside the if statement, or after it, the constructs do different things. did you perhaps mean: for x in L: if f(x): do stuff for x in L: if not f(x): continue do stuff if so, my rule of thumb is to use alternative 1 if "stuff" is short, and alter- native 2 if "stuff" is long, or if you have multiple tests before you get to the real stuff. ymmv, as usual. and yes, if "stuff" is trivial, and builds a new list, consider using a list comprehension: L2 = [stuff for x in L if f(x)] From http Wed May 5 14:51:37 2004 From: http (Paul Rubin) Date: 05 May 2004 11:51:37 -0700 Subject: Zero-fill shift References: Message-ID: <7xekpyg11i.fsf@ruckus.brouhaha.com> Daniel Orner writes: > while(n-- > 0) > { sum += delta; > y += (z << 4)+a ^ z + sum ^ (z >>> 5) + b; > z += (y << 4)+c ^ y + sum ^ (y >>> 5) + d; > } That's Wheeler and Needham's Tiny Encryption Algorithm (TEA). You can just AND the intermediate results with 0xffffffff as needed, but unless you're trying to interoperate with some other program that uses that algorithm, you're better off using a different algorithm. There's plenty to choose from that are already implemented in Python or as Python extensions. From NOmanlio_perilloSPAM at libero.it Sat May 29 02:33:57 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 29 May 2004 06:33:57 GMT Subject: missing types in module types? Message-ID: <3s8gb01cu0sngo16282v7l1eddqudgoemt@4ax.com> Hi. I have found that some types are missing from module types: import types from types import * def check_type(obj): type_list = [eval(t) for t in dir(types) if t.endswith('Type')] return [[x, type(obj)] for x in type_list if isinstance(obj, x)] def fun(): pass cm = classmethod(fun) sm = staticmethod(fun) p = property() print check_type(cm) [[, ]] print check_type(sm) [[, ]] print check_type(fun.__init__) [[, ]] print check_type(p) [[, ]] Regards Manlio Perillo From phil at riverbankcomputing.co.uk Wed May 26 06:32:04 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 26 May 2004 11:32:04 +0100 Subject: ANN: PyQt v3.12 (Python Bindings for Qt) Released Message-ID: <200405261132.04955.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v3.12 available from http://www.riverbankcomputing.co.uk/. Changes since the last release include support for Qt v3.3.2, and the provision of an evaluation version for Windows to be used with the evaluation version of Qt. Support for the non-commercial version of Qt v2.3.0 for Windows has been reinstated. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt. Like Qt, PyQt is available under the GPL (for UNIX, Linux and MacOS/X), a commercial license (for Windows, UNIX, Linux and MacOS/X) and a free educational license (for Windows). PyQt is implemented as a set of 9 extension modules containing 300 classes and over 5,750 functions and methods. PyQt also includes bindings to QScintilla, the port to Qt of the Scintilla editor component. PyQt can be used either as a rapid prototyping tool, or as an alternative to C++ for developing large Qt applications. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. Third party tools are also available - such as eric3, a comprehensive IDE (including an editor, debugger, class browser, integration with Qt Designer, re-factoring tools, unit testing tools and integration with source code control systems). eric3 is written entirely using PyQt and is available from http://www.die-offenbachs.de/detlev/eric3.html. From fgeiger at datec.at Tue May 18 12:00:54 2004 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 18 May 2004 18:00:54 +0200 Subject: OPC Server in Python References: Message-ID: "David Fraser" schrieb im Newsbeitrag news:c8a59n$7s5$1 at ctb-nnrp2.saix.net... > I would recommend looking at Lab43's LightOPC which is a C > implementation of OPC code available under LGPL, you can use it as > examples... Start with a simple server, look at the OPC > groups/items/browsing later... I've already encountered LightOPC. Now, as its recommended here, I'll have a look into it. Thanks! > Would be good to hear how you progress... I'll keep this group informed, but it certainly will take its time until then... Many thanks and kind regards Franz GEIGER From bucket79 at daum.net Fri May 14 05:40:00 2004 From: bucket79 at daum.net (bucket79) Date: 14 May 2004 02:40:00 -0700 Subject: appending to dict Message-ID: <95f72778.0405140140.662d63fc@posting.google.com> Hi is there anyway appending to dictionary? list has this feature >>>a = [] >>>a.append(1) >>>print a [1] but dictionary can't i wanna do like this thing >>>a = {1, 2} >>>a.append(3, 4) -> This is just my idea :@ >>>print a {1:2, 3:4} so i try this feature like >>>a = {1, 2} >>>a = dict(zip(a.keys().append(3), a.values().append(4))) but this make's error because a.keys().append(3) makes 'None' (i can't understand this :( ) so i try >>>import copy >>>a = dict(zip(copy.copy(a.keys()).append(3), copy.copy(a.values()).append(4))) and a = dict(zip(copy.deepcopy(a.keys()).append(3), copy.deepcopy(a.values()).append(4))) but this make's error, too why a.keys().append(3) makes 'None' ? and is there anyway appending to dictionary? any post will be appreciated :) From adeleinandjeremy at yahoo.com Tue May 4 18:01:07 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Tue, 4 May 2004 15:01:07 -0700 (PDT) Subject: tkinter problem ... Message-ID: <20040504220107.43741.qmail@web50308.mail.yahoo.com> I just recently posted about this very same problem. In fact, I had dug a lot deeper, and even "fixed" the problem for my platform (RedHat 8.0/9.0), but I am left very unsatisfied. The fix I use is incredibly crufty, requiring an environment variable to be set so that the proper library path is used - every time I want to run python. I never received a response to my post, and I am tempteed to believe that there is a bug, but as I have not read *every* bit of documentation, config file notes, and source code, I am not going to go claiming so. Oh and by the way, IDLE still won't work correctly - my fix simply allows me to import Tkinter in the interpreter (not even in a script). I know there must be a better way, because I have never experienced any problems with tkinter/idle/python before v2.2, so I am ignorant of something, and I am even ignorant of what that something is. Or maybe it really is that there is a usability bug in that the installer assumes it knows where tcl and tk libraries are, instead of looking. But I just don't know enough to say so authoritatively, and your problem may be different than mine (as may be your platform). Strangely, I have seen on this list some saying that tk is dying off, and that we should use wxPython. But tk is usable by Tcl, Perl, Java, Scheme, and a few others, and I doubt that wxPython has that going for it, so I remain incredulous. Also, IDLE is written for tk, not for wxPython. Your problem is definitely what the previous respondant said, viz., you are either missing the tk library interface file (eg, tklib.so or tklib.dll), or your Python can't find it. I hope for your own sanity that the problem is the former only and not the latter, as this has caused me a lot of grief lately. I wish you better luck, and request that whatever the problem, you post back with specifics about it and its solution should you find such a solution. - Jeremy __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From dave at pythonapocrypha.com Wed May 19 10:34:05 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 19 May 2004 08:34:05 -0600 Subject: MFC application and Python References: <2410357897.20040519033752@smtp.myrealbox.com> Message-ID: <032301c43dae$566bdd90$6600a8c0@YODA> Adal wrote: > I'm working on a C++ Win32 MFC application and I want to move as much > code as possible to Python. > > At first I wanted to use a Python GUI package and keep the critical > components (performance wise) in C++ extensions. The application must > have a native look so this leaves us with only two choices. > > wxPython is way too bloated (9 MB on disk, 20MB! in memory for basic > stuff) and people say buggy. PythonWin is nice and small, but lacks > some features, like GDI support. You might consider using ctypes as it lets you call pretty much any Windows API. If you are familiar with rather low-level Win32 GUI programming, Venster (a pure Python package built on top of ctypes) provides a good head start - at my company we've used it in several places and have found it to be a good alternative when app size is an issue, or when we're not really interested in anything but a Win32 deployment. -Dave From marcel at vernix.org Wed May 5 12:15:59 2004 From: marcel at vernix.org (Marcel Molina Jr.) Date: Wed, 5 May 2004 12:15:59 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: References: Message-ID: <20040505161559.GA22140@foxy> On Tue, May 04, 2004 at 04:54:30PM -0700, Stephen Ferg wrote: > I've been wondering how we can improve the quality of the Python > documentation. [..snip..] > One solution is a documentation wiki: see the request (below) for a > "corresponding wikiable page for every page here in the pydocs." A > similar but better solution is to follow the model created by the PHP > community. If you follow the link to > http://us2.php.net/manual/en/function.sort.php you'll see how > impressive the results can be. Something like this is clearly what we > need. if php's documentation is being presented as a sort of model in this thread, then i would like to mention what *i* find the most helpful aspect of its documentation system, far apart from there being a comment posting system at the bottom of each page, which has been (as far as i can tell) the primary feature that people would like adopted by python. what really makes sense for me with php's documentation is how very intuitive (and therefore easy and fast) it is to get to what one is looking for. this is particularly true of its online documentation of its built in functions. this ease of access is leveraged through their websites way of dealing with 404 requests. if you go to php.net/ you are automatically redirected to the page that documents that function. this is often more efficient than the three step process of going to the page, doing a search, clicking on the appropriate search result. it is often faster than have a bookmark to a page that lists all functions and then scrolling or even Ctrl-Fing your way to the appropriate one. if you mistype (by putting an underscore, say, where there is none, or visa versa), then you are presented with a page of the 20 closest matches. this can be taken advantage of when there are a set of functions that all share the same prefix (say 'str' or 'pg' or 'array'). in addition, once you have made it to the function you are looking for, the notion of categories is reflected in the left menu which will note that you are on an "str' type function and will then list all string functions for you. the sites 404 handling also extends to more than built in function detection. if you go to php.net/operators you are redirected to the gateway to all documentation on operators. on the left, it provides a menu of all other such gateway pages in the same categorical section of the languages documentation, so there are links to similar gateway pages such as "types", "variables", "constants", "control structures", "classes and objects", etc. it recognizes from what "height" you are approaching the language, which is helpful. in the case of a specific string function (as mentioned above) it lists all string functions, in the case of being on the operators page, it lists all other fundamental language documentation pages. this is not to say that this is revolutionary or unique. i suspect (without the aid of explicitly *remembering*) that most language documentation provides these things. my point about php's iteration of this, though, is that the interface is very intuitive. it does a good job of being psychic. this approach may used with other documentation systems, i just don't know about them. going to google will often get you within three clicks of what you are looking for. that is pretty good. php's website often gets me to what i am looking for in one try, though. when one is focusing on the problem at hand, and making frequent documentation enquiries, getting to the answers as quick as possible allows one to keep their thoughts primarily on what the problem/question is, rather than having to break off and think about the best ways of trying to find a given piece of documentation. online documentation shouldn't be one's only recourse though, and this is a place where python has a major leg up on php. one aspect to python's documentation that i really appreciate is having the help() function interface to pydoc now in the interpreter. whether it be ruby's 'ri', perl's 'perldoc' or python's 'pydoc', command line interfaces to documentation are very helpful, both as a learning tool and a reference, especially when they can be accessed from within an editor such as with vi's Shift-K macro. php has no such interface. pydoc from the interpreter through 'help()' often gets me to where i want to go in one step, so no complaints there. it would be nice, though, if there was the same kind of web site functionality at python.org as there is at php.net (though i am not familiar with all the ways to access documentation for either and there may be many means of getting documentation that address my need that i am just not aware of). i think ruby's "ri" is really great, though much of that functionality seems to be more or less built into python through dir() and __doc__, et al. Summary: php's web site affords the user a flexible approach toward accessing documentation. once you actually *get there* you might like to have comments at the bottom of the page, or you might like, on the other hand, a more "official" reference style approach. regardless, though, you have to *get there* first and php's website makes that very fast and intuitive. i don't have issues with python's documentation, per se, the way that the person who started this thread does. i just wanted to mention the thing that i like about php's documentation which no one else has seemed to mention. thanks, marcel -- Marcel Molina Jr. From gabriel.cooper at mediapulse.com Mon May 3 17:37:13 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 03 May 2004 17:37:13 -0400 Subject: Python CSV DictWriter Problems In-Reply-To: <16534.46723.35707.92255@montanaro.dyndns.org> References: <40966026.70600@mediapulse.com> <409663B5.90102@mediapulse.com> <16534.46723.35707.92255@montanaro.dyndns.org> Message-ID: <4096BB89.9060500@mediapulse.com> Skip Montanaro wrote: > Gabriel> Is there a known-bug in csv.DictWriter? It is ignoring my > Gabriel> attempts to specify a Dialect. It doesn't even error if you > Gabriel> give it anything invalid. I can send it the registered > Gabriel> string-name of the dialect, a string of gibberish, a dialect > Gabriel> object instance, a dialect class object... it accepts all and > Gabriel> ignores all. > >Fixed in CVS I believe. I will check when I get a chance (there doesn't >seem to be a test case for this), but you might try grabbing the DictWriter >class from the csv.py that's in CVS. > > Bah, it turns out I was a goofball. I forgot that there were two parameters between the last required param and the dialact parameter. Basically the function definition looks like this: *DictWriter*(csvfile, fieldnames[, restval=""[, extrasaction=|'raise'|[, dialect=|'excel'|[, fmtparam]]]]) and I did this: x = DictWriter(file, fields, dialect) when I actually had to do either: x = DictWriter(file, fields, None, None, dialect) or x = DictWriter(file, fields, dialect=dialect) Whoops. I ignored the two parameters 'restval' and 'extrasaction'. The worst part is how much time I spent looking at that and simply didn't see it. Tsk Tsk. Gabriel. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stevewilliams at wwc.com Wed May 19 23:11:18 2004 From: stevewilliams at wwc.com (Steve Williams) Date: Thu, 20 May 2004 03:11:18 GMT Subject: What's the meaning of Dutch in "The Zen of Python" In-Reply-To: References: Message-ID: Tim Peters wrote: [omissionalized] I would > have said French, except that every French person I asked "how do you make a > shallow copy of a list?" failed to answer > > alist[:] > > so I guess that's not obvious to them. Based on my exposure to comp.lang.python over the past four years, I'd bet every one of the Italian persuasion would answer correctly. Conclusion? Pragmatics is great in theory, but . . . From agriff at tin.it Sun May 16 16:27:22 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 16 May 2004 20:27:22 GMT Subject: Guess My Number Game References: <90aea0p1sn3ehbca0tds5uuhj5brrbbdj9@4ax.com> Message-ID: On Sun, 16 May 2004 14:57:28 GMT, "Andrew Dalke" wrote: >And not really an answer to the OP; here's a solution which uses >the bisect module, letting it do the heavy work. It uses the same sort >of guess function you have, tied to Python's __cmp__. It isn't an answer >because it's rather too complicated for someone learning programming. It also has the same problem about guessing too many times. bisect_left looks for a position in a sorted list given a value; the "guess the number" game is different, and you're looking for a value instead. You can come close by using a range as the artificial list, but you will end up guessing even when it's not needed (e.g. if answered "low" for 8 and "high" for 6 you don't need another guess; you already know the answer is 7). It's not bisect_left fault, of course; that function is more general and can't take advantage from knowing that the list that is being passed is indeed a range of integers. It's also funny to see a bisection search called the "heavy work": the convoluted (and IMO somewhat ugly) code used to be able to call bisect is much more complex and less intuitive than the bisection code itself. To me seems it would be more accurate saying that the heavy work is trying to call bisect for a use that isn't what bisect was written for. Andrea From noemail at noemail4u.com Wed May 19 08:43:07 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Wed, 19 May 2004 12:43:07 GMT Subject: So what's a "pythong"? (was Re: Python/C++ Developers required for consulting position in Brooklyn, NY) References: Message-ID: <4c7d365be80ef570ec45eff637715cd3@news.teranews.com> On Tue, 18 May 2004 10:44:25 -0400, Peter Hansen wrote: >> We are looking for several contractors with very strong C++ and >> Pythong development skills. > >"Pythong"... now there's a scary image. :-) Ouch! Well, maybe the Python T-Shirts will soon have a companion product. But the question then becomes... what do you want written on your Pythong? Can we get pythondev all-star signature versions? --dang From aahz at pythoncraft.com Sun May 2 15:20:32 2004 From: aahz at pythoncraft.com (Aahz) Date: Sun, 2 May 2004 15:20:32 -0400 Subject: PEP 328 update Message-ID: <20040502192032.GA27165@panix.com> PEP 328 (``import`` changes) has been updated and is available at http://www.python.org/peps/pep-0328.html Comments on the revised version are welcome. One area where feedback is particularly desired is on the frequency of relative imports inside packages in current code, both in absolute terms and as a percentage of all imports. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From godoy at ieee.org Thu May 13 14:13:27 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 13 May 2004 15:13:27 -0300 Subject: Help with Distutils References: Message-ID: On Qui 13 Mai 2004 13:14, Johan Svedberg wrote: > I just started playing around with Distutils and there is one thing I > could use some help with. I'm wondering if there is some convenient way > to access the directories where the data_files was installed? Could you explain when and why you are trying to do that? -- Godoy. From news at contrado.com.au Thu May 13 07:34:22 2004 From: news at contrado.com.au (gsm) Date: Thu, 13 May 2004 21:34:22 +1000 Subject: iterators References: Message-ID: <40a35d4e$0$16597$5a62ac22@freenews.iinet.net.au> Not too sure but I suppose you can design class iterators and you decide how they behave. I normally just add a __iter__ method and use yield class IteratorObject: def __init__(self, data): self.data = data self.__items = len(data) def __iter__(self): index = 0 while index < self.__items: result = blah blah i.e do what ever you want here #eg return a random item from list yield result index += 1 not sure if this helps "Manlio Perillo" wrote in message news:o996a0t6ra0pj42emgjpjsr9c375dracrf at 4ax.com... > Hi. > > Python support forward iterators, but what about bidirectional and > random access ones? > > > Regards Manlio Perillo From ajsiegel at optonline.com Sat May 22 20:11:12 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 23 May 2004 00:11:12 GMT Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <40AFDAF1.4080400@v.loewis.de> Message-ID: <83qva01mh68c319d23e9o4ldtl62qm3188@4ax.com> On Sun, 23 May 2004 00:57:53 +0200, "Martin v. L?wis" wrote: > >The fact that I use cm to measure X, Y, and Z still doesn't make >them homogenous. A question on some IQ test: X,Y & Z rerpesent the 3d coordinates of a point in some coordinate system. X=1 Y=1 Z=1 The ordred seqence (1,1,1) of the X,Y & Z coordinates represents a) heterogenous data b) homogenous data c) N/A has a right answer. A. I disagree. Regards, Art From R.Brodie at rl.ac.uk Thu May 6 12:57:06 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 6 May 2004 17:57:06 +0100 Subject: AttributeError: 'function' object has no attribute 'split' References: <11e5f362.0405060845.16fff0f8@posting.google.com> Message-ID: "Earl" wrote in message news:11e5f362.0405060845.16fff0f8 at posting.google.com... > PathList= string.split(FullPath, "/") is generating the above error > message. when I run my script, but works just fine from the python > command line! What gives? Somehow you've bound the name "string" to a function e.g. >>> def string(): ... return 'help' ... >>> string.split('1') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'split' Let that be a lesson to you to never use meaningful variable names ;) From Scott.Daniels at Acm.Org Mon May 31 16:17:28 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 31 May 2004 13:17:28 -0700 Subject: exceptions In-Reply-To: References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: <40bb96e2$1@nntp0.pdx.net> Calvin Spealman wrote: > ... > Have to admit tho, a continue feature might be useful. Some languages have > this, don't they? The thing is, Where exactly to continue? Should you retry > whatever raised the exception, continue just after it, at the beginning of > that line, or what? > > See this older thread: Xerox's experience (in deliberately removing the "continue from exception" language feature) I found very instructive. -Scott David Daniels Scott.Daniels at Acm.Org From matthiasjanes at gmx.net Sun May 9 13:12:20 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 9 May 2004 10:12:20 -0700 Subject: CGI Proplem displaying image References: Message-ID: > > Use sys.stdout for output in CGI scripts. > Escpecially with binary files. > Try this and see if the problem goes away > > ################# > #my CGISRIPT: test.py > > #! /usr/bin/env python > > import sys > sys.stdout("Content-type: image/jpeg\n\n") > > filename="cgi-bin/dog.jpg" > img = open(filename, 'rb').read() > sys.stdout.write(img) > > ################## > > Remember Google is your friend > http://starship.python.net/crew/davem/cgifaq/faqw.cgi > > waldek Thanks to both of you, Maybe my question was not clear enough: It is for me not a problem to print the Image to screen. (As I said in the beginning) if I use a form with methodes=post example: ____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______ ################# #my CGISRIPT: test.py #! /usr/bin/env python print ("Content-type: image/jpeg"); print # End of headers! filename="cgi-bin//dog.jpg" infile = open(filename, 'rb') doginmemory=infile.read() print doginmemory ################## ################# #my html page with the image tag
################ ____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______ BUT What I want is that I display the image on an HTML page with text together. tables and ....... something like that ################# #my html page with the image tag Some Text some Text ################ A working example code - even very small one would be appreciated Matthias Janes From tzot at sil-tec.gr Mon May 24 17:22:45 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 25 May 2004 00:22:45 +0300 Subject: Solving the Einstein's Riddle in Python References: <40B22B86.152586E4@alcyone.com> Message-ID: <7ep4b0p9j86eojoutm6macj9qt9neeujq2@4ax.com> On Mon, 24 May 2004 10:06:14 -0700, rumours say that Erik Max Francis might have written: >Juha Haataja wrote: > >> I managed to implement a Python code for solving the >> so-called Einstein's Riddle, ... > >Note that this riddle actually has nothing to do with Einstein. Oh, yeah, forgot to mention that. And, either most of the people I know are in the 2% of the population, or the puzzle is not exactly an IQ test... PS Erik, the other day (on the matter of _Troy_ the movie) I was looking for an English translation of the _Iliad_ on the web for a friend, and Google had your site somewhere in the first results page (don't remember the exact search terms I used, though); I saw your name and said, "this name is strangely familiar" :) Great site. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From tjreedy at udel.edu Sat May 22 11:09:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2004 11:09:26 -0400 Subject: Python compilers? References: <7xzn81rue6.fsf@ruckus.brouhaha.com> Message-ID: "Heather Coppersmith" wrote in message news:m23c5smwos.fsf at unique.phony.fqdn... > > In _Common Lisp The Language, Second Edition_, by Guy Steele > (CLTL2), on page 686, in section 25.1.3 ("Compilation > Environment") there is a lengthy list of assumptions the compiler > makes, including: > > o ... within a named function, a recursive call to a function > of the same name refers to the same function [barring > notinline declarations] ... > > o ... a call within the file being compiled to a named > function that is defined in that file refers to that > function [barring notinline declarations] ... > > o ... the signature (or "interface contract") of all built-in > Common Lisp functions will not change ... Interesting. PyCode can be sped up by making the same assumptions. Richard Hettinger's recent recipe implements these assumptions. (It was rejected as part of the standard lib for being too implementation specific, but remains available in the archives and Python Cookbook site.) [snip less applicable to Python today stuff] > So compiled Lisp is a less dynamic than Python, The balance between flexibity and speed continues to be debated by the developers. Terry J. Reedy From diablosystems2000 at yahoo.com Mon May 24 02:51:55 2004 From: diablosystems2000 at yahoo.com (ds2000) Date: 23 May 2004 23:51:55 -0700 Subject: nested grouping with regular expressions Message-ID: <2164532c.0405232251.3877859a@posting.google.com> Hi, Let regex be some regular expression, which contains groups. The pattern that I am interested in is the form of "<(regex)*>" (i.e. the list of some constantly repeating regular expression inside the <> brackets. Unfortunately, re.match("<(..)*>", string).groups() will return only the groups correspond to the last occurence of (regex) Is it possible to get a more tree-like group match (i.e. or at least a list which will contain the groups of each regex occurence). Thanks ahead, ds From frank at chagford.com Sun May 2 03:00:53 2004 From: frank at chagford.com (Frank Millman) Date: 2 May 2004 00:00:53 -0700 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> <10978dla4s8sq17@news.supernews.com> Message-ID: <246a4e07.0405012300.4776f4f3@posting.google.com> "John Roth" wrote in message news:<10978dla4s8sq17 at news.supernews.com>... > "Frank Millman" wrote in message > news:246a4e07.0405010447.11ed5400 at posting.google.com... > > Hi all > > > > I have a question regarding inheritance. I have come up with a > > solution, but it is not very elegant - I am sure there is a more > > pythonic approach. Assume the following class definitions. > > > [...] > > > > Is there a more direct way for a top-level class to determine which > > subclasses were used to instantiate it? > > Look at the __class__ attribute. Specifically, __class__.__name__ > should tell you the name of the class. > > John Roth > > Thanks for the reply, John. Unfortunately this does not seem to give me what I am looking for. I can only look at the __class__ attribute once the object has been instantiated. I want to check the inheritance hierarchy from the top-level __init__ while the object is being instantiated, and raise an exception if it fails my test. It seems from Heather's reply that it is not possible to do this directly, and therefore my inelegant solution is probably as good as any. See my reply to Heather for further comments. Thanks again. Frank From aahz at pythoncraft.com Mon May 10 12:38:16 2004 From: aahz at pythoncraft.com (Aahz) Date: Mon, 10 May 2004 12:38:16 -0400 Subject: BayPIGgies: May 13, 7:30pm Message-ID: <20040510163816.GA2042@panix.com> The next meeting of BayPIGgies will be Thurs May 13 at 7:30pm. It will feature a PyCon trip report from Guido van Rossum and Aahz. BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Advance notice: The June 10 meeting will feature Bruce Eckel repeating his PyCon keynote on the Python type system. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From guy at NOSPAM.r-e-d.co.nz Sun May 9 20:32:20 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Mon, 10 May 2004 12:32:20 +1200 Subject: list comprehension Message-ID: Hello, Trying to change a string(x,y values) such as : s = "114320,69808 114272,69920 113568,71600 113328,72272" into (x,-y): out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" I tried this: print [(a[0],-a[1] for a in x.split(',')) for x in e] But it doesn't work. Can anyone suggest why or suggest an alternative way? The text strings are significantly bigger than this so performance is important. TIA, Guy From me at privacy.net Mon May 24 15:05:55 2004 From: me at privacy.net (Heather Coppersmith) Date: 24 May 2004 15:05:55 -0400 Subject: Prothon vs. Python integers References: Message-ID: On Mon, 24 May 2004 11:31:08 -0700, "Mark Hahn" wrote: > "Paul Prescod" wrote [ snip ] >> Prothon 0.1 Interactive Console, Build 532, May 21 2004 (Ctrl-D to exit) >> >> >>> print 2** 65 >> 3.68935e+19 >> >> >>> print 2**65 == (2**65 + 1) >> True >> If Prothon is a language designed for the next ten years then >> it should be tuned for correctness and ease of use, not for >> limitations of today's hardware. > I'm sure this isn't the only place Python is better. > Prothon has the long integer support in the parser if anyone > wants to take the trouble to put the long object code in. I did > nothing to preclude it. I just didn't see any need for it myself > and didn't take the trouble to put it in. > Longs seemed like a needless exotic kludge to me in the 64-bit > world. Surely once you get to 3.7e19 you are in floating point > territory. I can't imagine counting anything up to 10**19. Beans? ;-) Accountants ("bean counters," in the derogatory vernacular) will be displeased if Prothon silently loses pennies (or other small- valued currencies) after a certain amount (lira and drachma spring to mind, too). Also, modern day cryptography applications can demand integer/ logical operations on 256-, 512-, or more- bit (upwards of 1e150) integers. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From iv at an.voras.fer.hr Tue May 18 06:59:14 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Tue, 18 May 2004 12:59:14 +0200 Subject: HTTP 1.1 pipelining In-Reply-To: References: <4860c084.0405170736.13c6e8b4@posting.google.com> Message-ID: JanC wrote: > Ivan Voras schreef: > > >>I don't think this is how HTTP/1.1 pipelining works. It is still a >>request-response protocol - the only "pipelining" is in the fact that it >>doesn't require a separate connection session for each request-response >>pair. > > > "Pipelining" != "Connection: Keep-Alive" > > Thank you - it's clearer to me now! But, isn't this a direct consequence of keep-alive? From peter at engcorp.com Fri May 7 07:38:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 May 2004 07:38:29 -0400 Subject: Python Resources In-Reply-To: <109l91isml27qe4@corp.supernews.com> References: <109l91isml27qe4@corp.supernews.com> Message-ID: Oten wrote: > Hey Everyone I am looking for as many python web resources as possible I am > looking at developing a Python Search Engine for anything to do with Python. > > Modules, Books Tutorials, Information, Applications, anything at all > > just post to this message with your link and I will put it up and when its > done I will post to this forum > > if you have Python Links in your favourites Post them as well > > I have been searching google as well > > I would like to make this the biggest directory of searchable python > information > > Thank You > > Someone who loves Python I suggest you organize and put up all the links you already have, and then post a link to the "search engine" here. That way you won't waste a lot of people's time suggesting sites that you already have in your list. Surely with Google helping you've already got 95% of the main ones covered anyway... -Peter From steve.menard at videotron.ca Tue May 25 08:58:43 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Tue, 25 May 2004 08:58:43 -0400 Subject: jython 2 cpython bridge In-Reply-To: <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > Randall Smith wrote: > >> I would like to use a type 4 JDBC driver in my Python program. I >> believe I can use in with Jython. Do you know of some way to >> communicate between the Jython and Python processes so that the >> CPython program can use the Jython JDBC database connection? > > > Create some form of IPC between the two, for instance using xmlrpc. > > --Irmen > > PS: I would have suggested to use Pyro, but: > - Java/Jython doesn't have the select() system call that Pyro needs for > a server, > - There are bugs in Jython that make it crash when compiling Pyro's > source. Alternately, you can look at JPype ( http://jpype.sourceforge.net ). It is still a very early release, but I would welcome any feeback. And version 0.1 should allow you to use JDBC without problem. It currently only works on Windows, but if there is interest, I could make a linux release pretty quickly. From acrobert-at-ucalgary-dot-ca at ucalgary.ca Sun May 2 00:38:23 2004 From: acrobert-at-ucalgary-dot-ca at ucalgary.ca (Anthony Roberts) Date: Sun, 02 May 2004 04:38:23 GMT Subject: Efficient string concatenation methods In-Reply-To: References: Message-ID: <3X_kc.316677$Pk3.160920@pd7tw1no> ................................. I was curious about this like an hour ago and googled for it, and hit your page. Thanks! It was quite helpful. From greg at cosc.canterbury.ac.nz Mon May 17 00:40:00 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 17 May 2004 16:40:00 +1200 Subject: Unification of Methods and Functions In-Reply-To: References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> Message-ID: <2gqu12F5qqk9U1@uni-berlin.de> David MacQuigg wrote: > James has been telling me it is terribly wrong to keep data as > attributes of classes There's nothing inherently wrong with that, as long as you're certain you will only ever want one instance of that piece of data. In my chip example, you might want to keep a count of the total number of transistors in your chip as a class variable of the Transistor class. But that only works if your program only ever deals with one chip at a time. If there can be more than one chip, then you'll need a Chip class whose instances either keep a count of Transistors contained in that chip, or have a method that can compute the count when needed. Even if you think you will only deal with one chip at a time, it would be good design practice to plan on having a Chip class anyway, in case the requirements change. The amount of work involved is about the same either way, and the design which avoids class variables is more flexible. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From NOmanlio_perilloSPAM at libero.it Sat May 29 02:33:44 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 29 May 2004 06:33:44 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> Message-ID: <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> On 27 May 2004 22:52:10 +0100, jjl at pobox.com (John J. Lee) wrote: >Manlio Perillo writes: >[...] >> I'm trying to fix the regular expression patternin Cookie.py but it >> does not work: >[...] > >Yeah, IIRC there's some odd stuff in there, that doesn't even seem to >come from the standards, let alone reality ;-) > I have fixed the pattern. For matching spaces it is needed '\ ' and not ' '. Here is the code. Now the Cookie parse the Netscape format. _LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]" _WeekPatt = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)" _MonthPatt = r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" _DatePatt = r"(?:" + _WeekPatt + r",\ \d{2}-" + _MonthPatt +\ r"-\d{4}\ \d{2}:\d{2}:\d{2}\ GMT)" _CookiePattern = re.compile( r"(?x)" # This is a Verbose pattern r"(?P" # Start of group 'key' ""+ _LegalCharsPatt +"+?" # Any word of at least one letter,\ nongreedy r")" # End of group 'key' r"\s*=\s*" # Equal Sign r"(?P" # Start of group 'val' r'"(?:[^\\"]|\\.)*"' # Any doublequoted string r"|" # or ""+ _DatePatt + "" # A date as specified by Netscape\ spec r"|" # or ""+ _LegalCharsPatt +"*" # Any word or empty string r")" # End of group 'val' r"\s*;?" # Probably ending in a semi-colon ) I also have added a method to BaseCookie that behaves like Morsel.OutputString: def OutputString(self, attrs=None, sep='\n'): """Return a string suitable for HTTP. """ result = [] items = self.items() items.sort() for K,V in items: result.append( V.OutputString(attrs) ) return sep.join(result) Now the Cookie is usable on the client side too. >The Cookie module really doesn't know how to handle cookies on the >client side. It does not matter, all the cookie logic for my program is very very simple and standard Cookie is all I need. > Use this, which does: > >http://wwwsearch.sf.net/ClientCookie/ > > >You can just say: > >ClientCookie.urlopen("http://www.example.com/") > >and be done with it. > I have seen the module, but it is too complicated. Standard Cookie module (with my corrections) plus httplib module is really all I need. Thanks and regards Manlio Perillo From rick.ratzel at scd.magma-da.com Thu May 20 17:37:30 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Thu, 20 May 2004 16:37:30 -0500 Subject: How to convert a Python Tuple into a C/C++ array? In-Reply-To: References: Message-ID: <40ad251b$0$15829$39cecf19@news.twtelecom.net> Here is one way to do it (untested...consider it pseudo-code): ... my_array = (double*) malloc(sizeof(double) * PyTuple_Size(pyObj)); tupleSize = PyTuple_Size(pyObj); for( i=0; i < tupleSize; i++ ) { tupleItem = PyTuple_GetItem(pyObj, i); if( !PyFloat_Check(tupleItem) ) { printf("Error: tuple contains a non-float value"); exit(1); } my_array[i] = PyFloat_AsDouble(tupleItem); } ... Jinming Xu wrote: > Hello everyone, > > While embedding my C++ program with Python, I am impeded by the > conversion from a Python Tuple to a C++ array. I hope to get some > assistance from you guys. > > I have a sequence of float numbers to be passed from Python to C++, with > indefinite size. So I chose to use Tuple on the Python side. Since > PyArg_ParseTuple() has no appropriate format to parse Tuple (The Tuple I > am saying is not the Tuple of arguments) of arbitray size, I simply > passed the tuple as follows > > PyObject* myTuple; > if(!PyArg_ParseTuple(args,"O",&myTuple)) > return NULL; > > Now I have the pointer, myTuple, to the Tuple passed in. How can I > convert the the entired tuple, myTuple pointing to, into a float array, > or convert an individual element into a C/C++ float number? Are there > any conversion functions? > > Any suggestions or hints will be deeply appreciated! > > Thanks in advance! > > Jinming > > _________________________________________________________________ > Express yourself with the new version of MSN Messenger! Download today - > it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > From jepler at unpythonic.net Wed May 19 12:28:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 19 May 2004 11:28:30 -0500 Subject: unique number generator In-Reply-To: <03f901c43dad$d0093f40$c700000a@kachun> References: <5da2b26991d290ff30a502d392812f4b@news.teranews.com> <03f901c43dad$d0093f40$c700000a@kachun> Message-ID: <20040519162825.GN14843@unpythonic.net> This is probably not easy to do, without more requirements. UUIDs can be generated randomly, in which case about 120 of the 128 bits may vary. This means that you wouldn't expect to generate two that are identical before about 2^60 are generated, which is enough to make most people comfortable. 8-digit numbers, well, they're shorter. You'd expect to have a collision after about 10,000 "unique" numbers are generated randomly. This isn't very many! UUIDs can be generated using partly a number which should be unique to each machine, plus some other factors. You could consider doing this, giving each machine a unique prefix and generating the suffixes randomly or sequentially. For example, if you have 100 of fewer hosts, you give them the 2-digit prefixes 00 through 99, and let them generate IDs by choosing the final 6 digits. If the machine does so randomly, you'll expect a collision after about sqrt(10e6) ~ 3000 IDs per machine, and if it is done sequentially on each machine then you can use all 10e6 IDs on each machine. 3000 and 10e6 are both pretty small, though. There's a reason that UUIDs are large numbers, unless your system is guaranteed to be very small, narrow "unique numbers" will fail, and if your system is small you might as well allocate them manually, or automatically but sequentially from some "master" source. Jeff From cybermanxu at hotmail.com Thu May 20 16:40:54 2004 From: cybermanxu at hotmail.com (Jinming Xu) Date: Thu, 20 May 2004 15:40:54 -0500 Subject: How to convert a Python Tuple into a C/C++ array? Message-ID: Hello everyone, While embedding my C++ program with Python, I am impeded by the conversion from a Python Tuple to a C++ array. I hope to get some assistance from you guys. I have a sequence of float numbers to be passed from Python to C++, with indefinite size. So I chose to use Tuple on the Python side. Since PyArg_ParseTuple() has no appropriate format to parse Tuple (The Tuple I am saying is not the Tuple of arguments) of arbitray size, I simply passed the tuple as follows PyObject* myTuple; if(!PyArg_ParseTuple(args,"O",&myTuple)) return NULL; Now I have the pointer, myTuple, to the Tuple passed in. How can I convert the the entired tuple, myTuple pointing to, into a float array, or convert an individual element into a C/C++ float number? Are there any conversion functions? Any suggestions or hints will be deeply appreciated! Thanks in advance! Jinming _________________________________________________________________ Express yourself with the new version of MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rowen at cesmail.net Tue May 4 16:13:32 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 04 May 2004 13:13:32 -0700 Subject: urllib hanging in thread Message-ID: I am having trouble with some ftp code. On some platforms it works fine and on others it reliably hangs. The code uses urllib to retrieve a file in a background thread, which runs the following code. The diagnostic message before urllib.urlopen is printed, but the one after urllib.urlopen is not: def _getTask(self): try: self._toFile = file(self.toPath, 'wb') print "opening URL" self._fromFile = urllib.urlopen(self.fromURL) print "URL opened" # when hung this does not print self._totBytes = self._fromFile.info().getheader("Content-Length") if self._totBytes: self._totBytes = int(self._totBytes) self._state = Running while True: nextData = self._fromFile.read(8192) if not nextData: break elif self._state == Aborting: self._cleanup(Aborted) return self._readBytes += len(nextData) self._toFile.write(nextData) self._cleanup(Done) except Exception, e: self._cleanup(Failed, exception = e) However, I can only make it hang when run as part of a fairly large Tkinter application. The same code runs fine standalone or as part of a minimal Tkinter test application. The large application has a few other threads for communicating via TCP. In all other respects the large app runs fine; the ftp hangs while everything else keeps cooking along. Closing the TCP connection (which should stop the other threads) has no effect on the stalled ftp transfer. It works fine on my MacOS X 10.3.3 box, including both the built in python (a variant of 2.3 with aqua Tk) and a python 2.3.3 that I built as a plain unix python with X11 Tk. The code hangs on our RedHat linux boxes (python 2.3.3, dunno the linux version). It also hangs as a standalone MacOS X executable, which is especially weird since the code runs fine on the same computer before it gets packaged up as an application. Any suggestions would be most appreciated. -- Russell From viruswall at austrocontrol.at Mon May 3 04:39:11 2004 From: viruswall at austrocontrol.at (viruswall at austrocontrol.at) Date: Mon, 3 May 2004 08:39:11 GMT Subject: Virus Alert Message-ID: <200405030839.i438dBsr001728@austrocontrol.at> The mail message (file: Passwoerter.txt.pif) you sent to info, ais contains a virus. (on mail.austrocontrol.at ) From tjreedy at udel.edu Mon May 24 10:35:57 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 May 2004 10:35:57 -0400 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com><5sl4o1-crf.ln1@eskimo.tundraware.com><10avdpe73rnj20d@corp.supernews.com><8a0bb987.0405222327.78ef180e@posting.google.com> <10b2dvrfqhmbm5a@corp.supernews.com> Message-ID: "Michael Geary" wrote in message news:10b2dvrfqhmbm5a at corp.supernews.com... > Uri wrote: > For example, these do exactly the same thing: > > import re > for line in file( 'inputFile' ).readlines(): > print re.split( '\s+', line.strip() ) > > import re > reWhitespace = re.compile( '\s+' ) > for line in file( 'inputFile' ).readlines(): > print reWhitespace.split( line.strip() ) > > But for a large file, the second version will be faster because the regular > expression is compiled only once instead of every time through the loop. I am curious whether you have actually timed this or seen others timings. My impression (from other posts and from reading the code a year ago) is that the current re implementation caches compiled re's (recache[hash(restring)] = re.compile(restring)) just so that the first example will *not* recompile every time thru the loop. If so, I think one should name an re for pretty much the same reasons as for anything else: conceptual chunking and reuse in multiple places. Terry J. Reedy From AvMailGate at argos.mainconcept.de Sat May 22 09:59:50 2004 From: AvMailGate at argos.mainconcept.de (AvMailGate at argos.mainconcept.de) Date: Sat, 22 May 2004 15:59:50 +0200 (CEST) Subject: AntiVir ALERT [your mail: "Hello"] References: <20040522135940.964F618F38F@argos.mainconcept.de> Message-ID: <20040522135950.92A1618F666@argos.mainconcept.de> * * * * * * * * * * * * * * * AntiVir ALERT * * * * * * * * * * * * * * * This version of AntiVir is licensed and full featured. AntiVir has detected the following in a mail from your address: Worm/NetSky.Z worm The mail was not delivered. Please remove any potential malicious software from your computer before sending a new mail with attachments. Mail-Info: --8<-- Message-Id: <20040522135940.964F618F38F at argos.mainconcept.de> From: python-list at python.org To: info at mainconcept.de Date: Sat, 22 May 2004 09:59:35 -0400 Subject: Hello --8<-- -- AntiVir for UNIX Copyright (C) 1994-2002 by H+BEDV Datentechnik GmbH. All rights reserved. For more information see http://www.antivir.de/ or http://www.hbedv.com/ From jepler at unpythonic.net Wed May 26 15:30:59 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 26 May 2004 14:30:59 -0500 Subject: prefix matching In-Reply-To: References: Message-ID: <20040526193059.GF537@unpythonic.net> Here's another simple approach: def startswith_one(s, prefixes): for p in prefixes: if s.startswith(p): return True return False If speed is important and "prefixes" doesn't change frequently, then coding a FSM in C is the way to go. The last time this question went around, I learned that REs like a|b|c essentially tries the alternatives one after another, rather than compiling into an FSM like I learned in school, so the amount of time taken is proportional to the length of the total RE, not the longest alternative. Jeff From fumanchu at amor.org Wed May 19 12:59:26 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 May 2004 09:59:26 -0700 Subject: Socket sample? Message-ID: Daniel Orner wrote: > I'm a newcomer to socket programming... I need to use a > server socket > which should be able to handle more than one connection at a > time. I've > read the HOWTO, but I'm still a bit confused about some of the more > intimate details. I've also seen a few pieces of sample code > scattered > here and there, but nothing substantial. > Does anyone know of some sample code that handles > multiple connections > (either by using select() or forking/threading processes)? Hopefully, it'll use both. ;) My distro has a file in Python23/Lib called "SocketServer.py". Have a look through there if you have it--there are a couple of threaded server classes. FuManChu From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun May 16 05:43:24 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 16 May 2004 11:43:24 +0200 Subject: Python and Windows.Forms References: <87n08qrpcv.fsf@pobox.com> <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> <5foda055796ui1putjgobd28pl8r8q9mh7@4ax.com> Message-ID: Python, the first "divination" programming-language ? From rschroev_nospam_ml at fastmail.fm Sat May 22 05:03:37 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 22 May 2004 09:03:37 GMT Subject: Pyrex - The speed of Python with the clarity of C? In-Reply-To: <40AE9A5E.8F514E3B@shaw.ca> References: <40AE2C4E.CE1CE6C0@shaw.ca> <40AE9A5E.8F514E3B@shaw.ca> Message-ID: SeeBelow at SeeBelow.Nut wrote: > But does this C code get compiled into machine code? Yes. > If so, What compiler does that, and when? There's a small getting-started somewhere, I suggest you try that; it covers all that. I tried it a few weeks ago, and IIRC Pyrex creates some C code that you have to compile into a shared library with your favorite C compiler. The shared library can then be imported in Python as a module. -- "Codito ergo sum" Roel Schroeven From tjreedy at udel.edu Wed May 12 11:16:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 May 2004 11:16:17 -0400 Subject: max value in list References: Message-ID: "C GIllespie" wrote in message news:c7te26$8q1$1 at ucsnew1.ncl.ac.uk... > Dear all, > > I have a few lists. What's the best way of finding the maximum number of all > the lists. > > For example, > > [2,3,4],[1,2,3],[4,7] > > The max is 7. Sidestepping 'best' which may depend on context, a general 'good' way is >>> lists = [2,3,4],[1,2,3],[4,7] >>> max([max(l) for l in lists]) 7 Terry J. Reedy From hungjunglu at yahoo.com Sun May 2 12:28:50 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 2 May 2004 09:28:50 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> <69cbbef2.0405020222.6024b162@posting.google.com> Message-ID: <8ef9bea6.0405020828.5eafbd5c@posting.google.com> has.temp2 at virgin.net (has) wrote in message news:<69cbbef2.0405020222.6024b162 at posting.google.com>... > these systems already exist and there's nothing to stop anyone else > from trying them out themselves _before_ trying to critique my > arguments. That is the whole point. This is not like choosing a government where once you are done, there is no point of return until years later. Why don't people just try out? When one has not even tried, and starts to make criticisms like "unification means elimination, I will have to use my shoes to store my soup", it brings nothing but regrets. Ignorance can always be made temporary, regrets, on the other hand, last a lifetime. Making criticisms on something that one (a) has never tried, (b) will never try, is out of the realm of software engineering, even more so when the downloads are free of charge. I am not sure what these criticisms show: about a system, or about the persons making the criticisms? regards, Hung Jung From KNguyen at MEGISTO.com Mon May 17 11:58:02 2004 From: KNguyen at MEGISTO.com (Khoa Nguyen) Date: Mon, 17 May 2004 11:58:02 -0400 Subject: Pyparsing question Message-ID: Hi, I am a newbie to Python and pyparsing. I am having difficulty creating a grammar that spans multiple lines, the input data look like this RTSP/1.0 200 OK\r\n Cseq: 1\r\n Session: 12345-1\r\n \r\n Greatly appreciate if anyone can give me a sample or point me to the right direction Thanks, Khoa Nguyen -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.invalid Tue May 4 13:22:35 2004 From: no.email at please.invalid (Guido) Date: Tue, 04 May 2004 17:22:35 GMT Subject: curses and python (linux, debian) In-Reply-To: References: Message-ID: Michael Hudson wrote: > Guido writes: > > >>Hello >> >>I'm new to python and i'm trying to write a script that shows a menu. >> >>Now, I have some troubles with curses.setsyx() >> >>I do: >> >>import curses >> >>curses.setsyx(2, 20) >>curses.putp("TEST TITLE") >>curses.setsyx(25, 35) >>curses.putp("TEST CENTER") >>curses.setsyx(12, 35) >>curses.putp("TEST CENTER") >> >>but it just prints all the string after each other at the first >>lines.. >> >>can anybody help me please? > > > Don't you call initscr() first? > > Cheers, > mwh > i did, but i forget to copy it From eriksp at attbi.nospam.com Tue May 18 05:46:53 2004 From: eriksp at attbi.nospam.com (EAS) Date: Tue, 18 May 2004 09:46:53 GMT Subject: Timer events References: <93dqc.15615$gr.1409242@attbi_s52> Message-ID: But how do you display the time while it is going? From josephwinston at mac.com Mon May 3 09:08:26 2004 From: josephwinston at mac.com (Jody Winston) Date: Mon, 03 May 2004 13:08:26 GMT Subject: Embedding python into PyQt References: Message-ID: "Diez B. Roggisch" writes: >> What I am trying to do is to embed the python interactive interpreter >> inside a qt TextEdit. >> >> I could write an event loop myself, but I was wandering if there exists a >> solution somewhere, or the best way to do it myself. >> > > I'm quite sure this has been discussed on the pykde mailing list a while ago > - search the archines. > > A program that actually does do that is eric3. > -- > Regards, > > Diez B. Roggisch """mainloop.py -- a nearly exact imitation of the Python main loop.""" """Based on: http://groups.google.com/groups?q=compile+single+python+exec+syntax&hl=en&lr=&ie=UTF-8&selm=199705282255.SAA23573%40eric.CNRI.Reston.Va.US&rnum=2 """ import traceback, sys def run(code, env): try: exec code in env except: sys.last_type = sys.exc_type sys.last_value = sys.exc_value sys.last_traceback = sys.exc_traceback traceback.print_exception(sys.last_type, sys.last_value, sys.last_traceback) def mainloop(env): print "Fake Python", sys.version # print sys.copyright print 'Type "help", "copyright", "credits" or "license" for more information.' # Set sys.ps1 and sys.ps2 if they are undefined; # they are only set in interactive mode try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " # Source collected so far; empty if at start of statement source = "" while 1: if source: prompt = sys.ps2 else: prompt = sys.ps1 try: line = raw_input(prompt) except EOFError: break except KeyboardInterrupt: source = "" print "\nKeyboardInterrupt" continue if source: source = source + "\n" + line else: source = line # Compile three times: as is, with \n, and with \n\n appended. # If it compiles as is, it's complete. If it compiles with # one \n appended, we expect more. If it doesn't compile # either way, we compare the error we get when compiling with # \n or \n\n appended. If the errors are the same, the code # is broken. But if the errors are different, we expect more. # Not intuitive; not even guaranteed to hold in future # releases; but this matches the compiler's behavior in Python # 1.4 and 1.5. err = err1 = err2 = None code = code1 = code2 = None try: code = compile(source, "", "single") except SyntaxError, err: pass try: code1 = compile(source + "\n", "", "single") except SyntaxError, err1: pass try: code2 = compile(source + "\n\n", "", "single") except SyntaxError, err2: pass ## print code, code1, code2 ## print 'err = "%s"' % (err) ## print 'err1 = "%s"' % (err1) ## print 'err2 = "%s"' % (err2) ## print "same = ", err1 == err2 if code: ## print "We got code" run(code, env) source = "" elif code1: ## print "We got code1" pass elif str(err1) == str(err2): ## print "err1 == err2" traceback.print_exception(SyntaxError, err1, None) source = "" if __name__ == '__main__': mainloop(globals()) -- Jody Winston From nc-jantzegu at netcologne.de Sat May 22 17:46:15 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Sat, 22 May 2004 23:46:15 +0200 Subject: Python compilers? References: <7xzn81rue6.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" schrieb im Newsbeitrag news:mailman.183.1085238574.6949.python-list at python.org... > > > So compiled Lisp is a less dynamic than Python, > > The balance between flexibity and speed continues to be debated by the > developers. And should be debated by the users, too. Not all of Pythons dynamics is really necessary to write good programms. Writing good software needs creativity and discipline. We like to work with Python, because it allows us creativitity. Sometimes to enforce a grain of discipline in Python would not be bad. There have been many discussions about programming idioms and design patterns in the last years. They give not so high level languages the ability to simulate high level features. They could also help to give a very high level language more solid ground. And they normalize the way to handle common classes of problems """There should be one-- and preferably only one --obvious way to do it. """ We could try to search patterns, idioms, antipatterns which could establish a better way to use the Python language: -- to avoid unnecessary dynamics -- to avoid unnecessary features -- to establish the 'obvious way to do it' -- without loosing the power and expressiveness of python """In the face of ambiguity, refuse the temptation to guess. """ Possible sideeffect:.- it could be easier for mechanical tools (Pyrex, Psycho, PyPy, Starkiller) to make Python faster Not all people will agree about a useful set of patterns. But this is not necessary now. Patterns and idioms do not change a language immediately. They do not fall from heaven, it is necessary to play around and to gain some experience. I think patterns define a subset of a language and some constraints on programms Maybe this constrained subset (or subsets if there are controversal ideas) can be formalized and be checked by 'pylintplus' or 'pythoncheckerX' (do not google). Or there would be a configurable universal 'Monsterchecker'. In the first line of our sources we expose a checkpolicy and the checker will follow this policy. If patterns can not be formalized so easy, they can be established by convention. I do not know the result of this process ... Now some ideas what could be done in the near future 1) Integration of Pyrex into Python. [strong variant] Syntactically this languages are close. Maybe they could be changed so, that every valid Pyrex source is also a valid Python source with -hopefully- the same semantics. Special Pyrex tokens would be allowed, but meaningless when used in the Python context. Benefit: more homogenous environment. Little changes in the program could be made without a C-Compilation step. Maybe the support of interfaces would be necessary in Python, but this is not a bad idea. Then rewrite some parts of the standard library in Pyrex [weak variant] Rewrite some parts of the standard library in Pyrex 2) Find a set of constraints which make it easier for Psyco (now) and Starkiller (later) to do their job 3) Implement Monsterchecker modes for 1 and 2 Regards Guenter From aahz at pythoncraft.com Wed May 12 13:29:01 2004 From: aahz at pythoncraft.com (Aahz) Date: 12 May 2004 13:29:01 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: In article , Kirk Job-Sluder wrote: > >Well, there is another big difference. I'm a big fan of instant >gratification so the off-the-shelf tool that does the job in 10 seconds >is better than 5 minutes to 1 hour writing a pythonic tool. I have >re-written shell scripts in python just for kicks, but I don't have any >illusions that refactoring everything into python should be a >perogative. If it takes you an hour to rewrite a ten-second job into a Pythonic script, you don't know Python very well. That kinda counters your claim of a shallow learning curve for the other programs. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From bptonner at yahoo.com Mon May 3 08:53:41 2004 From: bptonner at yahoo.com (Brian) Date: 3 May 2004 05:53:41 -0700 Subject: Keyboard input magnetic stripe reader and wxPython References: <5b17ec49.0405021353.460ebdad@posting.google.com> Message-ID: <5b17ec49.0405030453.33854490@posting.google.com> bptonner at yahoo.com (Brian) wrote in message news:<5b17ec49.0405021353.460ebdad at posting.google.com>... > This probably has a simple answer: Yes it does! >From the parent wxWindow of wxTextCtrl... text1=wxTextCtrl(....etc....) text1.SetFocus() text1.Hide() -Brian From theller at python.net Thu May 27 10:03:05 2004 From: theller at python.net (Thomas Heller) Date: Thu, 27 May 2004 16:03:05 +0200 Subject: Fortran-compiled DLLs in Python References: Message-ID: "byte biscuit" writes: > Hi there everybody! > The problem is the following: > we have a DLL (H2O.dll) - compiled in Visual Fortran - depending in turn on > another DLL. > H2O.dll contains only one (1) function, with a known name (WATER). > The WATER function is called with the following parameters: > - TT (datatype: double precision) [input] > - PP (datatype: double precision) [input] > - State (datatype: integer) > [input] > - DiERR (datatype: integer) > [output] > - SIG (datatype: double precision) > [output] > - Prop (datatype: double precision array[16 elements]) [output] > > Obviously, we would like to make use of Python to handle the function and > pick out the results... > We thought of using the **ctypes** module to tackle the problem, but we have > stranded just about at the first attempt: > >>>> from ctypes import * >>>> h2o = windll.H2O >>>> > h2o.WATER(c_long(40.0),c_long(1.0),c_int(2),c_int(dierr),c_int(Sig),c_long*1 > 6(prop)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: int expected instead of float instance > > Who can show us the Right way, riding the Python? THANKS! > > stephen > > > -- > http://mail.python.org/mailman/listinfo/python-list "Luca Simonetti" writes: > Hi Thomas! > an answer from the true creator of the ctypes module - nice! > anyway, we tried implementing your solution and got the following > Traceback Error: > >>>>h2o.WATER(c_double(40.0), c_double(1.0), c_int(2),byref(dierr), byref(sig), prop) > > Traceback (most recent call last): > File "", line 1, in ? > WindowsError: exception: access violation > > which would seem to be the classical exception raised through a failed > function call...? > This is the classical GP fault, which would normally crash a program. ctypes catches it, but doesn't give more information (in current CVS, it would have informed you about which memory location could not be written or read, but that would probably not help you very much). > - Prop (datatype: double precision array[16 elements]) [output] I do not know how fortran passes this parameter, in the example code I posted I assumed that the caller allocates an array, passes a pointer to it to fortran, and the fortran code fills in the elements. Do you have C sample code that works? Thomas From CousinStanley at HotMail.Com Sat May 8 15:42:26 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Sat, 8 May 2004 12:42:26 -0700 Subject: Lost : Plot_Demo Message-ID: <3l2c2j0qpjuo$.1ko02rxrdodj4$.dlg@40tude.net> Several months ago someone here mentioned a small and simple plot demo .... I think it was around the Oct./Nov. 2003 time-frame, but I'm not sure about that .... And, I think the demo was in one of standard Python directories, maybe .... /Scripts /Tools/Scripts The demo put up a small window that provided a text entry field at the bottom where the user could enter an expression that would be eval__uated, scaled, and plotted .... The initial expression that was evaluated when the demo was first loaded was something like .... y = sin( 3*x ) + cos( 2*x ) I don't remember if the original query was someone looking for a plot solution, or in the context of the __evils__ of eval .... I've Googled this NewsGroup and almost worn out the FIND button in Windows trying to find it again .... I have several plot package options available, but would like to find __that__ particular demo again .... Any clues ???? -- Cousin Stanley Human Being Phoenix, Arizona From __peter__ at web.de Sat May 1 03:33:55 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 May 2004 09:33:55 +0200 Subject: Web development class References: Message-ID: Lorenzo Bolognini wrote: > it's been a while I haven't looked at Python but I remember that there > once was a class (I think it was just a class) that helped in web > development. Can't remember the name of the project: it was a kind of a > parser which would allow you to do this sort of stuff: > > h1.red (assigning properties to html entities) > > I think the project's web page was on a kind of red background. > > Any hints? Have a look at http://mail.python.org/pipermail/python-list/2004-April/215227.html Peter From jacek.generowicz at cern.ch Thu May 13 04:07:19 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 May 2004 10:07:19 +0200 Subject: things I wish python could do References: Message-ID: Ryan Paul writes: > I've spent a lot of time using python, and personally, I feel like it is > vastly superior when compared to languages like java, and c++, but there > are still a few things that detract from its elegance and flexibility. I > thought I might mention a few of them. I'd like to hear what people think > of my complaints, and I also like to hear the complaints of others. > > 1. many keywords (eg:try/except) are strictly imperative, and cannot be > used in a functional context. Yes, I find the whole statement expression dichotomy one huge PITA. > this really should be possible: map(print,mylist) > > 2. there is no easy way to extend existing classes externally. > > its possible, but it aint pretty... > > class Shape: > def __init__(self,numSides, perimeter): > pass > > Currently you can do this: > > Shape.__dict__.update({ > 'triangle':ClassMethod( > lambda self,sideLength: Shape(3,sideLength*3)) > > 'square':ClassMethod( > lambda self,sideLength: Shape(4,sideLength*4)) > }) Which looks like (I don't know what ClassMethod is) a long-winded way of wrting: Shape.triangle = lambda self, sideLength: Shape(...)) > I want a way to extend a class as easily as I can define it. You can. There is one syntax for creating new classes, and another for mutating existing ones. Ruby conflates the two. I think that what you "want" is to cleate new classes and mutate existing ones using the same syntax. Perhaps you should question whether you really want that. Maybe there's a satisfactory solution based on the decorators that are being proposed in PEP 318: class Shape [update]: def triangle(self, sideLength): ... > 4. assignments cant be made inside of anonymous functions. Actually, there's very little you can do in anonymous functions, given that you are restricted to a _single expression_. > I was surprised to find that Ruby solves all of my python > complaints, while achieving grace and simplicity easily comparable > to that of python, and providing a few innovative extras (including > real private, public, and protected methods). Yes, access-restricted private methods were an innovation in the field of programmer productivity reduction, but it was not an innovation on Ruby's part ... though why a language which sounds quite sensible, would choose to embrace such a criminal practice is a mystery to me. (Hmm ... briefly perusing a Ruby manual, I get the impression that some of it is a result of having to get around problems caused by all classes inheriting all (would-be) global functions ... which makes me reconsider my statement that Ruby sounds quite sensible.) > Are there are any strong reasons why a language shouldn't support the > things I list? 1) Keywords are just plain wrong. 4) Python's indentation-based block structure makes general anonymous functions a bit problematic. (Briefly perusing the PEPs I notice 308 ... and I'm surprised that it's publication date is not April 1st, as it looks like a PERLification attempt.) > Is anybody aware of features promised for future python versions > that solve or nullify my problems? Read the PEPs. > Are any of my perceived problems really just products of ignorance? Probably. I'm feeling in a controversy-stirring mood. Can you tell? With any luck I've trodden on Python's, Ruby's and your toes :-) From htx1 at gmx.de Wed May 26 04:39:18 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Wed, 26 May 2004 10:39:18 +0200 Subject: Passing parameters to functions In-Reply-To: References: Message-ID: Thomas Philips wrote: > Thanks for the explanation. A follow up question: Suppose I want to > pass AT LEAST 2 positional arguments and AT LEAST 2 keyword arguments > into a function, Then I think I would logically define the function as > follows > > def f(parg1, parg2, karg1="yes", karg2="no", *pargs, **kargs): > print parg1, parg2, pargs, karg1, karg2, kargs > > and I expect that > f(1, 2, 3, 4, 5, karg1="maybe", karg2="maybe not", m="yes", n="no") > > will return > 1 2 (3, 4, 5) "maybe" "maybe not" {'m': "yes", 'n': "no"} > > But instead I get an error: > f() got multiple values for keyword argument 'karg1' > > [...] > > How can I pass all these arguments into the function cleanly? Maybe this way: f (1, 2, karg1="maybe", karg2="maybe not", m="yes", n="no", *[3, 4, 5]) Greeting, Holger From tdelaney at avaya.com Sun May 9 19:36:54 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 10 May 2004 09:36:54 +1000 Subject: Iterating Dictionaries in a Function Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0172A0F1@au3010avexu1.global.avaya.com> Michael Geary wrote: > def findx(st): > d = {'a': 1, 'rty': 4, 'er': 2} > try: > item = d[st.lower()] > except: > print 'Item not found:', st > else: > print 'Item found:', st, item > return item What is that bare `except` doing in there? A general tip - never use a bare except. There are exceptions to the rule, but you need to really understand why not to use a bare except before you do. Also, since you're using a non-changing dictionary, it's best to only create it once. OPTIONS = {'a': 1, 'rty': 4, 'er': 2} def findx (st): try: item = OPTIONS[st.lower()] except KeyError: print 'Item not found: %s' % (st,) return None else: print 'Item found: %s %s' % (st, item,) return item or even better, don't bother catching the exception (I presume you're only doing it for debugging, as with the printing): def findx (st): return OPTIONS[st.lower()] which of course becomes OPTIONS[st.lower()] As stated before, if there's a bug, it's almost certainly in your code (most likely due to your misinderstanding of something). The Python builtin types (e.g. dictionary) are *extensively* tested and used and any such bug would have come to light a long time ago. Tim Delaney From charlvj at yahoo.com Thu May 6 06:12:15 2004 From: charlvj at yahoo.com (Charlie) Date: 6 May 2004 03:12:15 -0700 Subject: classes vs dicts Message-ID: Greetings, I am pretty new to Python and like it very much, but there is one thing I can't figure out and I couldn't really find anything in the docs that addresses this. Say I want to write an address book program, what is the best way to define a person (and the like): create a class (as I would do in Java) or use a dictionary? I guess using dictionaries is fastest and easiest, but is this recommended? Thanx for any help. From grey at despair.dmiyu.org Tue May 25 20:55:36 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 26 May 2004 00:55:36 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: On 2004-05-26, SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be created, but > Python programmers regularly use a class when there will only be one > instance. What is the benefit of this? What happens when down the line someone wants to use that code in something that requires multiple instances? -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From peter at engcorp.com Mon May 3 11:25:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 11:25:44 -0400 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: <0MudnVoTELDrxAvdRVn-gw@powergate.ca> References: <0MudnVoTELDrxAvdRVn-gw@powergate.ca> Message-ID: <5b-dnVJ33JJj_gvdRVn-hQ@powergate.ca> Peter Hansen wrote: > rzed wrote: > >> I have a similar configuration on my system, except that I have a >> glut32.dll, and I have no problems running the demo. There are >> evidently several glut32.dll versions around. > > > That is evidently my problem as well, since after following Mike's > advice about numarray, the error changed to telling me that I > don't have OpenGL installed... which is at least true as far as > glut32.dll missing... Okay, in spite of installing everything that I should have, I didn't have a glut32.dll on my machine. Google led me to http://www.xmission.com/~nate/glut.html from where I downloaded a copy, manually stuck it in c:\windows\system32, and PyOpenGL works now. Now I see that this is on the pyopengl.sourceforge.net installation notes page... I don't recall installing this the same way last time, but there you go. Not only RTFM, but go back and read it again another time if things still don't work. -Peter From tim.one at comcast.net Thu May 27 02:41:45 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 27 May 2004 02:41:45 -0400 Subject: why learn In-Reply-To: <40b58695_1@news.iprimus.com.au> Message-ID: [mr_vocab] > hey i finished working through alot of python stuff and no a fair bit bout > it > > now what can i do with it??? Follow your bliss: in your case, it looks like you'd really enjoy writing a program to post the same question 100 times. It's a lot easier to write a program for that than to stay up all night doing it by hand . From jepler at unpythonic.net Tue May 25 22:52:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 May 2004 21:52:21 -0500 Subject: Embedding Python at the OS level - build problems In-Reply-To: <20040526003414.GA2712@unununium.org> References: <20040526003414.GA2712@unununium.org> Message-ID: <20040526025221.GB32066@unpythonic.net> "pgen" has to be built and run on the host system. I'm surprised to learn that this little detail hasn't been fixed in the build system after all these years. I think it's pretty safe to say that you have to have *some* kind of module to import as 'os'. Just what subset of the functionaliy is actually necesary to start Python, I'm less sure. If your OS is sufficiently different from POSIX, just add a case to the top of os.py for it, and start from scrach on your OS low-level module. Good luck with your project! Jeff From ajsiegel at optonline.com Fri May 28 19:40:58 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 23:40:58 GMT Subject: terminological obscurity References: <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> Message-ID: On Fri, 28 May 2004 22:12:03 +0200, "Martin v. L?wis" wrote: >Arthur wrote: >> Is the random set of, say, 10 human beings homogeonous or >> hetereogenous? > >If they are random, than yes, they are homogenous as they are >all human, and no, the are heterogenous, because they are >random, i.e. they share no features. But then nothing can be determined about the hetergenousity or the homogenousity of any particular context for this data by reference to the data itself. Though the reverse is not true. In the conversation I am having this is a significant point. But I suspect we are not having the same conversation. Art From GPodubs at hotmail.com Wed May 26 14:14:45 2004 From: GPodubs at hotmail.com (SilverShadow) Date: Wed, 26 May 2004 14:14:45 -0400 Subject: Defining Multiple Objects at Once Message-ID: <464afbb13c2bd25bb14351db772159e0@localhost.talkaboutprogramming.com> Hello, I'm having trouble with something that may be easily remedied. I use Cantera running on Python. I need to make multiple "Reactor()" objects and have them assigned a different (user defined) name. For example: reactors = [R1, R2, R3...etc.] for reac in reactors: reac = Reactor() My problem is there is no way to operate on each reactor separately. (e.g. R1.temperature()) The only thing that can be done is reac.temperature(), but that gets overwritten each time. So, my question is, is there any way to assign multiple names w/o having to write out lines of explicit definitions in the code? Thank you in advance. From mwh at python.net Fri May 21 05:48:24 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 21 May 2004 09:48:24 GMT Subject: Running code on module import References: <20040521050534.21796.00001788@mb-m15.aol.com> Message-ID: vbasicboy at aol.com (Grant D. Watson) writes: > You're probably all foo-ed out by now. Is there any way to do this? > I'm not married to the import hook idea, it just seemed like the > most promising to me. I'd agree with that. I would also wonder just what on earth you are up to... it seems very unnatural to me. Cheers, mwh -- It's a measure of how much I love Python that I moved to VA, where if things don't work out Guido will buy a plantation and put us to work harvesting peanuts instead. -- Tim Peters, comp.lang.python From snrkiwi-lists at yahoo.com Sun May 30 15:05:04 2004 From: snrkiwi-lists at yahoo.com (Stephen Roderick) Date: Sun, 30 May 2004 15:05:04 -0400 Subject: Failing connection with MySQLdb on Mac OS X In-Reply-To: <975703D4-B1C3-11D8-A984-000A95AA5CB4@yahoo.com> References: <975703D4-B1C3-11D8-A984-000A95AA5CB4@yahoo.com> Message-ID: <420C5F62-B26C-11D8-A984-000A95AA5CB4@yahoo.com> Two things fixed this: 1) using the database name instead of the table name in the connect() [d'oh!] 2) upgrading to mysql-python-0.9.3b1 Back to the grindstone ... > Getting weird error, and I was wondering if anyone had any > suggestions. My system appears to satisfy all MySQLdb prerequisities > in terms of python, mysql, etc. Also, phpMyAdmin works fine with > mysql, leading me to believe that my installation of MySQLdb is at > fault. Any ideas? > > TIA > > > For file test1.py (for appropriate values of user and passwd, and > database location exists) > > import MySQLdb > db = MySQLdb.Connect ( host="localhost", user="yyy", passwd="xxx", > db="location" ) > > Error is : > > Traceback (most recent call last): > File "test1.py", line 3, in ? > db="location" ) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/site-packages/MySQLdb/__init__.py", line 63, in Connect > return apply(Connection, args, kwargs) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/site-packages/MySQLdb/connections.py", line 115, in __init__ > self._make_connection(args, kwargs2) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/site-packages/MySQLdb/connections.py", line 41, in > _make_connection > apply(super(ConnectionBase, self).__init__, args, kwargs) > _mysql_exceptions.InternalError: (-1, 'connection is closed') > > > -- > http://mail.python.org/mailman/listinfo/python-list > From me at privacy.net Fri May 28 04:10:45 2004 From: me at privacy.net (Duncan Booth) Date: 28 May 2004 08:10:45 GMT Subject: How to list all functions in an imported module? References: <889cbba0.0405270506.3cd91d26@posting.google.com> <21064255.0405271138.544bc83c@posting.google.com> Message-ID: Peter Hansen wrote in news:o-idnZ6O7qVg5SvdRVn-tA at powergate.ca: > Peter Abel wrote: > >> klachemin at home.com (Kamilche) wrote in message >> news:<889cbba0.0405270506.3cd91d26 at posting.google.com>... >> >>>I can't figure out how to list all functions from an imported module. >>>I searched Google, but all the answers I found didn't work. Did >>>something change in Python 2.2, perhaps there's a new method of doing >>>it? >> >> >> e.g the module os >> >> >>>>>import os,types >>>>>for k,v in os.__dict__.items(): >> >> ... if type(v) == types.BuiltinFunctionType or\ >> ... type(v) == types.BuiltinMethodType or\ >> ... type(v) == types.FunctionType or\ >> ... type(v) == types.MethodType: >> ... print '%-20s: %r' % (k,type(v)) > > Yuck... wouldn't using "callable(v)" be a lot nicer? It depends whether he wants to include callable classes or really does want just functions. If he doesn't want callable classes, then a nicer way would be to use isinstance, which also gives you the option of factoring out the list of types: >>> FUNCTION_TYPES = (types.BuiltinFunctionType, types.BuiltinMethodType, types.FunctionType, types.MethodType,) >>> for k,v in os.__dict__.items(): if isinstance(v, FUNCTION_TYPES): print '%-20s: %r' % (k,type(v)) From h.b.furuseth at usit.uio.no Tue May 25 15:04:06 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 25 May 2004 21:04:06 +0200 Subject: Named integers and enums References: <40b37015$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: >Hallvard B Furuseth wrote: > >> I wonder: isinstance() says that even classic class instances are 'object' >> instances, even though they do not seem to be (since __slots__ does not >> work): >> >>> class o: __slots__ = () >> ... >> >>> isinstance(o(), object) >> 1 >> >>> o().foo = True >> >>> > > Actually __slots__ works, you just have a funny idea of what __slots__ > is _for_. __slots__ is a _storage_optimization_. That's not what I mean. I'm wondering why isinstance() claims that instances of 'o' are instances of 'object', when 'o' is not declared to be a subclass of 'object'. I used __slots__ to check if 'o' is a subclass of 'object' anyway, since __slots__ is documented to only work for new-style classes - i.e. classes derived from 'object'. Well, it is not. If it had been, the assignment to o().foo above would have failed. -- Hallvard From peter at engcorp.com Mon May 17 08:23:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 May 2004 08:23:16 -0400 Subject: Is there any instruction on creating a python debugger? In-Reply-To: References: Message-ID: Phipps Xue wrote: > Phipps > "Ben Finney" wrote in > message news:slrncag9fe.21p.bignose-hates-spam at rose.localdomain.fake... > >>On Mon, 17 May 2004 10:08:50 +0800, Phipps Xue wrote: >> >>>I wanna implement a python debugger, but I don't know the way exactly. >> >>By "implement", do you mean you want to use an existing one, or you want >>to make your own? > Sorry for the confusion. Let's see... you're sorry, but you still won't clear it up? ;-) From htx1 at gmx.de Wed May 12 10:15:49 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Wed, 12 May 2004 16:15:49 +0200 Subject: getting the index while iterating through a list In-Reply-To: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> References: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> Message-ID: Fernando Rodr?guez wrote: > While iterating through a list I'd like to know not just the current element, > but also its index. Is there a better way than this: > > i = 0 > newList = [] > for element in aList: > newList.append((i, element)) > i += 1 > > Is there a more elegant way of doing this with for? And with map()? Not with map. Use zip: newList = zip (range (len (aList)), aList) Greetings, Holger From peter.maas at mplusr.de Tue May 4 07:04:09 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 04 May 2004 13:04:09 +0200 Subject: wxPython examples In-Reply-To: <109dr0b4edhb9f2@corp.supernews.com> References: <109dr0b4edhb9f2@corp.supernews.com> Message-ID: Axium Computer Services wrote: > The thing that really bothers me about the tutorials is the entire > layout is always in the __init__ method of the wxFrame class. It seems > if the applications got very large this would become unwieldy. Usual solution is to move the layout definition to a separate file. This could be Python code, XML, or something else (see PythonCard resource files or Delphi dfm files). wxPython allows to define the dialog layout with XML (see demo). Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From michael at foord.net Mon May 17 11:20:39 2004 From: michael at foord.net (Fuzzyman) Date: 17 May 2004 08:20:39 -0700 Subject: Troubles with CSV file References: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> Message-ID: <8089854e.0405170720.52c73c2b@posting.google.com> [snip...] > I replace all "" to """ as suggested and all works fine now. This is not the > ideal solution (sometimes csv file have a data like > , 123, "", 345, > > ... which supposed to be a blank string (not shure). But it is irrelevant > for me now and *replacing* approach is pretty satisfactory. > > Thanks again for your help. > > BTW > http://www.voidspace.org.uk/atlantibots/pythonutils.html is unreachable > ( "The page cannot be displayed" error ) > > Vladimir Ignatov I think I previously stated that it was the unquote function in my csv module. In actual fact it is the linehandle function that handles the unquoting. If you have trouble amending it to cope with double quotes then let me know - I can hack together an amendment for you........ ( email me at mike AT pcblokes DOT com ) I think you will have to make a compromise though - in either case you make one possibility impossible - if you allow double quotes, except for "", Which you just treat as an empty single quote.... then any double quoted lines beginning with a comma become impossible. "", all this is upposed to be between double quotes "" (This is why the rest of the world doesn't use double quotes and single quotes in the same files !) My listparser module has the unquote function I was talking about. (and may also be relevant). Regards, Fuzzy From yazzoo at null.net Mon May 24 14:54:02 2004 From: yazzoo at null.net (yazzoo) Date: Mon, 24 May 2004 18:54:02 GMT Subject: smtplib data error Message-ID: Does anyone know what causes an SMTPLIB DataError? The only thing I can find in the manual is exception SMTPDataError The SMTP server refused to accept the message data. My problem is a previously functioning script suddenly failed last week. My ISP thinks it maybe something to do with upgrading CPanel on their server -- maybe a library was missed, but when I try and execute a script I get... Traceback (most recent call last): File "test-py.cgi", line 790, in ? sendemail(EmailFrom, EmailTo, emsg) File "test-py.cgi", line 20, in sendemail failed = server.sendmail(EmailFrom, EmailTo, emsg) File "/usr/lib/python2.2/smtplib.py", line 685, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (550, 'Administrative prohibition') Thanks for any suggestions. Lester. From __peter__ at web.de Thu May 6 08:50:22 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 14:50:22 +0200 Subject: Announcing PyInvoke References: Message-ID: Stewart Midwinter wrote: > Please tell me what RPC stands for. I don't see that explained anywhere http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=rpc&action=Search From pxlpluker at cfl.rr.com Sun May 9 14:21:57 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sun, 09 May 2004 14:21:57 -0400 Subject: how robust is (CGIHTTPServer ) In-Reply-To: <87n04hlgjd.fsf@blakie.riol> References: <87n04hlgjd.fsf@blakie.riol> Message-ID: <409E76C5.8080507@cfl.rr.com> Wilk wrote: >pxlpluker writes: > > > >> i was looking at twisted but it appears to be WAY beyond my megar >>skills at this point. >>so i think CGIHTTPServer will fit my needs if it is pretty stable. >>I have a small python cgi that i was building and i had this great >>idea of having the cgi server kinda rolled into it for various >>portability reasons and maybe some future features that would not have >>apache to realy on. >> >> > >If you want to have your own server, you don't need CGI, you can start >from BaseHTTPServer, it's very robust. I use it in production. >CGIHTTPServer and SimpleHTTPServer are good examples to show how to >expand BaseHTTPServer. > > I think i need cgi to run python scripts though. I am allowing file upload with some user management/accounts. What kind of traffic does your site get? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mogmios at mlug.missouri.edu Wed May 5 15:01:44 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Wed, 05 May 2004 12:01:44 -0700 Subject: MySQL vrs SQLite Message-ID: <40993A18.6030505@mlug.missouri.edu> I'm considering changing a Python program of mine, that uses MySQL as it's db backend, to use SQLite. I'm mostly wanting something that can make my program a complete package without requiring the user install and configure an external db program. Has anyone experience with these? They both follow the same DB-API so the code should be pretty easy to port, right? Any draw backs to making this change? From nid_oizo at yahoo.com_remove_the_ Thu May 27 09:01:54 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 27 May 2004 09:01:54 -0400 Subject: Update with pickle In-Reply-To: <71gtc.75003$Qc.3030919@twister1.libero.it> References: <71gtc.75003$Qc.3030919@twister1.libero.it> Message-ID: <2Fltc.48903$tb4.1681844@news20.bellglobal.com> Matteo Dell'Amico wrote: > Nicolas Fleury wrote: > >> I think it is acceptable that this pickle.update function would only >> accept reference of same type and raise an exception otherwise. The >> point of pickle.update would be to not "replace an object with another >> one" but to call __init__ on an existing object. > > > I still don't understand how exactly you would want it to work. If you > want to call __init__ on an existing object, why don't you just do it > explicitly? Could you post some equivalent code to what you would want > pickle.update to do? Unfortunately I can't, something like what Stefan described would be necessary to do it. Basically, instead of creating a new instance, the pickle.update would use an existing one. All the rest after that point is the same, whatever that means (fill up __dict__ or calling __setstate__ or whatever). In fact, forget about what I said about __init__;) Regards, Nicolas From greg at cosc.canterbury.ac.nz Wed May 19 21:09:16 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 20 May 2004 13:09:16 +1200 Subject: alternatives to making blocks like { } or other ?? In-Reply-To: References: Message-ID: <2h2epuF8ckqaU1@uni-berlin.de> Tim Williams wrote: > I found a bug in one of my programs recently where a line > of code should have been outside of an 'if', but wasn't because I hit > TAB one too many times. And for some reason it wasn't obvious from looking at the indentation? In a brace-delimited language, you can get the opposite problem, which is much worse: the code *looks* right judging by the indentation, but it doesn't match the brace structure. Python is a WYSIWYG language! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From lho at gmx.de Tue May 4 16:26:03 2004 From: lho at gmx.de (Lutz Horn) Date: Tue, 4 May 2004 22:26:03 +0200 Subject: Newbe-books References: <0ktjm1-d3q.ln1@home.rogerbinns.com> Message-ID: * Roger Binns [Tue, 4 May 2004 00:34:13 -0700]: > The Python Cookbook published by O'Reilly is a very good example > of such a book. The recipes are available online: http://aspn.activestate.com/ASPN/Python Lutz -- http://piology.org/ILOVEYOU-Signature-FAQ.html begin LOVE-LETTER-FOR-YOU.txt.vbs I am a signature virus. Distribute me until the bitter end From sorry at but.no.spam Tue May 25 12:42:17 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Tue, 25 May 2004 19:42:17 +0300 Subject: Problem with uudecode Message-ID: I made a Python script which takes Usenet message bodies from a database, decodes uuencoded contents and inserts them as Large Object into a PostGreSQL database. However, it appears that the to last few bytes of uudecoded data are always mangled. Take a look of this hexdump output: Originals (decoded with Pan, each line is from a different file): 000c2c0 e1bf 00ff 2541 a9e4 a724 d9ff 0011a10 ff54 00d9 00093e0 fb4f a80d ffd9 c200 ffef 00d9 Decoded by the script: 000c2c0 e1bf 00ff 2541 a9e4 a724 d0ff 0011a10 ff54 00d8 00093e0 fb4f a80d ffd9 c200 ffef 00d8 As you can see, one of the last two bytes gets altered in all cases. The script also outputs the decoded file to disk for debugging purposes, and the database large object and filesystem file match so it can't be a PostGreSQL problem. So, if anyone has any idea what is wrong, please tell me ? I can't found any reason why the bytes would get mangled... The script follows: #!/usr/local/bin/python2.3 # Insert message contents into the database, for each message-id already there # # Copyright 2004 by Juho Saarikko # License: GNU General Public License (GPL) version 2 # See www.gnu.org for details from pyPgSQL import libpq import nntplib import sys import string import regex import sha import imghdr import binascii import StringIO import os def strip_trailing_dots(n): tmp = [] for i in range(len(n)): if n[i][-1] == "," or n[i][-1] == ".": tmp.append(n[i][:-1]) else: tmp.append(n[i]) return tmp def findmimetype(body, filename): tail4 = string.lower(filename[-5:]) tail3 = string.lower(filename[-4:]) if tail4 == ".jpeg": return "image/jpeg" if tail3 == ".jpg": return "image/jpeg" if tail3 == ".png": return "image/png" if tail3 == ".jpe": return "image/jpeg" if tail3 == ".gif": return "image/gif" return None def insert_picture(conn, image, filename): hash = sha.new(image) qhash = libpq.PgQuoteBytea(hash.digest()) candidates = conn.query("SELECT id, picture FROM pictures WHERE hash = " + qhash ) if candidates.ntuples > 0: print "Found possible mathces " + str(candidates.ntuples) for x in range(candidates.ntuples): old = candidates.getvalue(x, 1) old.open("r") oldpic = old.read() old.close() if oldpic == image: print "Found a match" ret = (candidates.getvalue(x,0), 1) return ret mime = findmimetype(image, filename) print "attempting to get mimetype" if mime == None: print "No mimetype found" ret = (0, 0) return ret mime = libpq.PgQuoteString(mime) mimeres = conn.query("SELECT id FROM mimetypes WHERE mimetype = " + mime) if mimeres.ntuples == 0: conn.query("INSERT INTO mimetypes (mimetype) VALUES (" + mime + ")") mimeres = conn.query("SELECT id FROM mimetypes WHERE mimetype = " + mime) mimetype = mimeres.getvalue(0,0) picture = conn.lo_creat("rw") picture.open("rw") picture.write(image) picture.close() tmp = conn.query("INSERT INTO pictures (hash, mimetype, picture) VALUES (" + qhash + ", " +str(mimetype) + ", " + picture.name + ")") temp = conn.query("SELECT id FROM pictures WHERE OID = " + str(tmp.oidValue)) id = temp.getvalue(0,0) ret = (id, 0) return ret def try_decode_and_insert_uuencoded(conn, id): begin = regex.compile("begin [0-9]+ \(.*\)") conn.query("BEGIN") basedir = "kuvat" message = conn.query("SELECT data FROM fragments_bodies WHERE message = " + str(id) + " ORDER BY line") # print message.ntuples keywords = [] picids = [] newpicids = [] n = 0 s = "" picid = 0 print 'Starting message id ' + str(id) while n < message.ntuples: # print "length of row " + str(n) # print str(message.getlength(n, 0)) # print "Got length" abcddummy = message.getvalue(n, 0) # print "Got value" s = message.getvalue(n, 0) # print "Got s" if begin.match(s) > 0: # if match_beginning(s) > 0: # print "Begin matched" body = [] file = begin.group(1) # file = get_file_name(s) # print "Starting to decode, at line " + str(n + 1) for k in range(n+1, message.ntuples): # print "Decodind row " + str(k) s = message.getvalue(k, 0) if s[:3] == "end": n = k + 1 break try: body.append(binascii.a2b_uu(s)) except: try: bytes = (((ord(s[0])-32) & 63) * 4 + 3) / 3 body.append(binascii.a2b_uu(s[:bytes])) except: print "Broken attachment in message " + str(id) conn.query("ROLLBACK") return # print "Got to end, at line " + str(n) # print "Attempting to join body" body = string.join(body, "") # print "Attempting to hash body" # hash = sha.new(body) # qhash = libpq.PgQuoteBytea(hash.digest()) # qbody = libpq.PgQuoteBytea(body) # print "Attempting to find whether the pic already exists" print "Mimetype returned " + str(findmimetype(body, file)) # temporary = open("dummy", "wb") # temporary.write(body) # temporary.close() # dummy.write("dsfds") print "Calling insert function" picid, exists = insert_picture(conn, body, file) print "Returned from insert function with value " + str(picid) if picid > 0: # already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) # if already.ntuples == 0: # print "Attempting to find mimetype" # mimetype = findmimetype(body, file) # print "Found mimetype" # if mimetype != None: # o = conn.query("INSERT INTO pictures (picture, hash, mimetype) VALUES (" + qbody + ", " + qhash + ", " + libpq.PgQuoteString(mimetype) + ")") # already = conn.query("SELECT id FROM pictures WHERE OID = " + str(o.oidValue())); # already = conn.query("SELECT id FROM pictures WHERE data = " + qbody) # already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) # print "Attempting to insert hash and mimetype" # conn.query("INSERT INTO pictures (hash, mimetype) VALUES (" + qhash + ", " + libpq.PgQuoteString(mimetype) + ")") # print "Attempting to get id" # already = conn.query("SELECT id FROM pictures WHERE hash = " + qhash) # print "Attempting to get value" # picid = already.getvalue(0, 0) print picid print "Attempting to OK dir" if os.access(basedir + "/tmp", os.F_OK) != 1: os.mkdir(basedir + "/tmp") fh = open(basedir + "/tmp/" + str(picid), "wb") fh.write(body) fh.close() print "File ok" picids.append(picid) if exists == 0: newpicids.append(picid) if file != "": keywords.append(file) # else: # picid = already.getvalue(0, 0) # if already.ntuples == 0: # conn.query("ROLLBACK") # return # picids.append(picid) # if already.ntuples == 0: # print "already.ntuples == 0, ROLLBACKing" # conn.query("ROLLBACK") # return # print "Appending picid" # picids.append(picid) # print "Picid appended" else: tmptmp = string.split(s) tmpkey = strip_trailing_dots(tmptmp) if len(tmpkey) > 0: for j in range(len(tmpkey)): keywords.append(tmpkey[j]) # print "Adding 1 to n" n = n + 1 if len(picids) > 0: print "Found " + str(len(picids)) + " pictures (" + str(len(newpicids)) + " new ones)" # print "Finding Subject" head = conn.query("SELECT contents FROM fragments_header_contents WHERE message = " + str(id) + " AND header = (SELECT id FROM fragments_header_names WHERE header ilike 'Subject')") if head.ntuples > 0: # print "Splitting Subject" blah = head.getvalue(0,0) # print str(blah) blahblah = string.split(str(blah)) # print "Stripping" abctmpkey = strip_trailing_dots(blahblah) # print "Stripping done" # print "Really" tmpkey = abctmpkey # print "Subject split" if len(tmpkey) > 0: for j in range(len(tmpkey)): keywords.append(tmpkey[j]) o = conn.query("INSERT INTO messages DEFAULT VALUES") mid = conn.query("SELECT id FROM messages WHERE OID = " + str(o.oidValue)) messageid = mid.getvalue(0, 0) nresult = conn.query("SELECT contents FROM fragments_header_contents WHERE message = " + str(id) + " AND header = (SELECT id FROM fragments_header_names WHERE header ILIKE 'Newsgroups')") if nresult.ntuples > 0: for x in range(nresult.ntuples): newsgroups = string.split(nresult.getvalue(x, 0), ",") if len(newsgroups) > 0: for y in range (len(newsgroups)): newsgroup = libpq.PgQuoteString(newsgroups[y]) ngroupres = conn.query("SELECT id FROM newsgroups WHERE name = " + newsgroup) if ngroupres.ntuples > 0: newsgid = ngroupres.getvalue(0, 0) else: conn.query("INSERT INTO newsgroups (name) VALUES (" + newsgroup + ")") ngrtmpres = conn.query("SELECT id FROM newsgroups WHERE name = " + newsgroup) newsgid = ngrtmpres.getvalue(0, 0) conn.query("INSERT INTO messages_ngroups_glue (message, newsgroup) VALUES (" + str(messageid) + ", " + str(newsgid) + ")") else: print "An empty Newsgroups: header at messag " + str(id) conn.query("ROLLBACK") return else: print "No Newsgroups: header at message " + str(id) conn.query("ROLLBACK") return for x in range(len(picids)): conn.query("INSERT INTO messages_pictures_glue (message, picture) VALUES (" + str(messageid) + ", " + str(picids[x]) + ")") if len(keywords) > 0: for x in range(len(tmpkey)): qword = libpq.PgQuoteString(str(keywords[x])) tmp = conn.query("SELECT id FROM keywords_words WHERE keyword = " + qword) if tmp.ntuples == 0: conn.query("INSERT INTO keywords_words (keyword) VALUES (" + qword + ")") tmp = conn.query("SELECT id FROM keywords_words WHERE keyword = " + qword) keyid = str(tmp.getvalue(0, 0)) for y in range(len(picids)): conn.query("INSERT INTO keywords_glue(word, picture) VALUES (" + keyid + ", " + str(picids[y]) + ")") dummyone = "SELECT fragments_header_contents.line, fragments_header_names.header," dummytwo = " fragments_header_contents.contents FROM fragments_header_names, fragments_header_contents" dummythree = " WHERE fragments_header_contents.message = " + str(id) dummyfour = " AND fragments_header_contents.header = fragments_header_names.id" head = conn.query(dummyone + dummytwo + dummythree + dummyfour) if head.ntuples > 0: for h in range(head.ntuples): qhead = libpq.PgQuoteString(str(head.getvalue(h, 1))) qcont = libpq.PgQuoteString(str(head.getvalue(h, 2))) tmp = conn.query("SELECT id FROM header_names WHERE header = " + qhead) if tmp.ntuples == 0: conn.query("INSERT INTO header_names (header) VALUES (" + qhead + ")") tmp = conn.query("SELECT id FROM header_names WHERE header = " + qhead) headid = str(tmp.getvalue(0, 0)) line = str(head.getvalue(0, 0)) conn.query("INSERT INTO header_contents (header, message, line, contents) VALUES (" + headid + ", " + str(messageid) + ", " + line + ", " + qcont + ")") conn.query("DELETE FROM fragments_header_contents WHERE message = " + str(id)) conn.query("DELETE FROM fragments_bodies WHERE message = " + str(id)) conn.query("COMMIT") if len(newpicids) > 0: tmpdir = basedir + "/tmp/" for i in range(len(newpicids)): picid = newpicids[i] tmppicname = tmpdir + str(picid) permpicname = basedir + "/" + str(picid%1000) + "/" + str(picid) print tmppicname print permpicname if os.access(basedir + "/" + str(picid%1000), os.F_OK) != 1: os.mkdir(basedir + "/" + str(picid%1000)) os.link(tmppicname, permpicname) os.unlink(tmpdir +str(picid)) else: print "No pictures found" conn.query("ROLLBACK") return database = libpq.PQconnectdb('dbname = kuvat') items = database.query("SELECT message FROM whole_attachments") # try_decode_and_insert_uuencoded(database, 5407) for i in range(items.ntuples): try: print 'Starting call ' + str(i) try_decode_and_insert_uuencoded(database, items.getvalue(items.ntuples - 1 - i,0)) print ' returned from call ' + str(i) except: print 'Some other error occurred at message " + str(i) + ", trying to continue...' From nid_oizo at yahoo.com_remove_the_ Fri May 14 11:16:18 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 14 May 2004 11:16:18 -0400 Subject: Pickling array.array Message-ID: <3p5pc.78949$FH5.1782405@news20.bellglobal.com> Hi, Does anyone know if arrays would be picklable in python 2.4? Until then, I tried to derive from array.array and add __setstate__ and __getstate__ with the following code, but it seems I'm not doing it correctly. Any idea what I'm doing wrong? Thx and Regards, Nicolas import array as arr class array(arr.array): def __getstate__(self): return {'buffer': self.tostring()} def __setstate__(self, dict): self.fromstring(dict['buffer']) From eppstein at ics.uci.edu Fri May 14 01:15:45 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 13 May 2004 22:15:45 -0700 Subject: exhaustive subsets References: Message-ID: In article , "Brett Calcott" wrote: > I've found some python solutions to find the set of subsets for a given set, > but how do you find the set of the set of subsets whose union is the given > set and whose intersections is the empty set. > > ie. Given a cake divided into 6 unique pieces (0-5), how many different ways > can I distribute the cake so that there are no pieces left. eg. > > ((0), (1,2,3,4)) > or ((0),(1),(2,3,4)) > or ((0,1),(2,3),(4)) > or ((0,4),(1),(2,3)) > > Is there a name for this problem? Partitions? Didn't we just have a discussion about them here a week or two ago? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From richie at entrian.com Wed May 19 07:58:48 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 19 May 2004 12:58:48 +0100 Subject: How does use of bsddb interact with Python in a commercial environment? In-Reply-To: References: Message-ID: [Ken] > What are the legalities of writing commercial code which makes use > of the bsddb module in Python? I asked exactly this question when we adopted bsddb for SpamBayes. Here's what Barry Warsaw (the PythonLabs guy who talked to Sleepycat about it) had to say: http://mail.python.org/pipermail/spambayes/2002-November/002213.html It will continue to make nervous until SleepyCat themselves publish a statement about it. -- Richie Hindle richie at entrian.com From guineapig at pi.be Thu May 27 05:53:24 2004 From: guineapig at pi.be (GuineaPig) Date: Thu, 27 May 2004 11:53:24 +0200 Subject: calendar by week In-Reply-To: References: Message-ID: Peter Otten wrote: > GuineaPig wrote: > > >>One thing that I would like to accomplish is that the user has to only >>give in the weeknumber of the year. The app should then write the dates >>in this week to the excel-sheet. I've been looking at the calendar and >>time modules but I don't quite see a solution there (maybe there is >>though, maybe I'm just too much of a newbie.) > > > import datetime > > def daysOfWeek(year, week): > day = datetime.date(year, 2, 1) > year, weekBase, dayBase = day.isocalendar() > day += datetime.timedelta(1 - dayBase + (week - weekBase)*7) > delta = datetime.timedelta(1) > for i in range(6): > yield day > day += delta > yield day > > Try it: > > >>>>from daysofweek import daysOfWeek >>>>for d in daysOfWeek(2004, 1): > > ... print d > ... > 2003-12-29 > 2003-12-30 > 2003-12-31 > 2004-01-01 > 2004-01-02 > 2004-01-03 > 2004-01-04 > > Peter > Thanks Peter, This works great! Tom From SeeBelow at SeeBelow.Nut Mon May 10 13:34:39 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Mon, 10 May 2004 17:34:39 GMT Subject: What's the difference? (I see now. References: <409EB546.B8367374@shaw.ca> Message-ID: <409FBD3D.3B6397E3@shaw.ca> SeeBelow at SeeBelow.Nut wrote: > > between this: > > name = "C" > > and this: > > name = StringVar() > name.set("C") Now I realize that StringVar is a Tkinter class. You have to import from Tkinter, and you have to execute Tk() before you can execute StringVar(). There is more difference than similarity between my two fragments above. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From Joseph.V.Laughlin at boeing.com Fri May 14 18:22:02 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Fri, 14 May 2004 15:22:02 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: <67B3A7DA6591BE439001F2736233351202B479E1@xch-nw-28.nw.nos.boeing.com> > -----Original Message----- > From: Erik Max Francis [mailto:max at alcyone.com] > Sent: Friday, May 14, 2004 3:12 PM > To: python-list at python.org > Subject: Re: RELEASED Python 2.3.4, release candidate 1 > > > "Laughlin, Joseph V" wrote: > > > I would avoid installing applications that way, if only for > the fact > > that you can't uninstall an application. > > How can you not install an application installed that way? > > rm -f $PREFIX/bin/python* $PREFIX/bin/pydoc $PREFIX/lib/python* Personally, six months from now, I would have no clue as to all the different locations a particular program installed files to. It would be worse if the program had modified various configuration files, etc. And if you had other programs that depended on the program you were uninstalling, that would also lead to breakage. From tjreedy at udel.edu Sun May 23 19:35:18 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 May 2004 19:35:18 -0400 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: "Dan Bishop" wrote in message news:ad052e5c.0405231407.37ddba21 at posting.google.com... > What you *can* do to make your code faster (if you don't change matr > once it's created) is to precompute the 676 possible matrix rows. > > ELEMENT_RANGE = range(26) > MATRIX_ROWS = [[x, y] for x in ELEMENT_RANGE > for y in ELEMENT_RANGE] > for row1 in MATRIX_ROWS: > for row2 in MATRIX_ROWS: > matr = [row1, row2] > > That takes only 532 ms -- almost 3 times faster than the original. Cute. While I am quite familiar with and have experience applying the principle of computing once instead of multiple times, I missed its application here. tjr From rogerb at rogerbinns.com Sun May 16 22:19:16 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 16 May 2004 19:19:16 -0700 Subject: book on wxPython? References: <40a5a851$0$8512$a18e6209@newsreader.visi.com><40a651f4$0$17265$a1866201@newsreader.visi.com> Message-ID: Andreas Kostyrka wrote: > By the way, wxWindows does a API model that is > relativly close to Windows developement ;) The real Win32 API is based on the Win16 API which was a reasonable design in 1983, but had a lot of premature size and performance optimization. That premature optimization is extremely cruddy now. MFC was a C++ wrapper that tried to do things more sensibly (aka object oriented) but was constrained by the C++ language of the time and the underlying Win32 API. That said, MFC isn't *bad* a toolkit to base something like the design of wxWidgets on. And wxWidgets has gone through two major versions now and has significantly refined things. Roger From CousinStanley at HotMail.Com Thu May 6 10:57:50 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Thu, 6 May 2004 07:57:50 -0700 Subject: Need Help in Python References: <77632a66.0405041826.37568aef@posting.google.com> <154eba01da3bc4d337e453163f9096e2@news.teranews.com> Message-ID: On Thu, 06 May 2004 12:12:37 GMT, Daniel 'Dang' Griffith wrote: > """ Starter module for drawing boxes with characters. > No warranty or suitability for use is expressed or implied. > Daniel 'Dang' Griffith sez, "Have a nice day!". > """ Daniel .... Thanks for a nice generalization .... Preliminary tests indicate a problem with indent strings NOT being applied to the FIRST, top, line in the returned string .... I'll try to find the problem .... -- Cousin Stanley Human Being Phoenix, Arizona From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat May 15 04:48:13 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 15 May 2004 09:48:13 +0100 Subject: bug in inspect (was cgitb vs traceback) In-Reply-To: <40A5D206.3000901@jessikat.fsnet.co.uk> References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> <40A5D206.3000901@jessikat.fsnet.co.uk> Message-ID: <40A5D94D.6010708@jessikat.fsnet.co.uk> Robin Becker wrote: ..... > > No I'll mosy on over and see if it's known. I have a fix in place in our > code, but we had to modify it yesterday as we're delivering for 2.1. I didn't find anything similar there so I submitted a bug report and the patch I used. I think it's far too late for 2.3.4. As to whether this problem occurs in 2.1 I'm not sure. I know we fixed the fix in our 2.1 tests as it had a // operator in the code and that won't work in 2.1. I'm not sure whether it works though as we need it only with cgitb and I'm not sure that's even present in 2.1. -- Robin Becker From graham__fawcett at hotmail.com Thu May 13 09:22:35 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 13 May 2004 06:22:35 -0700 Subject: Smalles Possible Browser to display python cgi program References: Message-ID: matthiasjanes at gmx.net (matthiasjanes) wrote in message news:... > Dear everyone, > > I would like to know what would be the smalles possible WebBrowser for > displaying Python CGI application. > > I developed a few small application with an WebInterface. > > The appplication runs just locally. > > I use CGIHTTPServer.py Module as a small webserver and Mozilla > Firebird as Browser. > > Does anyone know of a very small browser which I can directly > integrate. > > Just the very minimum for this purbose, no bookmarks, no tools, no > javascript, no flash ...... > > just displaying frames, html, forms, python cgi files and images. Consider using the wxHTML widget in the wxPython GUI library. There's a nice writeup on it at IBM DeveloperWorks: http://www-106.ibm.com/developerworks/linux/library/l-wxpython/?open&l=810,t=gr -- Graham From dave at pythonapocrypha.com Sat May 8 08:40:46 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 8 May 2004 06:40:46 -0600 Subject: Help me. How to open a new IE window? References: Message-ID: <00f101c434fa$70395390$6600a8c0@YODA> angel wrote: > I want python(win32com) to open a new IE window. > Source is: > /******/ > import win32com.client > msie = win32com.client.Dispatch("InternetExplorer.Application") > msie.Visible = 1 > msie.Naviagte(http://www.python.org) > /******/ > The problem is the program always grabs a existed IExplorer window or > Explorer window. It never opens a new window. I ran into that same problem. Try this: msie = win32com.client.DispatchEx('InternetExplorer.Application.1') It seems to work for me. -Dave From giles_brown at hotmail.com Sat May 22 08:22:34 2004 From: giles_brown at hotmail.com (Giles Brown) Date: 22 May 2004 05:22:34 -0700 Subject: Pyrex - The speed of Python with the clarity of C? References: <40AE2C4E.CE1CE6C0@shaw.ca> <40AE9A5E.8F514E3B@shaw.ca> Message-ID: <57de9986.0405220422.1add461c@posting.google.com> SeeBelow at SeeBelow.Nut wrote in message news:<40AE9A5E.8F514E3B at shaw.ca>... > But does this C code get compiled into machine code? If so, What > compiler does that, and when? The pyrex installation provides distutils extensions. This lets you create a setup.py which compiles your .pyx files into .c files and then your .c files into .pyd modules. It really is extremely simple, but it does rely on having a C compiler set up that distutils can use. Best of luck, Giles From segphault at sbcglobal.net Mon May 10 17:01:31 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 10 May 2004 21:01:31 GMT Subject: What I don't like about wxPython References: <283adf56.0405100657.6f4840ef@posting.google.com> Message-ID: On Mon, 10 May 2004 07:57:17 -0700, Kevin Dahlhausen wrote: > I'll throw a plug in here for pyFltk. It overcomes many of the issues > you have with wxPython. It's not as heavily developed as the wxWin, > but Andreas is doing a great job of updates since taking it over. Thx for mentioning. I'd like to look into this, can I get a link? From tjreedy at udel.edu Sun May 2 10:53:37 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 May 2004 10:53:37 -0400 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> <246a4e07.0405012334.5e5474db@posting.google.com> Message-ID: "Frank Millman" wrote in message news:246a4e07.0405012334.5e5474db at posting.google.com... > Heather Coppersmith wrote in message news:... > > Python usually takes the "we're all adults here" point of view, > > and leaves that question to unit tests and/or code reviews. No > > amount of B&D is sufficient to protect from a malicious coder > > anyway. > ps What does B&D mean? Bondage and Discipline From sross at connectmail.carleton.ca Fri May 14 09:11:06 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 14 May 2004 09:11:06 -0400 Subject: beginner's question References: Message-ID: "Sean Ross" wrote in message news:Xs3pc.34385$dr1.943764 at news20.bellglobal.com... > dst.write(str(w in lexicon)) # writes 'True, ' or 'False, ' The above code will run the True/False output together, e.g. "TrueTrueFalseTrueFalse". I doubt that's what you want. Perhaps this, instead: dst.write("%s "%(w in lexicon)) That would write "True True False True False". Sean From Scott.Daniels at Acm.Org Mon May 17 17:02:50 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 17 May 2004 14:02:50 -0700 Subject: bit shifting question In-Reply-To: References: Message-ID: <40a92d88$1@nntp0.pdx.net> Grant Edwards wrote: > On 2004-05-17, Michael Hudson wrote: > >>>My question is does python share java's peculiar mode of bit >>>shifting, or does python adhere closer to c's bit shifting? >> >>The right shift in Python is arithmetic, i.e. preserves the >>sign bit. > > Which one is the sign bit? IOW, how wide is a "word"? In most cases, you should not be able to discover how wide a "word" is. Python is trying to move to a single integer data type which is a combination of the current "long" and "int" where the internal representation is an implementation detail. Unfortunately, shifting is one of those places you can still discover the "width" with code like: def wordwidth(): for shift in range(256): if 1 << shift < 0: return 1 + shift -- -Scott David Daniels Scott.Daniels at Acm.Org From follower at iname.com Thu May 6 22:47:33 2004 From: follower at iname.com (Follower) Date: 6 May 2004 19:47:33 -0700 Subject: [ANN] "Mongoose" catches runaway Pythons (Initial release v0.1) Message-ID: New "Mongoose" package now available: + Provides a graceful exit and report when an uncaught Python exception occurs in deployed production or beta software. + Catches and reports otherwise unhandled Python exceptions in a helpful and extensible manner. + Automatically generates an unique Mongoose Incident Identifier(TM) to help you track the same bug across multiple computers. License: LGPL Read more about Mongoose below or download and try Mongoose today: URL: Email: Basic usage example ------------------- import mongoose from mongoose.reporters import FileLogReporter mongoose.start() mongoose.registerReporter(FileLogReporter('mongoose.log')) mongoose.setSessionInfo('your_app_version', '1.0') # < ... your code here ... > mongoose.stop() Mongoose Reporters ------------------ Mongoose replaces the default system exception handler so one or more "reporters" can act in response to an uncaught exception. Supplied sample reporters can: * Log the event to a file * Email the developer or support staff * Display output on a console * Display a wxWindows dialog to the user Mongoose Incident Identifiers ----------------------------- Mongoose Incident Identifier technology provides developers with a convenient way to track the same exceptional incident (i.e. "bug") across multiple computers. A Mongoose Incident Identifier is an automatically generated unique identifier that will be the same on any computer which encounters the problem. (Similar to Full Circle Software's TalkBack ID and Bugtoaster's Crash Signature.) Sample reporter output ---------------------- ConsoleReporter: This program has encountered a problem that means it can not continue. Please contact your technical support provider, system administrator or the vendor of this software and ask them for assistance. Mongoose Incident Identifier: 89662 FileLogReporter (Long format): --------------------------------------------------------------------------- Mon Mar 3 15:50:23 2003 89662 exceptions.Exception Dummy Exception Traceback (most recent call last): File "mongoose/reporters.py", line 491, in ? raise Exception("Dummy Exception") Exception: Dummy Exception info one: Stuff info two: A value --------------------------------------------------------------------------- EmailReporter: From: mongoose at example.com To: developer at example.com Subject: Mongoose Incident Report X-Mongoose-Id: 89662 Date: Mon, 3 Mar 2003 15:50:23 -0800 (PST) (This is an optional message prologue.) --------------------------------------------------------------------------- Mon Mar 3 15:50:23 2003 89662 exceptions.Exception Dummy Exception Traceback (most recent call last): File "mongoose/reporters.py", line 491, in ? raise Exception("Dummy Exception") Exception: Dummy Exception info one: Stuff info two: A value --------------------------------------------------------------------------- More about "Mongoose Incident Identifiers" ------------------------------------------ The following is an example MII: 89662 Exciting, huh? Why is a Mongoose Incident Identifier good for users? ----------------------------------------------------- + A MII gives the user a single, small and easy to remember piece of information to identify their problem. They can then search the vendor's support database or talk to support personnel about it. Why is a Mongoose Incident Identifier good for support staff? ------------------------------------------------------------- + The MII for any particular incident is the same for all computers the software is installed on. A MII helps support staff determine whether a bug has been seen before, and find out if there are known solutions or work-arounds for it. Why is a Mongoose Incident Identifier good for developers? ---------------------------------------------------------- + Helps to determine how bugs should be prioritized by noting the relative frequency of each MII. + Provides a convenient method of conveying information from the user to the developer about particular bugs. Once a bug has an MII associated with it the developer can also link the logged traceback (including custom session information) and other information to it. Download and try Mongoose today: URL: Email:

Mongoose 0.1 - Catch and report otherwise unhandled Python exceptions in production or beta software in a helpful and extensible manner, also provides bug specific Mongoose Incident Identifiers. (07-May-04) From __peter__ at web.de Fri May 28 07:41:42 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2004 13:41:42 +0200 Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> Message-ID: Rodrigo Daunaravicius wrote: > Is there an elegant way to directly refer the 2nd dimension of a > multi-dimensional sequence (like the nth character in a list of strings). [list of strings example] While your example doesn't work, as Matteo already explained, the Numeric package provides an intuitive way to refer to the nth dimension of a matrix: >>> a = Numeric.reshape(range(9), (3,3)) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a[:, :-1] array([[0, 1], [3, 4], [6, 7]]) In spite of its name, Numeric is not limited to numbers: >>> d = ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n'] >>> a = Numeric.array(d) >>> a.tostring() '0891931243\n0325443777\n0933477028\n0699624617\n' >>> a[:, :-1].tostring() '0891931243032544377709334770280699624617' Note that shorter strings are filled with spaces: >>> Numeric.array(["123\n", "4\n", "789\n"]).tostring() '123\n4\n 789\n' Of course this is overkill for your example use case. Peter From fredrik at pythonware.com Wed May 26 07:25:30 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 13:25:30 +0200 Subject: r'\' - python parser bug? References: <5155aad2.0405250137.1cd7c53e@posting.google.com> <8089854e.0405252339.18e0c59d@posting.google.com> Message-ID: Fuzzyman wrote: > Wrong, surely ? nope. > >>> print '\\' > \ the parser sees the first backslash, skips the second backslash, sees the end quote, and passes everything between the quotes to the next compiler stage. > >>> print r'\\' > \\ the parser sees the first backslash, skips the second backslash, sees the end quote, and passes everything between the quotes to the next compiler stage. > >>> print r'c:\subdir\' > SyntaxError: EOL while scanning single-quoted string the parser sees the first backslash, skips the "s", and moves on. the parser then sees the second backslash, skips the end quote, and stumbles upon an EOL. syntax error (grammar violation). > > When the parser sees a backslash inside > > a string literal, it always skips the next character. > > In the above example the parser *only* skips the next character if it > is at the end of the string... surely illogical. you're confusing the string literal syntax (which is what the parser deals with) with the contents of the resulting string object (which is created by a later compiler stage). read the grammar (it's in the language reference) and try again. From kkto at csis.hku.hk Fri May 28 10:29:28 2004 From: kkto at csis.hku.hk (Isaac To) Date: Fri, 28 May 2004 22:29:28 +0800 Subject: r'\' - python parser bug? References: <5155aad2.0405250137.1cd7c53e@posting.google.com> <8089854e.0405252339.18e0c59d@posting.google.com> <5155aad2.0405272246.436235c4@posting.google.com> Message-ID: <7i7juwlj5j.fsf@enark.csis.hku.hk> >>>>> "Konstantin" == Konstantin Veretennicov writes: Konstantin> @"\" // ok @"\"" // error, unterminated string literal Konstantin> For me, personally, trailing backslashes aren't as important Konstantin> as quotes. Python wins again :) hm...... Quotes in Python can only happen if it follows a \. This is not that useful I believe. Of course, unless \ is really used as an escape character in the string, i.e., regex. Perhaps the "r" in r'\'' should be read as "regex" rather than "raw"? =) Regards, Isaac. From jfabiani at yolo.com Tue May 18 11:28:55 2004 From: jfabiani at yolo.com (john fabiani) Date: Tue, 18 May 2004 15:28:55 GMT Subject: error converting list to tuple In-Reply-To: References: Message-ID: john fabiani wrote: > Stefan Seefeld wrote: > >> hi there, >> >> I'm trying to convert a tuple to a list, >> and get a 'TypeError: list objects are unhashable'. >> >> Can anybody enlighten me as to the possible causes >> for this ? Where does hashing come into play during >> this conversion ? >> >> Could it be that my runtime is corrupted ? >> The code is executed from within a C++ extension >> module I'm developing... >> >> Thanks for any help, >> Stefan >> >> PS: I'm using python 2.3.3 in case that matters >> >> > God I can't believe I think I can answer this question: > mylist=[] > t=('123','hello','bye') > for count in range(0,len(t)): > mylist.append(t[count]) > > It works for me. > John even better than above: mylist=list(t) See everyone I'm learning but it is not easy for an old man to learn new tricks. John From agriff at tin.it Sat May 1 11:18:16 2004 From: agriff at tin.it (Andrea Griffini) Date: Sat, 01 May 2004 15:18:16 GMT Subject: a=([],); a[0]+=[1] Message-ID: <7ff790taojrrqka0trq9ltm82g0ac95ria@4ax.com> When reading about python "warts" i stepped in this example I find quite puzzling: a = ( [] , ) a[0] += [1] this gives an error, because a tuple cannot be modified. But if you print the content of "a" it will show it has indeed been modified. How can this happen ? if "+=" for list was called then no modification to the tuple was requested and so no error should have been raised; if instead "+" and "=" was executed then after a failing assignment the original list is safe... (or at least I thought so; if you type "a[0] = [2]" you get the error and "a" is not modified). Is there an explanation simpler than investigating on python sources ? Andrea From eastier at free.fr Thu May 6 16:30:41 2004 From: eastier at free.fr (Emmanuel) Date: Thu, 06 May 2004 22:30:41 +0200 Subject: Several questions about embedding Python References: Message-ID: <409AA071.2041F54E@free.fr> Miki Tebeka a ?crit : > Hello All, > > I'm trying to extend a hardware simulator (written in C/C++) by > embedding Python. > After reading the documentation and playing around several questions > popped up: > > 1. Is there a way (using SWIG/Boost.Python ...) to export existing C/C++ > functions other than hand writing the wrapper functions. > Something like: py_export(a_c_function) > Since the Python module need to get information from the simulator I > can't just write pure SWIG wrapper (or can I?) ? I don't understand... Just have a header file with the function you want to call from Python, and let SWIG parse it. That's what I'm doing... > > > 2. How do I debug the Python code? Since the interpreter is called from > the simulator application I can't run `pdb' on it. I used HAP editor/debugger, that can be quite simply included in a embedded app. But I must admit there are still some bugs in it, and I'm not sure it's still actively developped... > > > 3. Why on does pyconfig.h decides that `python23_d.lib' should be used > when _DEBUG is on (IMO is should use Py_DEBUG)? I'm debugging *my* > application not Python. You should use : #ifdef _DEBUG #undef _DEBUG #include "python.h" #define _DEBUG #else #include "python.h" #endif instead of the main #include "python.h" to get rid of this issue. Actually, I have a special MyPython.h for this. ( I add a special define in order to allow this trick or not, I remember times where step into python for debugging ) Hope it helps, Emmanuel From j_mckitrick at bigfoot.com Tue May 4 14:27:17 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 May 2004 11:27:17 -0700 Subject: Problem binding and events References: <20040427135207.GA5359@dogma.freebsd-uk.eu.org> Message-ID: > if a keyboard binding doesn't work as you expect it to, it's usually because > focus is somewhere else. when in doubt, add a widget.focus_set() call to > the appropriate location. It turns out I had to bind the event to the Toplevel container, not the listbox. Not sure why that is the case, but it works now. Thanks From ehab_teima at hotmail.com Mon May 31 10:54:06 2004 From: ehab_teima at hotmail.com (Ehab Teima) Date: 31 May 2004 07:54:06 -0700 Subject: exit code from py2exe as a service Message-ID: <17aafe08.0405310654.422fce95@posting.google.com> Hello, I'm using py2exe to convert python code to a service. It all works great. One little problem is that when I run MyService.exe -option, it always returns 0 exit code. This makes trapping errors too hard. Could this be fixed? I'm using 0.5.0. Ehab From newsgroups at jhrothjr.com Sat May 8 07:00:19 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 May 2004 07:00:19 -0400 Subject: Distutils help needed! References: <109o01v7s4lm2bd@news.supernews.com> Message-ID: <109pfeqh9indgc9@news.supernews.com> I got a response by e-mail that suggested I look at either scripts or data_files. Somehow when I read the doc, data_files went right by without making an impression! I'll try that next. Scripts, on the other hand, produced an error and I had to remove it for the install to work at all. And I'm now puzzled about why manifest.in even exists. If you have to name every file in the setup script, it seems awfully redundant. BTW - responses in e-mail will not always reach me. Everything, and I mean everything, from newsgroups goes directly to my trash folder, does not pass go, does not get whitelisted or anything else. If I throw out the trash without looking, it isn't there. John Roth "John Roth" wrote in message news:109o01v7s4lm2bd at news.supernews.com... > I'm trying to put together a distribution for Python > FIT 0.4a1 (the first version I'm actually distributing), > and distutils is giving me a slight problem. It seems > to be building OK and both the manifest file and the > .zip file have all the right directories and contents. > The install seems to work and it's putting the fit > directory in the right place, but the result is missing > directories that don't contain at least one Python module. > (and one directory that does contain a Python > module, but it doesn't contain a __init__.py - > the module is a script, not something to import.) [snip the rest] From michele.simionato at poste.it Thu May 27 04:44:05 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 27 May 2004 01:44:05 -0700 Subject: Cleaner idiom for text processing? References: Message-ID: <95aa1afa.0405270044.71307d09@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > Yet another way to create the dictionary: > > >>> import itertools > >>> nv = iter("foo 1 bar 2 baz 3\n".split()) > >>> dict(itertools.izip(nv, nv)) > {'baz': '3', 'foo': '1', 'bar': '2'} > >>> > > Peter BTW, the name I have seem for this kind of things is chop: >>> import itertools >>> def chop(it, n): ... tup = (iter(it),)*n ... return itertools.izip(*tup) ... >>> list(chop([1,2,3,4,5,6],3)) [(1, 2, 3), (4, 5, 6)] >>> list(chop([1,2,3,4,5,6],2)) [(1, 2), (3, 4), (5, 6)] >>> list(chop([1,2,3,4,5,6],1)) [(1,), (2,), (3,), (4,), (5,), (6,)] (I don't remember if this is already in itertools ... ) Michele Simionato From jdhunter at ace.bsd.uchicago.edu Sun May 16 18:22:46 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 16 May 2004 17:22:46 -0500 Subject: Help with large data set and fatal python error In-Reply-To: ("Vineet Jain"'s message of "Sat, 15 May 2004 10:27:39 -0400") References: Message-ID: >>>>> "Vineet" == Vineet Jain writes: Vineet> Exception exceptions.AssertionError: Vineet> in Vineet> ignored Do you know what assertion is failing in the remove function and can you fix it? Vineet> Any ideas what the errors means and how can I Vineet> debug/catch them? The most likely thing is that you have made a mistake in your reference counting, perhaps decrementing a reference where you shouldn't have, or creating a python object and failing to incref it. Have you written a python extension module? If so did you do it by hand or are you using one of the standard wrapper generators like SWIG or pyrex? If the latter, it could be a bug in the wrapper generator. If not, it might help to post some of your code which acts on the PyObjects. JDH From skip at pobox.com Sat May 8 18:11:47 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 8 May 2004 17:11:47 -0500 Subject: Looking to hire a python programmer In-Reply-To: References: Message-ID: <16541.23331.242115.966575@montanaro.dyndns.org> >> I need to hire a python programmer for a small modification project. >> Where is the best place to find one? Roy> Try the Python job board, http://www.python.org/Jobs.html The job board would be a good place to post your job opening. Don't look for resumes there however. Skip From paulo.pinto at cern.ch Thu May 6 08:34:16 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Thu, 06 May 2004 14:34:16 +0200 Subject: A simple xml.dom.minidom question Message-ID: Hi All, I want to have some control of how the xml in writexml() is written. Is that possible? Or do I have to do navigate the XML tree by myself? Thanks in advance, Paulo Pinto From mwh at python.net Mon May 24 10:37:30 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 24 May 2004 14:37:30 GMT Subject: r'\' - python parser bug? References: <5155aad2.0405240635.6c2915a5@posting.google.com> Message-ID: kveretennicov at yahoo.com (Konstantin Veretennicov) writes: > Hi, > > recently i tried this: > > ActivePython 2.3.2 Build 232 > >>> '\\' > '\\' > >>> r'\' > File "", line 1 > r'\' > ^ > SyntaxError: EOL while scanning single-quoted string > > Is this a known issue? http://www.python.org/doc/faq/general.html#why-can-t-raw-strings-r-strings-end-with-a-backslash Cheers, mwh -- To summarise the summary of the summary:- people are a problem. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From dmq at gain.com Fri May 7 21:08:09 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 07 May 2004 18:08:09 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <1083822394.7883@yasure> <3sgl90pcsl8s7n4q65v0rnefirrog0clk1@4ax.com> <2g0fsrF33p4cU1@uni-berlin.de> Message-ID: On Fri, 07 May 2004 15:59:20 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> Static methods >> are necessary because it is a very natural thing to write a method in >> a class that needs to work without being bound to any particular >> instance. > >I beg to differ. It might seem natural to someone who's >been exposed to C++ or Java, but I don't think it's >a priori a natural thing at all. I'm not fond of C++ or Java. Python is my first actual use of OOP. >In Python, a function defined inside a class is a method. >If you want a function to be a method, you put it inside >a class. If you don't want it to be a method, you don't >put it inside a class. It's as simple as that. I really don't care if we call something a method or a function. What I care about is that a program is well-structured and easy to understand. I seem to be getting a lot of heat for putting the show() functions in multiple classes in my Animals_2.py example. The alternatives proposed seem to make the structure less clear. Instead of having each part of the total show() functionality in its appropriate class [1] I'm told that I need to put all of this at the global level. One suggestion was to find some regularity in all the show functions and write a global function to generate all outputs based on that regularity. This won't work, because in general, there is no such regularity. Another possibility I have thought about is having a global function that selects among four blocks, depending on the type of the instance that called the show() function. If its a Cat, we need all four output blocks. If its a Mammal, we need just Mammal and Animal. In other words, replicate the inheritance behavior of classes with some kind of if ... elif ... elif ... elif ... structure. This will be a pain to write, compared to the elegance of just having each show() function call its parent. The real problem with these alternatives, however, is that it puts stuff that belongs in a particular class, outside of that class. This will make the code harder to understand, and harder to maintain. When I need to add a Feline class between Mammal and Cat, I must remember to edit the global show() function, adding stuff unique to Feline, and changing the logic of the selections to include the new block. With a large hierarchy of classes this is going to be a mess, certainly more mess than just adding a few 'staticmethod' lines to the existing classes. Maybe I'm missing an option here. I don't claim to be an expert in Python. -- Dave [Note 1] A function belongs in a class if the variables it works with are unique to that class. If it works with variables from several classes, it belongs in the class of a common ancestor. For optimum modularity and encapsulation, we should put each function as low as possible in the hierarchy of classes, without excessive duplication. The tradeoff is you want to avoid crowding all your functions at the top, and avoid unnecessary replication of the same functionality in multiple classes at the bottom. Example: If I had a function that needed only Cat variables, except for one variable from Parrot, I would not put that function in the Animal class. The better tradeoff is to leave it a Cat function, and reach out with a fully-qualified reference to grab that one Parrot variable. ( I might also put a ### flag on the line in Cat where that outside variable is needed, so I don't later forget about this external dependency.) From phrogeeb at hotmail.com Tue May 11 03:20:47 2004 From: phrogeeb at hotmail.com (Uri) Date: 11 May 2004 00:20:47 -0700 Subject: Writing Formatted txt to a file (xtreme newbie q) References: <8a0bb987.0405101503.2656788a@posting.google.com> Message-ID: <8a0bb987.0405102320.58898a9f@posting.google.com> > [[question1, answer1], [question2, answer2], etc...] > or > ['question1=answer1', 'question2=answer2', etc...] > or some other way. > It is stored in the format: ([question1, answer1]), made up of the question list and the answer list zip()'ed together. Is there a better way to do this? I had considered doing it with a dictionary, but i had problems with this, and found the easiest way to be zipped two lists together. WE can also keep them apart, I suppose. I hadn't realized it depended so heavily on which way you do it. =) Thanks! From rnd at onego.ru Mon May 31 13:13:38 2004 From: rnd at onego.ru (Roman Suzi) Date: Mon, 31 May 2004 21:13:38 +0400 (MSD) Subject: 2.2 <-> 2.3 surprise Message-ID: Hi! I really like python 2.3 but sometimes I write for 2.2 too. New cool feature of doing: f = open('file') for line in f: do_something(line) works strange in 2.2: I can't just quit first loop and do: for line in f: do_some_more(line) (I as skipping message header by first loop and processing body the the second). In 2.3 it works as intended! Of course, simple refacture made it one loop... Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From bokr at oz.net Sun May 2 23:57:35 2004 From: bokr at oz.net (Bengt Richter) Date: 3 May 2004 03:57:35 GMT Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> <1095h4vc89hmcf@corp.supernews.com> Message-ID: On Mon, 03 May 2004 02:31:53 -0000, Dave Benjamin wrote: >In article , Greg Ewing wrote: >> Dave Benjamin wrote: >>> Hey, I never knew that "this" could be used inside of an anonymous object >>> in JavaScript. Thanks for pointing that out! >>> >>> In Python, you'd have to give the object a name, since there's no "self" to >>> refer to. >> >> No, you wouldn't, because the Python equivalent would >> be something like >> >> def F(): >> c = [105] >> >> class C: >> a = 5 >> >> def incr(self): >> self.a += 1 >> c[0] += 1 >> return [self.a, c[0]] >> >> return C() > >I don't know if I'd call it equivalent. Similar in effect, naybe, but the >idea was to create an anonymous, classless object. Anonymous follows, though not classless ;-) >>> o=type('',(),{'incr':lambda s: setattr(s,'a',getattr(s,'a',5)+1) or getattr(s,'a')})() >>> o.incr() 6 >>> o.incr() 7 >>> o.incr() 8 Or perhaps better, using the class variable as initial value as Greg is doing above: >>> o=type('',(),{'a':5,'incr':lambda s: setattr(s,'a',getattr(s,'a')+1) or getattr(s,'a')})() >>> o.incr() 6 >>> o.incr() 7 >>> o.incr() 8 You could also concoct a bound method operating on the variable held in a list >>> oincr = (lambda s:s.__setitem__(0,s[0]+1) or s[0]).__get__([5], list) >>> oincr() 6 >>> oincr() 7 >>> oincr() 8 Or perhaps more cleanly, just subclass list and instantiate with initial value: >>> o = type('',(list,),{'incr':lambda s:s.__setitem__(0,s[0]+1) or s[0]})([5]) >>> o.incr() 6 >>> o.incr() 7 This stuff is fun for exploring ins and outs of the language, but readable is best, if there's a readable alternative ;-) > >> It's a bit more awkward in Python due to the inability to >> directly rebind a name in an outer scope. > Yes, I wouldn't mind more and cleaner control of binding and evaluation, as to when and where (e.g. read time, def time, call time and local binding vs find-and-rebind in lexically nested or mro name spaces). >This is an issue, but not a serious one. In my original example, I used a >pretty simple workaround (an anonymous object). > OTOH, if something strikes you as a workaround, it's not something you want to be struck with regularly ;-) >> BTW, IMO this is a seriously warped technique that I >> would never use, even in Javascript. I can't see any >> benefit in it that's anywhere near worth the obfuscation. > >One benefit, which applies equally to both languages, is that this technique >gets you closer to enforced private attributes than the standard ways of >making objects. I'm sure you could hack frames or something, but "c" is >pretty much inaccessible to the casual programmer in your example above. > Gotta go. Regards, Bengt Richter From PeterAbel at gmx.net Thu May 20 16:24:05 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 20 May 2004 13:24:05 -0700 Subject: Printing formatted strings from a dictionary References: <21064255.0405131144.160af9a8@posting.google.com> Message-ID: <21064255.0405201224.77a7574f@posting.google.com> Josiah Carlson wrote in message news:... > [snip good reply from Peter] > > The other thing to remember is that there are implicit quotes: > >>> d = {1:2} > >>> "%(1)i"%d > Traceback (most recent call last): > File "", line 1, in ? > KeyError: 1 > >>> "%(1)i"%d > '2' Uuuaaah, I can't stop learning YOU(python). Couldn't verify the above example. Maybe some fault happened to you because the code which raised the KeyError and the successfull one are the same for me. But the following works: >>> d={'1':2} # Remark the quotmarks '1' >>> '%(1)i'%d '2' >>> I even would not have believed that this kind of formatting would work. But the more I think about it the more it becomes consequential and logical. - Peter - > - Josiah From sam at cvisiontech.com Tue May 11 20:32:25 2004 From: sam at cvisiontech.com (sam) Date: Wed, 12 May 2004 00:32:25 GMT Subject: PythonService crapping out References: Message-ID: looks like latest win32 on SF fixed this.... "sam" wrote in message news:m0eoc.44020$mX.15390141 at twister.nyc.rr.com... > this is happening on builds as early as 2.3.1 > > " > C:\Python23\Lib\site-packages\win32>PythonService.exe /register > Registering the Python Service Manager... > Fatal Python error: PyThreadState_Get: no current thread > > This application has requested the Runtime to terminate it in an unusual > way. > Please contact the application's support team for more information. > " > > Any fix on the horizon? > > thanks. > > From kevryan0701 at yahoo.com Sun May 23 23:18:21 2004 From: kevryan0701 at yahoo.com (Kevin T. Ryan) Date: Sun, 23 May 2004 23:18:21 -0400 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> Message-ID: <40b1697d$0$3131$61fed72c@news.rcn.com> Ralph A. Gable wrote: > I'm a newbie at this but I need to control MSIE6 using Python. I have > read the O'Reilly win32 python books and got some hints. But I need to > Navigate to a site (which I know how to do) and then I need to get at > the source code for that site inside Python (as when one used the > View|Source drop down window). Can anyone point me to some URLs that > would help out? Or just tell me how to do it? I would be very > grateful. I'm not sure why you need to go through IE, but maybe this will get you into the right direction: >>> import urllib >>> f = urllib.urlopen('http://www.python.org') >>> f.readline() '>> f.readline() ' "http://www.w3.org/TR/html4/loose.dtd" >\n' >>> You could do: for line in f: process(line) just like you can with a file. Check the urllib, urllib2, and other related modules (maybe httplib). Hope that helps. From __peter__ at web.de Mon May 3 03:31:40 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2004 09:31:40 +0200 Subject: Method binding confusion References: Message-ID: A B Carter wrote: > I'm a bit confused by the behavior of the following code: > > > import math > import myModule > > class Klass(object): > def doOperation(self, x, y): > return self.operator(x, y) > > class KlassMath(Klass): > operator = math.pow > > class KlassMyModule(Klass): > operator = myModule.pow > > km = KlassMath() > kmy = KlassMyModule() > > km.doOperation(2,4) > km.doOperation(2,4) Should that be kmy.doOperation(2,4)? Please cut and paste actual code. (The same goes for the tracebacks) > The last call fails with "TypeError: takes exactly 2 argumetns (3 > given)" I understand that in KlassMyModule the operator is being > treated as a method and a reference to the class instance is being > past as the first argument. And I also understand that Python is > treating a function from the standard math libary differently from a > function I defined in my own module. What I don't understand is why. Assuming that myModule.pow (which you do not to provide) is a function that takes two arguments, all these will fail: kmy.doOperation(2, 4) kmy.operator(2, 4) km.doOperation(2, 4) km.operator(2, 4) If you want to avoid the automatic addition of self, use staticmethod: >>> def mypow(a, b): ... return "%s ** %s" % (a, b) ... >>> class MyClass: ... operator = staticmethod(mypow) ... >>> MyClass().operator(2, 4) '2 ** 4' >>> Peter From dygimailNo at SPAMpoczta.fm Fri May 14 09:46:46 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 14 May 2004 13:46:46 GMT Subject: Loop and the list Message-ID: Hi all Have got a big problem. This is my code: -----BEGIN #stale programowe G = 6.67E-11 Mz = 6E+24 Rz = 6.37E+6 TX = range(10,780,2) TY = [] def skoknatezenia(ilpkt): "Oblicza skok" dr = ((2*Rz)-Rz)/ilpkt return dr def natezeniep(TX,TY,dr): "Liczy natezenie w przedziale " cnt = 0 for i in range(0,2*Rz,dr): TY.append((G*Mz)/((Rz+cnt)*(Rz+cnt))) cnt = cnt + dr return TY def maxvalue(TY): #gets an index of the max value in the TY list max = 0 for i in range(0,len(TY)): if (max True: try: Koniec2 = False while Koniec2 <> True: ilpkt = raw_input("Podaj ilosc punktow do wykreslenia 200):\t") try: int(ilpkt) ilpkt = int(ilpkt) Koniec2 = True except: print "Ilosc punktow musi byc liczba calkowita!\t" continue Koniec = True except: print "Nieoczekiwany blad. Sprobuj jeszcze raz." dr = skoknatezenia(ilpkt) TY = natezeniep(TX,TY,dr) print TY #first main point max = maxvalue(TY) print "max =",max TY = normowanie(TY) #normalize the function print TY -----END I don't understand why function maxvalue returns "9". When i start a program and check TY list in 'first main point', the max value has an index 0'. Then putting the list into the function maxvalue, gives me the index '9'. ;--/ Where is the mistake? ps Apologise for the Polish text's, in the code. I'll answer for any question. -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From fgeiger at datec.at Mon May 3 02:24:10 2004 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 3 May 2004 08:24:10 +0200 Subject: PyOpenGL demo in wxPython demo crashes Message-ID: Hi all, I wanted to look at the PyOpenGL demo in the wxPython demo, but had no luck: "Runtime Error Program: C:\...\pythonw.exe abnormal program termination" Has anyone overcome this problem? Many thanks in advance and best regards Franz GEIGER P.S.: Python 2.3.2 on Win2k, wxPython 2.4.2.4u, PyOpenGL (from PyOpenGL-2.0.1.07.py2.3-numpy23.exe), glut.dll (from GLUT 3.7.6) copied into \WINNT\System32. From mail.admin at williamsf1.com Sun May 9 16:36:20 2004 From: mail.admin at williamsf1.com (mail.admin at williamsf1.com) Date: Sun, 09 May 2004 21:36:20 +0100 Subject: Virus Alert Message-ID: <200405092036.i49KaKg19998@viruswall.williams.co.uk> The mail message (file: Textfile.zip) you sent to personnel at williamsf1.com \\ contains a virus. (on viruswall.williams.co.uk) From rcs at occs.cs.oberlin.edu Sat May 8 08:36:46 2004 From: rcs at occs.cs.oberlin.edu (rcs at occs.cs.oberlin.edu) Date: Sat, 08 May 2004 12:36:46 +0000 Subject: Python-list, How do they sa-ck those c0c.k-s? In-Reply-To: References: Message-ID: <17AE9386BF429BB5@occs.cs.oberlin.edu> Looks like you've come to a real Z00 here! Yeap! We have goats, we have horses, sheep, snakes, even dogs! e have lots of @n1m at ls here and we also have lots of g1r|s who just love to have some s. e -x with these creatures? How do they do it? http://zoo-action.com/av/val/?uFabl How do they sa-ck those c0c.k-s? How do they f at kk with snakes? Snakes don't have c0c.k-s!!! Guys! Our g1r|s can do it with every creature they want! They are ready for it! They are tired from men! They do realize that wild @n1m at ls are f at kking like no man would ever f at kk them. Cause they are animals and they f at kk just like everybody did thousands and millions years ago! http://zoo-action.com/av/val/?dTQQm Stunning 1ma-.ges, v1de0s, art series, lots of @n1m at ls, y0.u-n.g horny g1r|s spre at d1ng their legs and s at kking c0c-k.s! This is a first ever -X-.-X-.-X- zoo where every g1r| can f at kk the creature she wants! LOOK AT THIS NOW! uAdWbjpW GrhKtTttI From __peter__ at web.de Mon May 17 16:58:11 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 May 2004 22:58:11 +0200 Subject: Cache a large list to disk References: <939f49f8.0405171155.1de74c2a@posting.google.com> Message-ID: Chris wrote: > week, so I can safely cache this data to a big file on disk, and read > out of this big file -- rather than having to read about 10,000 files > -- when the program is loaded. > > Now, if this were C I'd know how to do this in a pretty > straightforward manner. But being new to Python, I don't know how I > can (hopefully easily) write this data to a file, and then read it out > into memory on subsequent launches. Have a look at pickle: >>> data = [{'el2': 0, 'el3': 0, 'el1': 0, 'el4': 0, 'el5': 0}, ... {'el2': 15, 'el3': 21, 'el1': 9, 'el4': 33, 'el5': 51}, ... {'el2': 35, 'el3': 49, 'el1': 21, 'el4': 77, 'el5': 119}, ... {'el2': 45, 'el3': 63, 'el1': 27, 'el4': 99, 'el5': 153}] >>> >>> import cPickle as pickle # cPickle is pickle implemented in C >>> pickle.dump(data, file("tmp.pickle", "w")) >>> data_reloaded = pickle.load(file("tmp.pickle")) >>> data_reloaded == data, data_reloaded is data (True, False) >>> data_reloaded [{'el2': 0, 'el3': 0, 'el1': 0, 'el4': 0, 'el5': 0}, {'el2': 15, 'el 3': 21, 'el1': 9, 'el4': 33, 'el5': 51}, {'el2': 35, 'el3': 49, 'el1 ': 21, 'el4': 77, 'el5': 119}, {'el2': 45, 'el3': 63, 'el1': 27, 'el 4': 99, 'el5': 153}] Peter From sridharinfinity at yahoo.com Mon May 3 06:11:20 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 3 May 2004 03:11:20 -0700 Subject: Path ... where is my application's home dir? References: Message-ID: <930ba99a.0405030211.74f33817@posting.google.com> Marco Aschwanden wrote in message news:... > On Wed, 28 Apr 2004 14:44:30 +0100, Tim Golden > wrote: > But I still wonder: Suppose sys.argv[0] wouldn't work. What would be the > easiest way to find out where an application lies? Yes. See `__file__` attribute of your application module. Also have a look at the module `inspect`. > > Ideas: > 1. going through sys.path and checking whether the application file is in > a dir > 2. or is there a module method, that tells you where it is stored? > > Thanks for "help", > Marco BTW, don't forget distutils. From jens-nospam at t-online.de Tue May 25 12:17:53 2004 From: jens-nospam at t-online.de (Jens Lippmann) Date: Tue, 25 May 2004 18:17:53 +0200 Subject: Slice assignment for strings? Message-ID: Hi all! I'm new to Python and just tried to assign values to a portion of a string, but I don't get it. My code is: bits = '\3ff' * bmi.bmiHeader.biSizeImage ofs = 0x1E2C0 for i in range(0, height): bits[i*linesize:(i+1)*linesize] = self.shbits[ofs:ofs+width/2] which leads to ... TypeError: object doesn't support slice assignment 'bits' is a binary string resp. an array of byte so to say. Note also that the right slice is shorter than the left one. So, my questions are: - How do I get it right? - If slicing seems to be the favorite way to address substrings, why is it impossible to use it on a left side of an assignment? kind regards Jens Lippmann From http Sat May 15 12:01:44 2004 From: http (Paul Rubin) Date: 15 May 2004 09:01:44 -0700 Subject: web security question. References: Message-ID: <7xekplsmqf.fsf@ruckus.brouhaha.com> pxlpluker writes: > I have a friend that was using formmail.pl until last weekend when it > was hacked by spammers with a buffer overflow attack on one of the > form fields. What makes you think it was a buffer overflow bug? formmail.pl is notorious for having security bugs, but none have been buffer overflows as far as I know. Are you sure it wasn't some other kind of bug? From duncan-news at grisby.org Fri May 7 05:52:00 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 07 May 2004 11:52:00 +0200 Subject: zodb troubles - seeking advice for app design References: <2fuolnF2h9qbU1@uni-berlin.de> Message-ID: In article <2fuolnF2h9qbU1 at uni-berlin.de>, Diez B. Roggisch wrote: >Everything works fine - in a single threaded app. But under load, the >omniorb will dispatch the incoming calls on several worker threads. zodb >requires that for each thread a separate connection has to be used. I'm not >sure how bad sharing the connection would be, but can imagine that this >isn't the best idea.... > >Now my problem is that the data object instances are separate for each >connection. So changes made in one thread aren't reflected in the instances >of other threads. If you want to stick with zodb, one option is to use a POA with the main thread model threading policy. That will dispatch all calls with the main thread, so your access to zodb will be single threaded. Of course, that will kill the performance gain you would have had from the threads. If you're not set on zodb, another option is to use Berkeley DB. That works very nicely in a multi-threaded environment with omniORB. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From segphault at sbcglobal.net Sat May 22 22:00:04 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sun, 23 May 2004 02:00:04 GMT Subject: Server/OS/Dev environment References: Message-ID: On Sat, 22 May 2004 09:16:40 -0700, Jean wrote: > Pm wrote in message news: >> Varietas delectat, Jean. ;) >> I suggest you spend a little time on exploring these and then >> you'll find out what you like best. (It's just like about girls: it'd be >> awful if every guy would prefer the same looks...) >> >> To add to you confusion, maybe have a look at Zope as well (www.zope.org) >> :-)) >> Or how about Webware? (http://webware.sourceforge.net/) Or Albatross? >> (http://www.object-craft.com.au/projects/albatross/) >> >> Best, >> Pm > > Ok. Great, Miklos. Thanks a lot! ;) > > Really, there are 2 items I need. Nice environment for rapid dev and > keeping codes clean. Of course, over a period of time, I will develop > my own taste. For now, though, I need to start a real project which > will double as a learning experience. I don't want to start down the > wrong path, then have to change course 3-4 months down the line. > > So, what's your "current" setup & why do you like it? > > Regards, > Jean zope is like the panacea for an illness that nobody has, but everybody has symptoms of. Zope is incredibly impressive, incredibly powerful, it does everything, it is brilliantly designed, but it requires immense amounts of time and patience to figure out how to employ it effectively, and customizing it to fit your needs will usually take more time than it would take to construct something from scratch. There are, however, numerous content management engines constructed on top of zope that fit more specific needs, and can be customized for what you want with relatively little sweat/blood. Plone is an excellent example. If you can find a Zope product that fits your needs, use it, but if you cant, you probably dont want to invest the time it would take to make one yourself. (i'm sure you have figured that out if you have glanced at the zope documentation yourself.) mod_python is great! I have had quite a bit of success using mod_python and some xml/xsl related python libraries. I like to use xml and xslt for my templating. I put python code in my xml files, and use a little pre-processor I threw together to process it. You might want to check out http://sqlobject.org/ which makes database access, construction, and manipulation a lot more pythonic. If you need an extendable web application framework (for writing client/server apps etc) you might want to check out the Twistd framework. As far as development environments are concerned, you have many excellent choices. I use a version of VIM that has a python interpreter compiled into it. There are a lot of graphical IDEs with graphical debuggers etc, for those who dont dig the 'home-rolled' environment thing- I use Eric3 when I need a graphical debugger, but it is also an excellent editor. Eric3 has a built in project manager and class browser as well, so it helps with those slightly bigger projects. If you are using somebody else's server make sure that it has the right modules, and make sure that it has a relatively up-to-date version of python (unless you enjoy not using the nice new features). Many hosting services are willing to add modules and perform updates if you ask them nicely. Good luck with your project! --SegPhault From paul at boddie.net Wed May 5 12:34:02 2004 From: paul at boddie.net (Paul Boddie) Date: 5 May 2004 09:34:02 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: <109gh8ml6lo6o7b@news.supernews.com> Message-ID: <23891c90.0405050834.20529152@posting.google.com> Peter Hansen wrote in message news:... > > Clearly the example presented (for function.sort.php) is > an extreme exception to that rule then, containing as it > does user-contributed, uh, "assistance" dating back to March > of 2000... It looks like a cross between a man page for a UNIX function that either never really got standardised across System V, BSD and umpteen other variants, or got overstandardised (hence the proliferation of sort functions), combined with a developer's cookbook (eg. the O'Reilly Python cookbook) but with less Reilly and more "Oh?". Paul From gregory_a_bakken at groton.pfizer.com Wed May 12 13:10:11 2004 From: gregory_a_bakken at groton.pfizer.com (Bakken, Gregory A) Date: Wed, 12 May 2004 13:10:11 -0400 Subject: zlib and gzip Message-ID: <75FBD3E83B69D711A9E600080261980C051B3ED6@groexmb04bak.pfizer.com> The short answer is I don't know. The longer answer is that I really don't know the driving force behind the compression/encoding that is being used. What I am doing is a more downstream process (so I am stuck with the chosen scheme). -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 1:04 PM To: Greg Bakken; python-list at python.org Subject: RE: zlib and gzip Silly questions first: Is it just a matter of 72 column-bounding to make it email-compliant? (keep in mind I haven't run your sample code yet, I'm sitting here perusing while on a conference call - meetings suck!!!) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Greg Bakken Sent: Wednesday, May 12, 2004 12:57 PM To: python-list at python.org Subject: zlib and gzip I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg -- http://mail.python.org/mailman/listinfo/python-list LEGAL NOTICE Unless expressly stated otherwise, this message is confidential and may be privileged. It is intended for the addressee(s) only. Access to this E-mail by anyone else is unauthorized. If you are not an addressee, any disclosure or copying of the contents of this E-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. If you are not an addressee, please inform the sender immediately. From __peter__ at web.de Thu May 27 01:31:52 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2004 07:31:52 +0200 Subject: Two questions about efficiency References: Message-ID: Steve M wrote: [two implementations of dictionary with default value] > I am interested in his claim that the second version is less efficient > unless the requested key is "almost never" in the dictionary. I would > have thought that the overhead to do a key lookup is quite a bit less > than the overhead required to create an exception object, so that the > first version would be on average more efficient only if the requested > key is in the dictionary, say, more than half the time. > > Does the "key in dict" test internally raise an exception on failure, > thus incurring at least the same overhead as the first version? Or is > the overhead to raise an exception much less than I have naively > supposed? Thinking/believing is definitely the wrong approach here. Python ships with the nice little script timeit.py that let's you verify your assumptions. class DictBase(dict): def __init__(self, default, *args, **kw): dict.__init__(self, *args, **kw) self.default = default class DictTry(DictBase): def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.default class DictIn(DictBase): def __getitem__(self, key): if key in self: return dict.__getitem__(self, key) else: return self.default class DictGet(DictBase): def __getitem__(self, key): return self.get(key, self.default) items = "hit alpha beta gamma delta epsilon zeta eta theta iota kappa".split() items = zip(items, map(str.upper, items)) dictTry = DictTry(None, items) dictIn = DictIn(None, items) dictGet = DictGet(None, items) $ timeit.py -s"from dicttime import dictTry as d" "d['hit']" 100000 loops, best of 3: 2.22 usec per loop $ timeit.py -s"from dicttime import dictTry as d" "d['miss']" 100000 loops, best of 3: 11.2 usec per loop $ timeit.py -s"from dicttime import dictIn as d" "d['hit']" 100000 loops, best of 3: 2.39 usec per loop $ timeit.py -s"from dicttime import dictIn as d" "d['miss']" 1000000 loops, best of 3: 1.49 usec per loop $ timeit.py -s"from dicttime import dictGet as d" "d['hit']" 100000 loops, best of 3: 2.11 usec per loop $ timeit.py -s"from dicttime import dictGet as d" "d['miss']" 100000 loops, best of 3: 2.03 usec per loop Two results stand out: misses are cheap for DictIn and expensive for DictTry. Peter From pxlpluker at cfl.rr.com Tue May 25 21:50:44 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Tue, 25 May 2004 21:50:44 -0400 Subject: Orlando Florida-python users group Message-ID: <40B3F7F4.8090608@cfl.rr.com> Orlando Florida-python users group. there isn't one. anyone want to start one ? From noamr at correctme.users.sourcephorge.net Fri May 21 11:22:31 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Fri, 21 May 2004 18:22:31 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2004-05-21, Noam Raphael wrote: > > >>Many times I find myself asking for a slice of a specific length, and >>writing something like l[12345:12345+10]. > > > [...] > > >>Wouldn't it be nice if the Python grammar had supported this frequent >>use? My idea is that the expression above might be expressed as >>l[12345:>10]. > > > It's a bit less efficient, but you can currently spell that as > > l[12345:][:10] > That is true, but if the list is long, it's *much* less efficient. Thanks for your comment, Noam From joewong at mango.cc Wed May 26 22:32:54 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 27 May 2004 10:32:54 +0800 Subject: how to terminate a process on win32? References: Message-ID: <013301c44392$eaa2a3b0$7f00a8c0@scl01.siliconcreation.com> But calling TerminateProcess will stop the application right away. I need someway that the process being killed get notified and thus to carry out some procedure before shut down. On Linux, I can use kill(pid, signum) to achive this but on windows? ----- Original Message ----- From: "Myles" Newsgroups: comp.lang.python To: Sent: Wednesday, May 26, 2004 9:49 AM Subject: Re: how to terminate a process on win32? > "Joe Wong" wrote in message news:... > > > os.popen2() to start my daemon, I can't figure out a way to stop it > > 'nicely'... Is there anything that I can do? > > Mark Hammond's Python for Windows extensions includes a demonstration > of killing processes on Windows: > > On my PC: > C:\Python23\Lib\site-packages\win32\scripts\killProcName.py > > Python for Windows extensions: > http://starship.python.net/crew/mhammond/ > https://sourceforge.net/projects/pywin32/ > > Regards, Myles. > -- > http://mail.python.org/mailman/listinfo/python-list > From wweston at att.net Thu May 27 19:20:08 2004 From: wweston at att.net (wes weston) Date: Thu, 27 May 2004 23:20:08 GMT Subject: MySQLdb returns "ValueError: invalid literal for float():" for cursor.execute('show databases') In-Reply-To: References: Message-ID: Tim Williams wrote: > I'm trying to write a simple python program to access a MySQL > database. I'm having a problem with using MySQLdb to get the results > of a SQL command in a cursor. Sometimes the cursor.execute works, > sometimes not. > > From mysql: > > mysql> show databases; > +-----------+ > | Database | > +-----------+ > | menagerie | > | test | > +-----------+ > 2 rows in set (0.09 sec) > > > This is the database that comes with the MySQL tutorial. I'm trying > to keep things simple here. > > When I try the same thing in Python 2.3.2 using MySQLdb I get: > > Python 2.3.2 (#6, Dec 10 2003, 08:44:50) > [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import MySQLdb >>>>db=MySQLdb.connect(unix_socket='/tmp/mysql.sock') >>>>c=db.cursor() >>>>c.execute('show databases') > > Traceback (most recent call last): > File "", line 1, in ? > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 95, in execute > return self._execute(query, args) > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 114, in _execute > self.errorhandler(self, exc, value) > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/connections.py", > line 33, in defaulterrorhandler > raise errorclass, errorvalue > ValueError: invalid literal for float(): menagerie > > > It seems that if I do a c.fetchall(), I can at least do c.execute > every *other* time: > > >>>>c.fetchall() > > Traceback (most recent call last): > File "", line 1, in ? > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 274, in fetchall > self._check_executed() > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 53, in _check_executed > self.errorhandler(self, ProgrammingError, "execute() first") > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/connections.py", > line 33, in defaulterrorhandler > raise errorclass, errorvalue > _mysql_exceptions.ProgrammingError: execute() first > >>>>c.execute('show databases') > > 2L > >>>>c.execute('show databases') > > Traceback (most recent call last): > File "", line 1, in ? > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 95, in execute > return self._execute(query, args) > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/cursors.py", > line 114, in _execute > self.errorhandler(self, exc, value) > File "/project/c4i/Users_Share/williams/Linux/lib/python2.3/site-packages/MySQLdb/connections.py", > line 33, in defaulterrorhandler > raise errorclass, errorvalue > ValueError: invalid literal for float(): menagerie > >>>>c.execute('show databases') > > 2L > >>>>c.fetchall() > > (('menagerie',), ('test',)) > > > Thanks in advance for any help. > > ---- > Tim Williams Tim, I tried this code and, as you can see, it worked: import MySQLdb db = MySQLdb.connect(user="wes", passwd="?????",db="PortfolioMySql",port=3306,unix_socket="/tmp/mysql.sock") cursor= db.cursor() sql = "show databases" cursor.execute(sql) while 1: t = cursor.fetchone() if not t: break print t cursor.close() db.close() >>> ('PortfolioMySql',) ('mysql',) ('test',) >>> wes From michael at foord.net Wed May 26 10:32:44 2004 From: michael at foord.net (Fuzzyman) Date: 26 May 2004 07:32:44 -0700 Subject: r'\' - python parser bug? References: <8089854e.0405252339.18e0c59d@posting.google.com> Message-ID: <8089854e.0405260632.2f4367fc@posting.google.com> Duncan Booth wrote in message news:... > michael at foord.net (Fuzzyman) wrote in > news:8089854e.0405252339.18e0c59d at posting.google.com: > > >>>> print r'c:\subdir\' > SyntaxError: EOL while scanning single-quoted string > >>>> > > >> When the parser sees a backslash inside > >> a string literal, it always skips the next character. > > In the above example the parser *only* skips the next character if it > > is at the end of the string... surely illogical. The reason given is > > effectively 'raw strings were created for regular expressions, so it > > doesn't matter if the behaviour is illogical' (and precludes other > > reasonable uses!!).......... > > > > In a python string, backslash is an escape character which gives the next > character(s) special meaning, so '\n' is a single newline character. If the > escaped character isn't a known escape then the parser simply passes > through the entire sequence. So '\s' is a two character string. In all > cases at least one character following the backslash is parsed when the > backslash is encountered, and this character can never form part of the > string terminator. > > Raw strings are processed in exactly the same way as normal strings, except > that no escape sequences are recognised, however the character following > the backslash is still prevented from terminating the string, just as it > would in any other string. This *useful*? behaviour allows you to put > single and double quotes into a raw string provided that they are preceded > by a backslash. > > print r'c:\subdir\'file' > > Raw strings aren't intended for writing DOS pathnames, they are actually > targetted for regular expressions where this behaviour makes more sense. > [snip..] Yeah.. that's not an annoying feature.... I mean no-one would ever want to use strings to hold Windows pathnames in...... Regards, Fuzzy From p at ulmcnett.com Thu May 13 14:47:25 2004 From: p at ulmcnett.com (Paul McNett) Date: Thu, 13 May 2004 11:47:25 -0700 Subject: ANN: Dabo 3-tier desktop framework for data-aware apps ERROR In-Reply-To: References: <200405120653.00578.p@ulmcnett.com> Message-ID: <200405131147.25658.p@ulmcnett.com> Andreas Kaiser writes: > What's wrong? > > Python 2.3.3 > WinXP Home SP1 > wxWindows 2.4.2.4u Sorry, lack of documentation. Dabo requires wxPython 2.5. Since I'm at it, here is a short list of the things you'll need to run the Dabo demos: Python 2.3 or higher wxPython 2.5 or higher MySQLdb 0.93a or higher -- Paul From __peter__ at web.de Fri May 28 12:05:37 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2004 18:05:37 +0200 Subject: Module calling-newbie question References: Message-ID: Roland Hedberg wrote: > Hi! > > I'm having problems with using modules. I'lls start with the error as it > is presented: > > Exception in Tree control callback > Traceback (most recent call last): > File "/local/develop/apacheadmin/Tree.py", line 427, in PVT_set_state > self.widget.get_contents_callback(self) > File "sexptree.py", line 11, in getelements > for element in spo.sublist(node): > File "/local/develop/apacheadmin/sexp.py", line 103, in sublist > ss = string.split( subspec, "/" ) > File "/usr/local/lib/python2.3/string.py", line 121, in split > return s.split(sep, maxsplit) > > I using the tkinter based Tree.py module Charles E. "Gene" Cash and have > built one module sexp.py which among other things tries to split a > string. Really nothing fancy but it fails when the sexp module is used > by a python program sexptree.py (also by me). > > Sexp.py as well as sexptree.py imports string. > > What more can I do ?? > What am I doing wrong ?? You could throw in a print repr(subspec) statement above ss = string.split(subspec, "/") # ss = subspec.split("/") in current Python to verify that subspec is really a string. Peter From andrew-pythonlist at puzzling.org Mon May 24 11:15:18 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 25 May 2004 01:15:18 +1000 Subject: Jabber in Twisted In-Reply-To: References: Message-ID: <20040524151518.GK1081@frobozz> On Mon, May 24, 2004 at 04:42:46PM +0200, Rico Huijbers wrote: [...] > > Yes, I saw that, but since I find it easier to post to and read > newsgroups, and I already saw a couple of Twisted-related threads in > here, I figured I'd try here first. There's always the gmane gateway: nntp://news.gmane.org/gmane.comp.python.twisted -Andrew. From grante at visi.com Sun May 16 12:24:09 2004 From: grante at visi.com (Grant Edwards) Date: 16 May 2004 16:24:09 GMT Subject: book on wxPython? References: <40a5a851$0$8512$a18e6209@newsreader.visi.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> Message-ID: <40a795a9$0$8508$a18e6209@newsreader.visi.com> In article , Andreas Kostyrka wrote: >>> Ok, now add printing, drag and drop and comboboxes. >> >> No thanks. I don't do printing or drag and drop. Or >> comboboxes now that I think about it. My needs are fairly >> simple, and Tkinter would suffice nicely, except that the >> non-native look and feel seems to confuse Windows users. > That's the price you pay for having a nice API For some values of nice. :) > that is implemented without "native" widgets. wxWindows (and > wxPython upon it) is "more complicated" because it has to deal > with a number of native implementations. By the way, wxWindows > does a API model that is relativly close to Windows > developement ;) Well I've never done Windows development (by "Windows" I assume you mean MS), so that may explain some of my bewilderment. -- Grant Edwards grante Yow! YOW!!! I am having at fun!!! visi.com From jfabiani at yolo.com Sun May 9 21:06:08 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 10 May 2004 01:06:08 GMT Subject: newbie question - remove a module from ram Message-ID: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> Hi, I believe I have good understanding of import but it occurred to me that I might want to remove an imported module. I.e I load a module into ram and I no longer need the module. Modules just stays in ram? In the windows world I would "thisform.release()" and the garbage collector would release the ram. So did I miss something or is there no release method. How about a method within a class like destroy()? I just got to believe it's there???? But where? John From joewong at mango.cc Wed May 19 06:36:40 2004 From: joewong at mango.cc (Joe Wong) Date: Wed, 19 May 2004 18:36:40 +0800 Subject: unique number generator Message-ID: <008d01c43d8d$2c301c10$7f00a8c0@scl01.siliconcreation.com> Hi, I need to implement a unique number generator that 1 or more processes on same or different machines will make use of it. Is there any library / project available already for this? Thanks in advance, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: From dlissett0 at yahoo.com Fri May 14 18:14:16 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 14 May 2004 15:14:16 -0700 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> <6748553f.0405130815.4a69cc84@posting.google.com> Message-ID: <6748553f.0405141414.2efa1aa1@posting.google.com> Jack Diederich wrote in message news:... > I would leave python and some other languages out of the comparison. > You can do near line-for-line translations for languages in the same class > - say C++ and Java, or Assembly and C. Requiring the python/perl/ruby > versions to look like a C++ program just measures how badly C++ maps to > Python, and not much else. There's no requirement that Python versions look like a C++ program. Peter Hansen chose to write a Python version closely based on the C implementation. I've now replaced that with a faster version initially based on a Smalltalk OO implementation. -snip- > Writing benchmarks is just hard, if you allow people to solve the problem > in whatever way they like you end up measuring how good a coder the > language A guy is compared to the language B submitter. Maybe the hardest thing about benchmarks is keeping some perspective on what they might and might not mean ;-) Yes, the fine performance of the BCPL interpreter implementation (and the C implementation) has a lot to do with programmer skill. But I'm not that sure about the other versions ;-) From insert at spam.here Mon May 24 13:21:55 2004 From: insert at spam.here (Doug Holton) Date: Mon, 24 May 2004 12:21:55 -0500 Subject: ANN: Pyrex wrapper for the Aspell API In-Reply-To: <40b1ff18_3@news.unc.edu> References: <40b1ff18_3@news.unc.edu> Message-ID: <1c6dnV3--rqvsi_dRVn-vw@comcast.com> Gary Bishop wrote: > To get this to build and work on Windows I downloaded the Windows > version of aspell from http://aspell.net/win32/. I got the Full > Installer, a dictionary, and the libraries for MS VisualC++ as > separate downloads. I let the first two go to their default locations > and I unpacked the zip file for the last into the C:\Program > Files\Aspell top directory. Then I copied the aspell-15.dll from > C:\Program Files\Aspell\bin to a folder on my path. > > You will also, of course, need Pyrex from > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/. > > With the above completed the standard 'python setup.py install' should > build and install the extension. If you use distutils with pyrex then others won't have to download, install and setup Aspell, MS Visual C++, or Pyrex to use your module. http://ldots.org/pyrex-guide/2-compiling.html#distutils http://www.python.org/doc/current/dist/ From ville at spammers.com Mon May 17 05:44:41 2004 From: ville at spammers.com (Ville Vainio) Date: 17 May 2004 12:44:41 +0300 Subject: OPC Server in Python References: Message-ID: >>>>> "Geiger" == F GEIGER writes: Geiger> Could I do this in Python too? At the core an OPC Server Geiger> is a COM server, isn't it? Did anyone in this group do Geiger> anything like that already? And if so, are you willing to Geiger> share your experience? I've written an OPC client (in C++), and used a Wintech OPC client library (proprietary). I kinda regret that I didn't use the OPC COM interface directly, but I didn't know enough Python at the time (and didn't have the Python for win32 book). I guess technically OPC uses DCOM, but it ought to work the same way... Geiger> Any hint welcome! OPC is rather unpleasant. Systems that use OPC should rather use CORBA, which is an open standard. Many people in automation industry seem to be rather backward in the sense that they consider Windows, COM and such things "standard" in some perverse fashion. I would expose the variables that you do in your OPC server in some more open fashion (CORBA is great w/ Python), and then implement a small wrapper application that exposes the variables to OPC clients. -- Ville Vainio http://tinyurl.com/2prnb From fedor at mailandnews.com Mon May 17 12:38:25 2004 From: fedor at mailandnews.com (Fedor) Date: Mon, 17 May 2004 18:38:25 +0200 Subject: Smalles Possible Browser to display python cgi program In-Reply-To: References: Message-ID: > I use CGIHTTPServer.py Module as a small webserver and Mozilla > Firebird as Browser. > > Does anyone know of a very small browser which I can directly > integrate. Not what you asked, but the module webbrowser uses whatever browser is available. for example: import webbrowser webbrowser.open('http://localhost') Fedor From richardjones at optushome.com.au Sun May 16 20:33:36 2004 From: richardjones at optushome.com.au (richard) Date: Mon, 17 May 2004 10:33:36 +1000 Subject: [ANN] SC-Track Roundup 0.7.2 - an issue tracking system Message-ID: <40a80860$0$31679$afc38c87@news.optusnet.com.au> This maintenance release fixes some bugs in the 0.7 release of Roundup: - anydbm sorting with None values (sf bug 952853) - roundup-server -g option not recognised (sf bug 952310) - HTML templating isset() inverted (sf bug 951779) - otks manager missing (sf bug 952931) - mention DEFAULT_TIMEZONE requirement in upgrading doc (sf bug 952932) - fix DateHTMLProperty so local() can override user timezone (sf bug 953678) - fix anydbm sort/group direction handling, and make RDBMS sort/group use Link'ed "order" properties (sf bug 953148) - fix Interval editing (sf bug 954891) Known issues: - the metakit import feature currently has a bug and should not be used If you're upgrading from an older version of Roundup you *must* follow the "Software Upgrade" guidelines given in the maintenance documentation. Roundup requires python 2.1.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: python demo.py Source and documentation is available at the website: http://roundup.sourceforge.net/ Release Info (via download page): http://sourceforge.net/projects/roundup Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup ============= Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry "Track" design competition. Roundup manages a number of issues (with flexible properties such as "description", "priority", and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable "out of the box" with any python 2.1+ installation. It doesn't even need to be "installed" to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and seven database back-ends (anydbm, bsddb, bsddb3, sqlite, metakit, mysql and postgresql). From me at privacy.net Sat May 8 08:55:54 2004 From: me at privacy.net (Heather Coppersmith) Date: 08 May 2004 08:55:54 -0400 Subject: Preferences Files References: Message-ID: On Sat, 08 May 2004 11:53:34 GMT, Mark Fairchild wrote: > Is there a good preferences modules for Python? I know that the > Mac version has one, but I need something cross-platform. There are lots of them. I've had good luck with the standard ConfigParser module; YMMV. > I just started my first Python project, and I'm used to Java. > The java.util.logging package of the JDK is an amazing resource, > and I was pretty surprised when the Python documentation didn't > mention any similar module for Python. Given that Python API > has almost EVERYTHING that the Java API does and more, I'm sure > there must be something like the Java logging module. I don't know what the java.util.logging package does, but recent Pythons come with a Logging module, which has a suspiciously similar name. > Learn Lisp today! Uncle Turing wants you! I learned Lisp a while ago; it truly expanded the number of ways I can think about solving a problem and organizing a program. See also . Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From mcfletch at rogers.com Mon May 3 09:21:37 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 03 May 2004 09:21:37 -0400 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: References: Message-ID: <40964761.7030106@rogers.com> Try installing Numarray. When the 2.0.1.07 binary was built the packager had Numarray installed, and for some god-unknown (and frustrating) reason just having the package installed appears to create a (pointless extra) dependency on Numarray when you link to Numpy. Everything else sounds fine, Mike Peter Hansen wrote: > F. GEIGER wrote: > ... >> P.S.: Python 2.3.2 on Win2k, wxPython 2.4.2.4u, PyOpenGL (from >> PyOpenGL-2.0.1.07.py2.3-numpy23.exe), glut.dll (from GLUT 3.7.6) >> copied into >> \WINNT\System32. > ... _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From SeeBelow at SeeBelow.Nut Wed May 5 23:20:35 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Thu, 06 May 2004 03:20:35 GMT Subject: question: parameters for create_polygon() method References: <40984D5A.B819BF28@shaw.ca> <40986DD6.F06FF651@shaw.ca> Message-ID: <4099AF0C.85717026@shaw.ca> Peter Otten wrote: > I just tried it - it may not be in the docs, but it does work. > For example > > import Tkinter as tk > root = tk.Tk() > canvas = tk.Canvas(root) > canvas.pack() > points = [(20, 20), (50, 150), (200, 50)] > > canvas.create_polygon(fill="blue", *points) > root.mainloop() > > will draw a blue triangle. Surprisingly, it works! I tested it also. It never occurred to me to simply try the list of tuples in place of the normal arguments as explained in the docs. I just assumed that the docs were the full story. Yours is the best suggestion. The suggestion about a flatten() function is also a good one, but it turns out not to be needed. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From peter at engcorp.com Thu May 27 10:40:05 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 May 2004 10:40:05 -0400 Subject: Best way to enumerate something in python In-Reply-To: References: Message-ID: David Stockwell wrote: > FWIW this is what I'm going to do for enumerated types in python. Its > not perfect but it will make it fairly easy to get at column names so I > can build SQL statements on the fly and still have fairly easy to > maintain code > > #setup stuff > NAME_COL, ADDRESS_COL, CITY_COL, ZIPCODE_COL, \ > STATE_COL, COUNTRY_COL, SS_COL, CAT_COL, \ > DATE_COL, SALARY_COL = range(10) > > mycol = { > NAME_COL: " NAME ", ADDRESS_COL: " ADDRESS ", > CITY_COL: " CITY ", ZIPCODE_COL: " ZIPCODE ", > STATE_COL:" STATE ", COUNTRY_COL: " COUNTRY ", > SS_COL: " SS ", CAT_COL: " CAT ", > DATE_COL: " DATE ", SALARY_COL: " SALARY " } > # Use these for indexing by column name Any time you see a pattern of repetition like this, you can make improvements, at least with Python if not some other languages. If nothing else, this will generally vastly improve maintainability, and often readability as well. >>> cols = 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' >>> mycol = {} >>> for i,col in enumerate(cols.split()): ... globals()[col + '_COL'] = i ... mycol[i] = ' %s ' % col ... >>> dir() ['ADDRESS_COL', 'CAT_COL', 'CITY_COL', 'COUNTRY_COL', 'DATE_COL', 'NAME_COL', 'SALARY_COL', 'SS_COL', 'STATE_COL', 'ZIPCODE_COL', '__builtins__', '__doc__', '__name__', 'col', 'cols', 'enum', 'i', 'mycol'] >>> mycol[CITY_COL] ' CITY ' -Peter From rogerb at rogerbinns.com Tue May 25 14:20:36 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 25 May 2004 11:20:36 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: Mark Hahn wrote: > Roger Binns wrote: > > > In addition to all the excellent notes from Paul, I would recommend > > you consult with someone familiar with the locale and encoding > > issues for Hebrew, Arabic and various oriental languages such > > as Japanese, Korean, Vietnamese and Tibetan. Bonus points for > > Tamil :-) > > I sure hope you are kidding. If not you are scaring me away from doing > anything. You can get the design done right early, and worry about the implementation later. [ external string resource files ] > Do you mean for the interpreter or some enabling tool for the Prothon > programs? Doing this for the interpreter is on the to-do list. I mean for user programs and making it a fundamental part of the language (ie you must use it). The current model of print statements compatible with 1950's teletypes is old and busted. How about inspiration from 1960's era mainframes (or the more recent AS/400)? The AS/400 is actually an excellent example of an alternate approach. Your programs have a seperate resource that defines "screens" (think of a full display on a terminal). The resource is rich in that it can be longer than a screenfull (ie you need page down), and it defines both output fields and input fields, including validation information and type information for the fields. When the web arrived, they could instantly web enable the applications with zero changes to the application code. Similarly you could build a gui for the apps automatically as well. Taking a step back to what that could inspire in Prothon, how about making I/O richer. Instead of teletype style print, make the resource files richer. I should be able to run someones program and have it output to a teletype, a GUI, HTML, XML or whatever else becomes popular in the next ten years, without changing a line of code of the application. (Bonus points for encapsulating the command line arguments that way :-) Now you could do all this through libraries (ie as an optional part of the libraries rather than part of the language design) but the moment you do that, a lot of code won't use it, and a scheme like the above is only useful if all code uses it. Additionally the current schemes available in languages like Python is a royal pain in the butt. The language makes it hard to do. Try the following steps: - Start with a program that says "Hello, World" - Then change it to say the it in English and French - Then make it take a command line argument that accepts a name, and have it say Hello, Name (or Name, Hello depending on the locale) - Ok, now make it output HTML, XML, teletype and a gui If the language/library design is done well, each of those should add one line of code. Every language I am aware of the moment makes it take way way more than that, which leads people not to bother, which means that code randomly doesn't work with other libraries, and everything is still stuck at the lowest common denominator (printing to a teletype). Roger From shalabh at cafepy.com Mon May 31 12:52:13 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Mon, 31 May 2004 09:52:13 -0700 Subject: [].index In-Reply-To: References: Message-ID: Mike Edey wrote: > Good day. > Recently I'd run into wishing a list's index method would match > substrings. Being fairly new to this game I can't help but think that my > solution is a little, well, clumsy. In the following trivial example I'm > only interested in finding the first matching list item: > > >>>>data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo = >>>>['b','e','e'] >>>>[data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for >>>>ix in range(len(foo))] > > > ['bbb', 'eee', 'eee'] > > > So I guess this question is - have I missed a cleaner method then this > nested list comprehension? Here's an option: [s for s in data for prefix in foo if s.startswith(prefix)] Clearer to read and understand. I like to keep away from indexes and counters as much as possible. HTH, Shalabh From peter at engcorp.com Sun May 30 22:27:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 30 May 2004 22:27:31 -0400 Subject: Hexbin In-Reply-To: <40ba1ca5$0$119$3a628fcd@reader3.nntp.hccnet.nl> References: <40ba1ca5$0$119$3a628fcd@reader3.nntp.hccnet.nl> Message-ID: MaximusBrood wrote: > Im a newcomer to Python and I've got some error that I totaly dont > understand. [...] > If I run this one, an exeption is raised: > > Traceback (most recent call last): > File > "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", > line 407, in ImportFile > exec codeObj in __main__.__dict__ > File "", line 1, in ? > File "C:\WINDOWS\temp123\Stuf\all2.py", line 9, in ? > binhex.HexBin(file2, filename2) #translate hexed file 2 binary > TypeError: __init__() takes exactly 2 arguments (3 given) > > I've got only 2 arguments, but python thinks I've got there 3... Here's my quickie response, since I don't see that anyone else has tried to reply as of yet. If this doesn't do it, I can look into it further tomorrow. The definition of __init__ always looks like this: def __init__(self, ...): where ... represents zero or more arguments. Note that the "self" argument counts as one for purposes of the error message, so if it says it wants exactly two arguments, that means it really wants only one argument in addition to self. I don't know what binhex.HexBin() looks like, but it appears to be different than what you think. Taking a look at the source in python/lib/binhex.py might help you... find the __init__ method for class HexBin and you may solve your own problem once you learn what the one non-self argument is expected to be. Also checking the docs again might clear things up for you now. -Peter From hectoraranguren at hispavista.com Fri May 21 11:56:39 2004 From: hectoraranguren at hispavista.com (hector) Date: 21 May 2004 08:56:39 -0700 Subject: Python2.2 + mailbox. Bug???? Message-ID: <70c4ef5f.0405210756.187b7f07@posting.google.com> Hi This is my program: #!/usr/bin/python import sys from mailbox import PortableUnixMailbox tmp = sys.stdin mbox = PortableUnixMailbox(tmp) mbox.next() ... ... When I execute: "./program.py < mboxfile.txt", there's no problem But, if I execute: "cat mboxfile.txt | program.py" ... too bad! the error: Traceback (most recent call last): File "./prueba.py", line 8, in ? mbox.next() File "/usr/lib/python2.2/mailbox.py", line 23, in next self.fp.seek(self.seekp) IOError: [Errno 29] Illegal seek Why????? Thanks ALL!! From cookedm+news at physics.mcmaster.ca Mon May 3 23:20:18 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 03 May 2004 23:20:18 -0400 Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> <109drk3erp8cm8c@news.supernews.com> <4096F56A.F9815BA7@shaw.ca> Message-ID: At some point, SeeBelow at SeeBelow.Nut wrote: > I'm using Tkinter, creating buttons and scales. One of the buttons > should have a command option to execute a function that initializes some > class objects. These objects take a scale object as one of their > initialization parameters, So I have to create the class objects after I > create the scales. > > It seems that I must create the button that calls the initialization > function after that, or else the function assigned to the command option > is undefined. > > But I want to create the button first, so that it appears near the top > of my frame. > > I hope that's clear. Now you see why I didn't describe that in my > original post! Some actual code would make what you're trying to do clearer. Here's my guess: def stuff(master): scale1 = Scale(master) scale1.pack() scale2 = Scale(master) scale2.pack() def init_classes(scales=[scale1, scale2]): ... stuff ... button = Button(master, command=init_classes) button.pack() and what you'd like is def stuff(): # doesn't work as scale1 and scale2 haven't been assigned yet def init_classes(scales=[scale1, scale2]): ... stuff ... button = Button(master, command=init_classes) button.pack() scale1 = Scale(master) scale1.pack() scale2 = Scale(master) scale2.pack() You could use nested scopes like this: def stuff(): def init_classes(): scales = [scale1, scale2] ... stuff ... button = Button(master, command=init_classes) button.pack() scale1 = Scale(master) scale1.pack() scale2 = Scale(master) scale2.pack() Then, scale1 and scale2 aren't looked up until init_classes() is actually called, and the values are taken from the namespace of stuff(). By the time init_classes() is called, they should be assigned. Alternatively, you could move stuff() into a class, and assign scale1 and scale2 as attributes of that class. init_classes should then be a method of the class. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From none at shall.pass Sat May 15 05:14:01 2004 From: none at shall.pass (Thomas) Date: Sat, 15 May 2004 11:14:01 +0200 Subject: book on wxPython? References: Message-ID: <20040515111401.25d20607.none@shall.pass> Hi, try making a small App with Boa Constructor and look at the code afterwards just my 2 (Euro) Cents :-) Thomas From cookedm+news at physics.mcmaster.ca Tue May 4 13:48:11 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 04 May 2004 13:48:11 -0400 Subject: Growing database? References: Message-ID: At some point, Jonathon McKitrick wrote: > This might be a silly question, so I'm warning you ahead of time. > > I have a persistence database that is saving a 'month' object out with its > data. A single month pickled is about 50k. My database of shelved objects > contains 4 months of data is over 3 megs. Does the db object journal, or do > some other recordkeeping that could explain the huge size difference between > pickling to a file and pickling to a 'shelve'? Depends on what db module shelve uses for its backend. For instance, gdbm won't shrink a database file unless you specifically tell it to, so if you have a lot of deletions it will grow. Easiest way to fix it is to copy all the objects from your shelve to a new shelve. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From dmq at gain.com Tue May 11 14:06:19 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 11 May 2004 11:06:19 -0700 Subject: Unification of Methods and Functions References: Message-ID: On Tue, 11 May 2004 18:10:36 +1000, "Delaney, Timothy C (Timothy)" wrote: >Antoon Pardon wrote: > >> I'm a bit sick of this argument. There is a lot om implicity >> going on in python. if obj belongs to cls then obj.method() >> is syntactic sugar for cls.method(obj). That looks like >> a big implicite way to handle things in python. >Yes - there is a lot hidden here - but what is hidden is purely >implementation details. It should never bother the user, right? Pop Quiz: Which of the four outputs below is possible. Hints: Add a statement or two in front of these commands, then test your assumptions by running the sequence in your Python interpreter. >>> cat2 = cat1() >>> Cat.f = cat1.func >>> cat1.f = Cat.func >>> Cat.func, Cat.f, cat1.func, cat1.f A) (, , , ) B) (, , >, ) C) (, , , ) D) (, , >, >) In spite of all this, I still favor Python's implicit binding over the alternatives I have seen. To make binding really clear and explicit, you need to burden some very simple calls like cat1.method1() with extra syntax. So we pay a price on edge cases like the above, to make the normal use easy. Prothon is trying to make binding explicit, and they have a mess IMHO. This happens when you treat all possibilities as equally important, and don't exercise good judgement on what is overall the best compromise. -- Dave The one rule that trumps all others: Practicality beats purity. From peter at engcorp.com Wed May 5 06:37:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 May 2004 06:37:35 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: References: <109gh8ml6lo6o7b@news.supernews.com> Message-ID: Roger Binns wrote: >>As Andrew commented, there's nothing stopping you from >>contributing. > > Ask anyone who works on PHP. Their system is really good > and greatly helps developer productivity. The people who > work on the doc incorporate the comments into the next > doc releases and usually wipe them clean. Clearly the example presented (for function.sort.php) is an extreme exception to that rule then, containing as it does user-contributed, uh, "assistance" dating back to March of 2000... -Peter From jiba at tuxfamily.org Sat May 15 14:57:22 2004 From: jiba at tuxfamily.org (Jiba) Date: Sat, 15 May 2004 20:57:22 +0200 Subject: Paris python user group? In-Reply-To: References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: <20040515205722.2a8b396a@iceberg.banquise> ?a m'int?resse aussi !! > J'en suis ! > Y a-t-il d?j? une mailing liste ? > > "francois lepoutre" wrote in message > news:408795ee$0$25893$79c14f64 at nan-newsreader-02.noos.net... > > Hi all french speaking, Paris-based python users, > > Bonjour ? tous les utilisateurs parisiens de python, > > > > How many are we to use python in the *Paris* Area? > > Enough to build some community life? > > > > Combien sommes nous ? utiliser python sur Paris? > > Assez pour monter une assoc? > > > > Nous proposons le m?me lieu et la m?me > > formule mais nous sommes pr?ts ? discuter :) Je pr?cise que je suis v?g?tarien ; pour les moules c'est rat? mais une pizza 4 fromages m'ira parfaitement. Jiba From cm at leetspeak.org Sun May 16 07:25:02 2004 From: cm at leetspeak.org (Michael Walter) Date: Sun, 16 May 2004 13:25:02 +0200 Subject: Stackless python and microthreads In-Reply-To: <95aa1afa.0405152035.e7aa3a0@posting.google.com> References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <2gnhh0F4r098U1@uni-berlin.de> <95aa1afa.0405152035.e7aa3a0@posting.google.com> Message-ID: <2gp1ccF59macU1@uni-berlin.de> Michele Simionato wrote: > Michael Walter wrote in message news:<2gnhh0F4r098U1 at uni-berlin.de>... > >>Ville Vainio wrote: >> >>>>>>>>"Michele" == Michele Simionato writes: >>> >>> Michele> of learning Zope TAL/TALES/METAL, which I do not like >>> Michele> that much; I would rather prefer to generate HTML pages >>> Michele> with Lisp macros and use real s-expressions instead of >>> Michele> XML/HTML, but I can't :-( >>>What would you do with macros? [..] >> >>Syntactic abstraction. I would love to see macros in Python (actually >>working on some ideas for adding them to Python). > > NO!! I am really talking about prefix notation: I am pro macros when > you have prefix notations and s-expressions (i.e. HTML/XML), whereas > I am not advocating macros in Python, which has an infix notation. And my point was that I'm advocating macros in non-s-expression languages, too, as I think they are equally valuable there. > There are macro systems based on pattern matching which can work with > infix notation (I hear Dylan has one), but I feel somewhat happier with > Lisp-style macros where everything is a list. I'm pretty sure (and my experiments seem to indicate that, too) that you can have both macros defined by pattern-matching and "raw" macros which operate on the AST in Python, too. Yes, Dylan has macros, too, despite its syntax. Cheers, Michael From ronaldoussoren at mac.com Mon May 10 07:17:39 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Mon, 10 May 2004 13:17:39 +0200 Subject: MacPython applet problem In-Reply-To: <32e55451.0405100202.508aa914@posting.google.com> References: <32e55451.0405100202.508aa914@posting.google.com> Message-ID: On 10-mei-04, at 12:02, boris m wrote: > I am running Python 2.3 on Mac OS 10.3. > > My problem is that applets don't seem to work. If I run a python > script in the terminal, everything is fine. If I run the same script > as an applet, nothing happens. The applet starts up, but dies after a > second or two. > > I used applets quite frequently unter OS9 and never had a problem with > them. Has anyone any idea why applets on OS X don't work the way they > did in OS 9? There's probably a traceback or other message in the console log (Console.app). That should point you in the right direction. Ronald From faizan at jaredweb.com Fri May 14 21:29:46 2004 From: faizan at jaredweb.com (Fazer) Date: 14 May 2004 18:29:46 -0700 Subject: Retrieve Email Attachments References: <7b454334.0405131902.60550e4c@posting.google.com> <2gj794F3fd4cU1@uni-berlin.de> <2gj7b8F3fd4cU2@uni-berlin.de> Message-ID: <7b454334.0405141729.212a1af6@posting.google.com> Thanks a lot for your guide! Lutz Horn wrote in message news:<2gj7b8F3fd4cU2 at uni-berlin.de>... > Lutz Horn wrote: > > Use poplib or imaplib to get a message as a string. > > > > >>> import poplib > > >>> connection = poplib.POP3("servername") > > >>> connection.user("username") > > >>> connection.pass_("password") > > forgot: > > >>> msg_as_string = connection.get(number_of_message_on_server) > > > Then use the email module (new in 2.2) to parse this string into an > > instance of email.Messsage using > > > > >>> import email > > >>> msg = email.message_from_string(msg_as_string) > > > > Use the methods of the resulting email.Message instance to get the > > contents of the email. From dialton3#NOSPAM#.despammed at virgilio.it Sat May 15 18:29:41 2004 From: dialton3#NOSPAM#.despammed at virgilio.it (Valentino Volonghi aka Dialtone) Date: Sat, 15 May 2004 22:29:41 GMT Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> Message-ID: <87oeopl44w.fsf@vercingetorix.caesar.org> michele.simionato at poste.it (Michele Simionato) writes: > This is a most interesting reference, thanks! Incidentally, I am in the process > of learning Zope TAL/TALES/METAL, which I do not like that much; I would > rather prefer to generate HTML pages with Lisp macros and use real > s-expressions instead of XML/HTML, but I can't :-( > Lisp/Scheme is much more suitable for web applications (in principle) > than any other language I know, it is unfortunate that (in practice) it > is not that used ... Hi Michele :). If all you need is s-expr you maybe can look at Nevow (pronounced 'nuevo'), which is the new web toolkit built on top of twisted.web. It has a template syntax that is similar to ZPT. And it has stan which is an s-expr-like syntax. Here is a little helloworld example: docFactory = rend.stan( T.html[ T.head[ T.title['Hello'], ], T.body[ T.p['Welcome to the wonderful world of Nevow!'], ], ] ) More infos at www.nevow.com or in the nevow wiki: http://divmod.org/users/wiki.twistd/nevow/moin.cgi/FrontPage or in irc in #twisted.web -- Valentino Volonghi aka Dialtone Linux User #310274, Proud Gentoo User Blog: http://vvolonghi.blogspot.com Home Page: http://xoomer.virgilio.it/dialtone/ From SeeBelow at SeeBelow.Nut Tue May 4 21:55:52 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 05 May 2004 01:55:52 GMT Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> Message-ID: <409849B2.9A289994@shaw.ca> Daniel Yoo wrote: > > SeeBelow at seebelow.nut wrote: > : Must function defs appear earlier in a file than use of their name? > > : If so, is there some way around this? It's creating a puzzle for me. > > Let's work on a concrete example. Say we want to write something like > this: > > ### > print square(42) > > def square(x): > return x * x > ### > > This doesn't work, because when Python hits the 'print square(42)' > statement, it's not aware yet of what 'square' means. But there is a > way around this: > > ### > def main(): > print square(42) > > def square(x): > return x * x > > if __name__ == '__main__': > main() > ### > > Here, we enclose the main flow of our program in a function called > main(). Python doesn't evaluate a function's body until it is called, > so by the time that we hit: > > if __name__ == '__main__': > main() > > we're ok, since both main() and square() are defined. > > So to answer your question: > > : Must function defs appear earlier in a file than use of their name? > > we can allow the use to be earlier in terms of location in the source > file, by using a function definition to delay the evaluation till all > the symbols are in place. > > Hope this helps! Yes, this is good info! thanks, Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From kirk at eyegor.jobsluder.net Tue May 11 02:57:06 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Tue, 11 May 2004 06:57:06 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: On 2004-05-09, Olivier Scalbert wrote: > Hello , > > What is the python way of doing this : > perl -pi -e 's/string1/string2/' file > ? To expand on what others have said, python emphasizes readability over compactness and obscure shortcuts. The perl "-pi" idiom wraps everything around a nice ammount of code, and the "-e" idiom wraps some more code. a script that sort of has some of the same functionality would go something like this: #############start bad code################## #!/usr/local/bin/python import getopt,sys,os,re #get your command line options #files will be in optlist, args = getopt.getopt(sys.argv[1:],'e:') #do the -p loop. for filename in args: #do the -i "in place" edit. oldfilename = filename+'.bak' os.rename(filename,oldfilename) newfile = open(filename,'w') #continue the -p loop for line in open(oldfilename).readlines(): #execute all of the -e statements. for command in optlist: #warning bad mojo here foo=(command[1] % line.rstrip("\n")) exec(("line=%s" % foo)) #print line #save to the new file print line newfile.write(line + "\n") newfile.close() os.unlink(oldfilename) ############end bad code################## The above code runs, but is not very good because I'm not that familiar with exec statements. Anyway I've tried to capture what "perl -pi -e" actually does which is to execute an arbitrary command over every line of an arbitrary list of files, editing them in place, with a temporary backup copy. Then you would call it with something like: python badscript.py -e 're.sub("foo","bar","%s")' badtest.txt However this is a place where an implicit loop works great. You can just do: perl -pi -e 's/foo/bar/' filelist Or if you hate the perl/sed syntax, there is: gawk '{gsub("foo", "bar", $0); print > FILENAME}' filelist Both of these work because perl and awk have mechanisms to implicitly loop over all the lines in a file. The python way tends to avoid implicit loops except for a few cases. > Thanks > Olivier From has.temp2 at virgin.net Sun May 2 14:21:33 2004 From: has.temp2 at virgin.net (has) Date: 2 May 2004 11:21:33 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <69cbbef2.0404281050.4dc3380e@posting.google.com> <6cc20cea.0405012255.5e352d27@posting.google.com> Message-ID: <69cbbef2.0405021021.7202e995@posting.google.com> jgardner at jonathangardner.net (Jonathan Gardner) wrote in message news:<6cc20cea.0405012255.5e352d27 at posting.google.com>... > I'll admit that classless OO programming looks neat. The only thing > that I can't see an obvious way of doing is to share a value or method > across multiple objects. A couple of ways I can think of: 1. Store the value in a module-level variable. This is not so odd an idea as it seems; e.g. see Dylan as one example of a [class-based] OO language where encapsulation primarily happens at module rather than class level. My own proto-OO code is generous in its use of modules and procedures. BTW, this may work particularly well in a language that has first-class syntactic support for declaring objects, as that'll allow you to put multiple modules within a single file (and modules within those modules, and so on, if that's what you want). 2. Create a single shared object to store this value, and pop a reference to it into a slot in every object that uses it so they can access it there. If you also want this value available to the objects' clients as well as the objects themselves, you can always make that slot into a parent slot so that external requests for the value are automatically delegated to it. > Also, it kind of renders the question, "What kind of object is this?" > meaningless. There are no /kinds/ anymore, at least not built into the > language. Yep. In its purest form, a proto-OO language would have only a single 'type' - object - and no 'classes' at all. While folk who are used to relying on type/class information to make their programs work may freak a bit at the thought of this, languages like Python and Ruby have already demonstrated that 'duck typing' can work well. (Again, it's mostly just a matter of the developer having a bit of discipline in the first place than relying on the compiler to pick up their slop after the event. I actually regard this particular justification for static typing - "it helps reduce bugs" - as a physical abuse of the type system. Anyway, if I ever feel the need for strong compile-time typing I'll go learn OCaml or something else with a really smart, sophisticated type system, not C/C++/Java. Or Dylan, which'll give me best of both worlds.) > I do enjoy seeing different perspectives from other communities. It > helps me get a new perspective with my own programming. Absolutely! Personally I'm only fluent in two languages - AppleScript (my alma mater) and Python (my current development platform of choice) - but I've tinkered with a few others (a little C, Perl, JavaScript, for example), and read up on at least a dozen more (Lisp, Forth, Java, Smalltalk, Eiffel, ML/OCaml, Ruby, Dylan, HyperCard, Obj-C to pop some names off the top of my head; and various niche languages I can't even remember the names of). Often I just get a vague impression of what these languages are trying to do, particularly on my first attempt to understand them, but after a while the pieces start to slot into place and I'll maybe go read some more. Sure I'm a shallow dilletante who clearly hasn't got enough Real Work to go do with themselves, but just wait till I REALLY get started! (Which is sure to be any day now, oh yes; any day...;) From ep at epoz.org Mon May 3 05:29:48 2004 From: ep at epoz.org (Etienne Posthumus) Date: Mon, 3 May 2004 11:29:48 +0200 Subject: Tkinter and XML-RPC In-Reply-To: References: <0jZjc.65$pw1.70887@news.uswest.net> Message-ID: <6C2CE76E-9CE4-11D8-BBDC-0003935458F6@epoz.org> On Apr 29, 2004, at 7:30 AM, Roger Binns wrote: > I actually ended up using Paramiko, a Python implementation of > SSH. Hi Roger That is a good tip, very interesting. Do you mind explaining what you did further? Does your server process listen on localhost, and the client then connects via SSH to the host on which your server process is running? I was wondering how I would do it, this was one guess. Nie to know about Paramiko, it looks a little more lightweight than the SSH that comes with Twisted, if one does not want to go the whole Twisted route. Curious how much it could be sped up by using OpenSSL for the crypto operation in stead of PyCrypto. Etienne Posthumus Amsterdam, Netherlands --- Python, Zope and Quixote consulting Cultural Heritage Research From ville at spammers.com Sat May 22 07:13:15 2004 From: ville at spammers.com (Ville Vainio) Date: 22 May 2004 14:13:15 +0300 Subject: Python compilers? References: <30260531.0405180848.42e2919d@posting.google.com> <8089854e.0405210201.2a9b6de@posting.google.com> Message-ID: >>>>> "Andrew" == Andrew MacIntyre writes: >> There is also GCJ as part of the GCC, which can compile both .class >> and .java files. Its libraries aren't complete yet, but I'm sure it's >> only a matter of time. Andrew> Hmmm... anyone tried GCJ on Jython? Native code will not help much if the created native code is of type: arg=lookup(object1, "fooarg") f = lookup(object2,"foomethod") call(f,arg) For the performance that is expected of native code we need direct dispatching with the addresses of the functions known at the compile time, or via direct indexing of linear virtual tables. (I'm speaking of static compilation here - what I said may not apply to psyco) -- Ville Vainio http://tinyurl.com/2prnb From greg at cosc.canterbury.ac.nz Tue May 25 00:07:51 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 May 2004 16:07:51 +1200 Subject: Prothon should not borrow Python strings! In-Reply-To: References: Message-ID: <2hfv4nFch1lmU3@uni-berlin.de> Paul Prescod wrote: > The > result of reading a file is a binary data string. The result of parsing > an XML file is a character string. What if the file you're reading is a text file? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From hungjunglu at yahoo.com Sun May 23 04:12:31 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 23 May 2004 01:12:31 -0700 Subject: Running code on module import References: <20040521050534.21796.00001788@mb-m15.aol.com> <10av0tnnpv79c3c@news.supernews.com> Message-ID: <8ef9bea6.0405230012.371fcff0@posting.google.com> "John Roth" wrote: > Look at the built-in __import__() function, and the ihooks module. > For what you want to do, you should be able to hook __import__ > so that you get control both before and after it. He wants action performed *after* the main() is defined, not around the time of import of his runmain. So, in a sense, he wants something like a metaclass for the __main__ module. Unfortunately: (a) Python's modules are not classes, you can't intercept module features with metaclasses. (b) He wants something specified at the top module, like an "import" statement. (If the *something* were specified at the bottom, it would make things a bit easier.) At the moment, I can only think on the sys.exitfunc as a proper hook. :) It's totally esoteric/un-orthodox. But for whatever it's worth, here is one example. Since it's totally un-orthodox, do not expect it to run properly under all circumstances. (E.g.: it won't run from console, it won't run inside Pythonwin, etc.) But it does run when executed with standard shell command line. #--- demo.py import runmain x=3 def main(switches, args): if switches['print']: legend = args[0] print legend, x #--- runmain.py import sys def runmain(): args = ['The value of %s is' % sys.argv[1]] switches = {'print': 1} sys.modules['__main__'].main(switches, args) sys.exitfunc = runmain #--- command line python demo.py x #--- result The value of x is 3 -------------------------------- As I have said, it's best to do as the Romans do, when in Rome. Bite the bullet and use the "if __name__ == '__main__':" that everyone else uses. It's really not that bad looking. Any args tweaking or switches can be done at the import of a tweaking module. Seriously, something like below would do. import myparams # creates args (from sys.argv) and switches def main(): .... uses myparams.args and myparams.switches if __name__ == '__main__': main() Hung Jung From peter at engcorp.com Thu May 20 11:46:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 11:46:14 -0400 Subject: Why does the "".join(r) do this? In-Reply-To: <545cb8c2.0405200738.296bb094@posting.google.com> References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: <1O-dnXfH1_NaTzHd4p2dnA@powergate.ca> Jim Hefferon wrote: > I'm getting an error join-ing strings and wonder if someone can > explain why the function is behaving this way? If I .join in a string > that contains a high character then I get an ascii codec decoding > error. (The code below illustrates.) Why doesn't it just > concatenate? It can't just concatenate because your list contains other items which are unicode strings. Python is attempting to convert your strings to unicode strings to do the join, and it fails because your strings contain characters which don't have meaning to the default decoder. -Peter From jmcalvar at telecable.es Wed May 12 07:41:56 2004 From: jmcalvar at telecable.es (=?ISO-8859-1?Q?Jos=E9?=) Date: Wed, 12 May 2004 13:41:56 +0200 Subject: process In-Reply-To: References: Message-ID: Thank you, finally I write a pid file when rotatelogs starts, and I delete it when it stops, then with isfile() I know if the process is working. Ryan Paul escribi?: > > > > I'm not aware of any way to retrieve the process list from python, but you > might try this: > > import commands > > x = commands.getstatusoutput('ps ax|grep rotatelogs')[1] From tuure at laurinolli.net Tue May 11 17:44:39 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Wed, 12 May 2004 00:44:39 +0300 Subject: Python security settings In-Reply-To: References: Message-ID: Laughlin, Joseph V wrote: > rpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 3010)) > When I run this program, I can connect to port 3010 on the localhost, > but I can't connect to the port from any other machine (or from the > local machine using the machine's hostname). Why is this? You are binding the server to localhost, it shouldn't receive packets from any other address than 127.0.0.1 and it's IPv6 counterpart. Bind to the interface you are trying to connect to instead. From dyzma at mat.uni.torun.pl Mon May 17 10:23:56 2004 From: dyzma at mat.uni.torun.pl (Lukasz Indyk) Date: Mon, 17 May 2004 16:23:56 +0200 Subject: html to image or html to postcript to image In-Reply-To: References: Message-ID: i'm sorry, i didn't make myself clear enough. once again then: i have html defining website, and i want to generate image with this website (without displaying it in browser window, doing print screen etc.) From ciccio at smilzo.net Wed May 5 14:33:04 2004 From: ciccio at smilzo.net (Fabio Corneti) Date: Wed, 05 May 2004 18:33:04 GMT Subject: PyQT developement for Windows Message-ID: Hi all, I read many posts on the subject, but I'm still confused about licensing issues with PyQT. I'm going to start a new project, and I'd like to use PyQT because it is an excellent product; the particular issue is that we would like to make the source code available under the GPL, but we would also like to distribute a compiled version for Win32. Having a commercial copy of QT and PyQT, would it be possible to develop a GPL version which would remain GPLed where PyQT and QT are GPL and build the Windows version from this code to redistribute it in some manner (e.g. freeware)? Thank you, -- ----------------- Fabio Corneti ciccio at smilzo.net ----------------- From Miklos at nowhere.hu Sat May 22 04:20:44 2004 From: Miklos at nowhere.hu (Pm) Date: Sat, 22 May 2004 10:20:44 +0200 Subject: Server/OS/Dev environment References: Message-ID: Jean wrote: > Hi. I am new to Python, but very eager to learn. I've browsed many > postings and found conflicting opinions on the best backend and > development setup. In fact, I am more confused now that when I first > began investigating this problem. > > I need to create web pages with MySQL as the primary data source. > What would be the best server set up for this? RH? Windows? > mod_python? Spyce? Some other templating mechanism? > > To develop such a site, should I be using Vim? Idle? Or Windows gui > software? Install MySQL & Python on Windows? Stick with Linux? > > A multitude of choices is great for the gurus, but not necessarily so > for a newbie... > > Thanks for any comments, > Jean Varietas delectat, Jean. ;) I suggest you spend a little time on exploring these and then you'll find out what you like best. (It's just like about girls: it'd be awful if every guy would prefer the same looks...) To add to you confusion, maybe have a look at Zope as well (www.zope.org) :-)) Or how about Webware? (http://webware.sourceforge.net/) Or Albatross? (http://www.object-craft.com.au/projects/albatross/) Best, Pm -- E-mail: base64.decodestring('cHJpc3pAYXN5bHVtdGVsLmNvbQ==\n') From segphault at sbcglobal.net Fri May 21 10:08:54 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Fri, 21 May 2004 14:08:54 GMT Subject: Newbie's rant's and question :) (long post) References: <1e6f6533.0405201134.138b752c@posting.google.com> Message-ID: On Thu, 20 May 2004 12:34:14 -0700, Hendy Teguh wrote: > Hello, > > first, a little warning, may contain negative comments, this is truly > my humble opinion, please consider it as a curious comments, not > flaming or trolling (there're tendency i read on newsgroup (especially > linux newsgroups), that newbie's opinion are often considered > trolling, especially from diehard fans :P ). And also since english > is not my native language, please forgive my bad english. > > Ok, a little background. i learned some programming language before, > all DOS (QuickBASIC, Pascal and Assembly). But when VB 'boomed', i > stopped programming (i didn't really like the way of visual > programming). Lately i began to use linux and see that python is > widely use in almost everywhere, i started to learn python. > > I've been learning python for about 2 or 3 months (not too seriously) > and i've been learning from a lot of online tutorials. So far i have > written 2 serious programs, one that remove certain attributes from > HTML tag, the other one auto-rename all images that a page use into > sequential order. All are done manually (read, parsed, edited and > wrote back). I think i pretty much grabbed the basic of python > language (although sometime still need to look for command reference). > > 1. I actually has a lot of idea of program that i want to write, but > since the 'basic' python has pretty much limitation in outputing > result (No GUI), so i think it's time for me to learn GUI extension. > After searching around, i finally decided to learn wxPython. I try to > follow the tutorial from the website, but it seemed that the tutorial > is written in mind that we have learned any GUI programming before. I > stopped on the middle of the tutorial since everything looks 'out of > control'. I (guess i) do know what the commands do, most question is > like 'where the heck does this command come from?' which lead to 'if i > want to do this, what should i do?'. > > i tried to search for other wxPython tutorial, but it seems a little > scarce. i googled around and found out that many expert always > recommended to look for reference from the demo file and the help > file. So, i try to learn by myself. It took me nearly 30 minutes > 'wreck havocing' the demo files and wxWindow reference just to find > the command to refresh the menu (which i've disabled). This is very - > very discouraging for me. Am i doing something wrong here or is this > the correct 'process' of learning GUI programming? I feel like > there're a lot of missing step from the 'basic' python tutorial to > 'expert' python tutorial. > > 2. so far i learned python, i got the impression that python is more > like a scripting language than programming since python rely heavily > on external libraries (i may be biased on this because i also > currently learning Blender 3D which use python as the scripting > language). In other word, somehow python is 'teethless' in doing > something 'powerful' by itself IMHO. > > I'm planning to write a simple graphic viewer in paralel learning GUI. > Since python don't support natively jpeg or png (am i right?), do i > need to find library to read those file or should i find the format of > each extension and decode with python by myself? if i can use library, > could anyone guide me where to find supporting library for python? (I > once every tried to google for zip handling library, found only zlib, > seems only handling ZIP compression not the zip file itself). > > 3. just a curious question, why doesn't python include a basic library > (GUI for example)? the library doesn't necessarily need to be > optimised, just to help introducing the way python work. An example > Pascal language, it included some library to handle graphic mode. Not > very optimised, but it really-really help me a lot in understanding > graphic mode. When i'm good enough and feel that it's very slow, i > could either search for better library or just programmed it myself > (in my case, i made a library from assembly). The point is that it > could really - really help the beginner to learn. > > > ok, end of my rants here :) > > Best regards, > > > Hendy looks like everybody else covered your GUI lib questions pretty well. I'll comment on your comment that python lacks teeth. ;-) Python has a simple, consistent syntax that facilitates rapid development of relatively powerful applications. Because it is an interpreted language, an algorithm implemented in pure python will always be slower than one implemented in a language like C that can produce native executables. Use of external libraries nullifies this problem. I start by writing my programs in python, and when I find functions or components that are lagging considerably, I rewrite them in OCaml or C, and make a python interface for them. In all honesty, I dont find that I have to do it very often. Python is very fast, even though it is interpreted. In most tests, you will find that python runtime speed is significantly better than Java's, and python also seems to use less memory than java. As far as I can tell, python has very nice teeth! Python challenges the the distinction between a 'scripting' language and a 'programming' language. It has the capacity to be whatever you need it to be. It is well suited for writing simple shell scripts (tho I typically prefer Ruby for shell scripts), and it is equally well suited for writing large scale programs. The ease with which external C and Ocaml libraries can be used and wrapped adds a lot of power to python. Good luck! --SegPhault From ajsiegel at optonline.com Sat May 29 09:00:24 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 29 May 2004 13:00:24 GMT Subject: terminological obscurity References: <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> <40b79d0e$0$26997$9b622d9e@news.freenet.de> <40b83034$0$27038$9b622d9e@news.freenet.de> Message-ID: On Sat, 29 May 2004 08:39:51 +0200, "Martin v. L?wis" wrote: >Arthur wrote: >> But then nothing can be determined about the hetergenousity or the >> homogenousity of any particular context for this data by reference to >> the data itself. >> >> Though the reverse is not true. >> >> In the conversation I am having this is a significant point. >> >> But I suspect we are not having the same conversation. > >I'm uncertain. I would see a significant point if you would >admit that "a list is for homogenous data" is not a tautology. I am not unwilling to make the admission, but I need some help. Becasue I am not unwilling to see a list as an homogenous context. But by placing data within that context we have done nothing to change the nature of the data. If the data was ambiguous, it is still ambiguous. The purpose of the list is a perspective on the data. From that perspective we view an homogenous aspect of it. Does that do? But if something about type is in the end at the bottom of your view, than I am still a bit lost, I am afraid. Art >You certainly need a context to make a statement about >homogeneity, but that context is *not* the mere fact that >the data are all stored in the list. > >Regards, >Martin From r_boman at yahoo.fr Tue May 4 11:19:02 2004 From: r_boman at yahoo.fr (Boman Romain) Date: Tue, 4 May 2004 17:19:02 +0200 Subject: Tkinter and threads Message-ID: Hi everyone, I've got problems with Tkinter and threads when using a debug version of python. I would like to build a "GUI thread" and an "interpreter thread" (the classical python command line). Both threads don't interact with each other (for now). The GUI must be in a separate thread because the user can execute commands that take a long time to run through the command line (and the GUI must be available during these commands) For example: (file: mygui.py) import threading import Tkinter class RWin (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self, *args): self.root = Tkinter.Tk() print 'starting Tk!' self.root.mainloop() bw = RWin() bw.start() when I load this file (import mygui), the tk window opens and everything is OK if I use a non-debug version of python. Otherwise (with a debug version), python_d crashes when I press a key with this message : "Fatal python error: invalid thread state for this thread" It seams that the problem comes from the EventHook() function defined by tkinter. This function is called by the main thread (the interpreter) because tkinter uses PyOS_InputHook (for managing things I don't understand). This function calls RestoreThread() with the Tk thread state instead of the main thread state. As the debug version checks these states, it fails. What is wrong? Is it impossible to have these two threads working toegether (in a debug version of python)? Romain From jcarlson at uci.edu Fri May 21 15:16:03 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 21 May 2004 12:16:03 -0700 Subject: Printing formatted strings from a dictionary In-Reply-To: <21064255.0405201224.77a7574f@posting.google.com> References: <21064255.0405131144.160af9a8@posting.google.com> <21064255.0405201224.77a7574f@posting.google.com> Message-ID: > Uuuaaah, I can't stop learning YOU(python). Couldn't verify > the above example. Maybe some fault happened to you because the code > which raised the KeyError and the successfull one are the same for me. > But the following works: > >>>>d={'1':2} # Remark the quotmarks '1' >>>>'%(1)i'%d > > '2' Right, I forgot to rebind d. My bad, but it is great that you figured it out. - Josiah From andy at andybak.net Sat May 8 13:59:59 2004 From: andy at andybak.net (Andy Baker) Date: Sat, 8 May 2004 18:59:59 +0100 Subject: Anyone seen this? Message-ID: http://www.getty.edu/art/collections/objects/o1271.html Obviously a Microsoft consiracy! From sross at connectmail.carleton.ca Mon May 10 22:10:00 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 10 May 2004 22:10:00 -0400 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: "Wolfgang Buechel" wrote in message news:4629559b.0405101330.286ddb32 at posting.google.com... > Hi, > > I want to iterate over all 2x2 matrices with elements in range 0..25 > (crypto-stuff). [snip] > Is there a shorter (and probably, with respect to exec time, faster) > way to write such a 4for loop? > (I want to scan 3x3, 4x4 matrices too (;-) > > -- Wolfgang Hi. The following code isn't necessarily shorter or faster (or more readable), but it's a bit more general: # slightly modified code from http://twistedmatrix.com/wiki/python/PostYourCode def sequences(n, things): "generates sequences of n items from a set of things" if n == 0: yield [] else: for x in things: for y in sequences(n-1, things): yield [x] + y def nXn_matrices(n, elements): "generates nXn matrices from elements" for s in sequences(n*n, elements): yield [s[i*n:(i+1)*n] for i in xrange(n)] # we'll try it over a small range ... M = 3 for m in nXn_matrices(2, range(M)): print m Output: [[0, 0], [0, 0]] [[0, 0], [0, 1]] [[0, 0], [0, 2]] [[0, 0], [1, 0]] [[0, 0], [1, 1]] [[0, 0], [1, 2]] [[0, 0], [2, 0]] ... ... [[2, 2], [2, 0]] [[2, 2], [2, 1]] [[2, 2], [2, 2]] # now 3X3 ... this takes a _l_o_n_g_ time ... M = 3 for m in nXn_matrices(3,range(M)): print m Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] [[0, 0, 0], [0, 0, 0], [0, 0, 1]] [[0, 0, 0], [0, 0, 0], [0, 0, 2]] [[0, 0, 0], [0, 0, 0], [0, 1, 0]] [[0, 0, 0], [0, 0, 0], [0, 1, 1]] [[0, 0, 0], [0, 0, 0], [0, 1, 2]] ... ... [[2, 2, 2], [2, 2, 2], [2, 1, 0]] [[2, 2, 2], [2, 2, 2], [2, 1, 1]] [[2, 2, 2], [2, 2, 2], [2, 1, 2]] [[2, 2, 2], [2, 2, 2], [2, 2, 0]] [[2, 2, 2], [2, 2, 2], [2, 2, 1]] [[2, 2, 2], [2, 2, 2], [2, 2, 2]] I'm believe there are several opportunities for optimization both in the code and in the algorithm (for instance, it may be possible to take advantage of repetition in the sub-matrices), but I won't be trying that now. Good luck with what you're doing, Sean From manatlan at online.fr Wed May 19 06:45:58 2004 From: manatlan at online.fr (marco) Date: Wed, 19 May 2004 12:45:58 +0200 Subject: drag drop from linux to a wxpython application Message-ID: <40ab3ae7$0$21248$636a15ce@news.free.fr> I've got a wxpython application and when i drag'n' drop files from(linux) rox/nautilus/konqueror to my app i've got strange chars in filenames (on win32 : it works well) example: - my dir "my photos" will become "/home/marc/my%20photos" - a dir "f?tes ? strass" will become (something like this) "/home/marc/f%A8%CFtes%20%8F%AC%20strass" it seems the filenames are "escaped" ... is there a way to got the good filenames ? (i means it doesn't come from python, but perhaps it's an encoding problems ?! i'd like to use a function like "unescape()" in javascript, to clean them) From jepler at unpythonic.net Fri May 21 07:59:10 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 21 May 2004 06:59:10 -0500 Subject: How do I create a dynamic wrapper for another language? In-Reply-To: <1085111772.6438.620.camel@stella.fnord.you> References: <1085111772.6438.620.camel@stella.fnord.you> Message-ID: <20040521115909.GA10886@unpythonic.net> Yes, probably. Consider the case of tcl. We already have Tkinter and _tkinter, which take the approach of a hand-written wrapper for the desired commands, but provide the "call" method of tkapp objects. You'd write something like "call", which does the appropriate thing, possibly checking for valid arguments in advance, translating return codes into Python values and exceptions. I know this is very hand-wavy, but so was your original question. Jeff From dippyd at yahoo.com.au Tue May 11 23:52:24 2004 From: dippyd at yahoo.com.au (Steve) Date: Wed, 12 May 2004 13:52:24 +1000 Subject: Integer division, surprising results References: <7aa8fd19.0405100941.43553112@posting.google.com> Message-ID: <40A19F78.20802@yahoo.com.au> Rory Geoghegan wrote: >>I've looked at faqs and documentation, and nothing jumped out at me. Can >>anyone explain the reasoning for this? > > > According to my math book integer division is defined as such: > a/b = q, where a = b*q + r and r is the remainder. > > A remainder (ei a modulo) is always positive, effectively flooring all > the division operations. Remainders are always positive, but modulo can be defined as either positive or negative (for negative arguments). There are pros and cons for doing it either way, although the Python way seems to have more pros than cons. -- Steven D'Aprano From grzegorz at ee.ualberta.ca Mon May 3 11:01:50 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Mon, 3 May 2004 11:01:50 -0400 Subject: Embedding python into PyQt In-Reply-To: References: Message-ID: I am going to reply to my own message. That way, if someone else looks for something similar - it'll be in the archives. PyCute is part of a PyQwt project (available at sourceforge). It does exactly what I want. I am using the PyCute3.py. There is a small snag if you want to use it with a Qt designer. I solved it by creating the following file: PyCute.py --------------------------------------------------------- import PyCute3 class PyCute(PyCute3.PyCute): def __init__(self, parent, name): PyCute3.PyCute.__init__(self, parent=parent) --------------------------------------------------------- After having that and the PyCute3.py in the same directory, just add a custom widget to designer as class PyCute. and include the line: Python:from PyCute import PyCute in the comment field of the form settings. Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) On Fri, 30 Apr 2004, Grzegorz Dostatni wrote: > > Cheers. > What I am trying to do is to embed the python interactive interpreter > inside a qt TextEdit. > > I could write an event loop myself, but I was wandering if there exists a > solution somewhere, or the best way to do it myself. > > Greg > > Advice is what we ask for when we already know the answer but wish we > didn't. > -- Erica Jong (How to Save Your Own Life, 1977) > > > > From winexpert at hotmail.com Wed May 19 17:32:39 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 19 May 2004 17:32:39 -0400 Subject: comparing strings and integers References: <3064b51d.0405191326.124a3ab3@posting.google.com> Message-ID: without knowing any better, its possible "1" translates to 0x31 so it would become 0x31 > 1 ===> True.... David http://cellphone.duneram.com/index.html ----- Original Message ----- From: Newsgroups: comp.lang.python To: Sent: Wednesday, May 19, 2004 5:26 PM Subject: comparing strings and integers > By mistake I coded something like > > print ("1" > 1) > > and got the result "True". Comparing an integer and a string seems > meaningless to me, and I would prefer to have an exception thrown. Can > someone explain why Python allows comparisons between integers and > strings, and how it handles those cases? Why is "1" > 1? > > Pychecker does not warn about the line of code above -- I wish it did. > > In my code what I really intended was to convert the "1" to an int and > THEN do a comparison. From winexpert at hotmail.com Thu May 27 11:54:12 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 15:54:12 +0000 Subject: How to I print without newline ? Message-ID: >>>def try1(text): ... x = "\r%s" % text ... print x, ... >>>def series(): ... try1("10") ... try1("999") ... >>>series() 999 Seems to work to put the \r first >From: "David Stockwell" >To: fowlertrainer at anonym.hu, python-list at python.org >Subject: RE: How to I print without newline ? >Date: Thu, 27 May 2004 15:22:05 +0000 > >Hi, > >This might work: > >print "25\r", > >the \r would do a carriage return with no line feed. >the , would try to keep it on the same line. > >not sure though. > > >David Stockwell >------- >Cell: http://cellphone.duneram.com/index.html >Cam: http://www.duneram.com/cam/index.html >Tax: http://www.duneram.com/index.html > > > > >>From: "fowlertrainer at anonym.hu" >>To: python-list at python.org >>Subject: How to I print without newline ? >>Date: Thu, 27 May 2004 17:06:17 +0200 >> >>Hi ! >> >>I want to print, but without newline. I want to create a progress for ftp, >>but the print is drop a newline for every percent. >>I want like this: >> >>0% 25% 50% 75% 100% >> >>But this happening: >>0% >>25% >>50% >>75% >>100% >> >>How to I prevent the newlines ? >> >>Thanx for help: >>FT >> >> >>-- >>http://mail.python.org/mailman/listinfo/python-list > >_________________________________________________________________ >MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE >download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Watch LIVE baseball games on your computer with MLB.TV, included with MSN Premium! http://join.msn.click-url.com/go/onm00200439ave/direct/01/ From skip at pobox.com Sun May 23 08:03:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 23 May 2004 07:03:38 -0500 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <30260531.0405222153.5027c135@posting.google.com> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <16560.37658.699032.405280@montanaro.dyndns.org> simo> Proper encapsulation is needed before the C++ brigade will take simo> P[y/ro]thon seriously as an OO language, ... Note that Python is not targeted at winning over C++ programmers, so that's unlikely to motivate anyone to tighten up Python's current name mangling. That's designed to prevent accidents, not access. Skip From jimmy at retzlaff.com Tue May 11 10:34:24 2004 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 11 May 2004 07:34:24 -0700 Subject: ANN: EasyDialogs for Windows version 1.14.0 Message-ID: EasyDialogs for Windows is available at: http://www.averdevelopment.com/python/ EasyDialogs for Windows is a ctypes based emulation of the EasyDialogs module included in the Python distribution for Macintosh. It attempts to be as compatible as possible. Code using the Macintosh EasyDialogs module can often be run unchanged on Windows using this module. The module has been tested on Python 2.3 running on Windows XP and Windows Server 2003. I would appreciate feedback at jimmy at retzlaff.com about experience running this on other version of Windows (I attempted to avoid APIs that weren't available on Windows 95 or Windows NT 4.0). EasyDialogs is written in pure Python using Thomas Heller's ctypes module (http://starship.python.net/crew/theller/ctypes/) to call Windows APIs directly. No Python GUI toolkit is used. This means that relatively small distributions can be made with py2exe (or its equivalents). A simple test of all the dialogs in EasyDialogs bundled up using py2exe results in a distribution that is about 1.25MB. Compressing the exe, dll, and pyd files using UPX (http://upx.sourceforge.net) drops that to about 550KB. Prerequisites EasyDialogs for Windows requires Windows, Python 2.3, and ctypes 0.6.3. License: MIT This is the initial public release of EasyDialogs for Windows. Jimmy From danb_83 at yahoo.com Tue May 11 01:13:25 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 10 May 2004 22:13:25 -0700 Subject: Inverse of int(s, base)? References: <2gac73Fk1ooU1@uni-berlin.de> Message-ID: olli at secnetix.de wrote in message news:<2gac73Fk1ooU1 at uni-berlin.de>... > Hi, > > Is there an inverse function of int(s, base) where base > can be any number up to 36? Yes, but for some reason it's not in the Python standard library. ... > PS: This is what I'm using right now. > > import string > str_digits = string.digits + string.ascii_lowercase > > def str_base (x, base): > result = "" > while x: > result = str_digits[x % base] + result > x /= base The above line should be "x //= base", so it works under -Qnew. > return result or "0" That works (for positive integers), but it might be more efficient to not create a new string each time through the loop. An alternative is: def str_base(n, base=10): if n == 0: return '0' isNegative = n < 0 if isNegative: n = -n result = [] while n > 0: n, lastDigit = divmod(n, base) result.append(str_digits[lastDigit]) if isNegative: result.append('-') result.reverse() return ''.join(result) From winexpert at hotmail.com Wed May 19 11:38:52 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 19 May 2004 15:38:52 +0000 Subject: What's the meaning of Dutch in "The Zen of Python" Message-ID: long time back we had to localize our software to dutch.... We hired a dutch translator. the only words I that I now remember in dutch are: Even Geduld... That message appeared at the beginning of a long sequence in huge letters..... (Hope I didn't get the spelling wrong). I think the reference below is a humerous reference to the person who created python Guido Van Rossum. I might be wrong though.... David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: Li Daobing >To: python-list at python.org >Subject: What's the meaning of Dutch in "The Zen of Python" >Date: Wed, 19 May 2004 20:31:09 +0800 > >Hello, > > Does anyone know what's the meaning of Dutch in "The Zen of Python"? > Thanks in advance > >Li Daobing > > > > 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! _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From brian at sweetapp.com Tue May 25 09:26:58 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 25 May 2004 15:26:58 +0200 Subject: XML-RPC - instance In-Reply-To: References: Message-ID: <40B349A2.3040203@sweetapp.com> Manuel Huesser wrote: > Currently it's possible to register a single functions or a an instance in > the standard XML-RPC library. Is there a possibility to refer to > a different instance, like in a session. Should be possible with HTTP/1.1, > but I haven't an idea. Could you be more specific? It is possible to do method dispatch pretty much any way that you want; is that the functionality that you are looking for? Cheers, Brian From dmgass at hotmail.com Tue May 11 09:48:59 2004 From: dmgass at hotmail.com (Dan Gass) Date: 11 May 2004 06:48:59 -0700 Subject: How do you register cleanup code to be run after script execution? References: <20040508090936.21319.00000994@mb-m04.aol.com> Message-ID: Upon reflection, this is close to what I want but not quite what I need. I wanted this answer to use in an open source test generator framework I am writing to unit/integration/function test Python, C, or C++ (it could be extended to other languages). For now the user interface is Python (someday maybe I'll make an XML interface). The user writes a script to setup the test and the framework generates the test and executes it. I wanted the generation of the test and the execution of it to occur when the script is done running. The trouble with using the atexit mechanism is that it is uses a last in first executed. I may run into trouble with integration tests where other things get registered after me and that cleanup will get done before I start (and they may shut down resources the test needs to execute). I'm thinking it maybe just best to provide the user a function to generate/execute the test that they must call last. BTW, as part of this effort I required a much more powerful configuration mechanism that is provided by the global module ConfigParser. If you are interested in this area please see http://config-py.sourceforge.net/. Thanks for your responses, Dan Gass From della at toglimi.linux.it Thu May 27 02:37:55 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 27 May 2004 06:37:55 GMT Subject: Update with pickle In-Reply-To: References: Message-ID: <71gtc.75003$Qc.3030919@twister1.libero.it> Nicolas Fleury wrote: > I think it is acceptable that this pickle.update function would only > accept reference of same type and raise an exception otherwise. The > point of pickle.update would be to not "replace an object with another > one" but to call __init__ on an existing object. I still don't understand how exactly you would want it to work. If you want to call __init__ on an existing object, why don't you just do it explicitly? Could you post some equivalent code to what you would want pickle.update to do? -- Ciao, Matteo From xgote at k-theory.com Sat May 29 19:36:30 2004 From: xgote at k-theory.com (Dave) Date: Sat, 29 May 2004 16:36:30 -0700 Subject: http file post Message-ID: <40B91E7E.3080205@k-theory.com> Greetings. Ive been trying to figure out how I can write to a file from an HTTP post while it is being uploaded. So far ive realized that my script isn't getting the data until the browser is done uploading. What I want to accomplish is a way to track the progress of a file upload. I'm guessing that if I can get it to write to a file as it is uploaded I can load another browser to check the progress of the transfer (by refreshing). Here is the general idea I have tried: if item.file: filen = item.filename filen1 = filen.split('\\') filen2 = filen1[len(filen1)-1] outfile = open(path + filen2 + '.tmp','wb') buff = item.file.read(40000) while buff != "": outfile.write(buff) buff = item.file.read(40000) if not buff: break Works, but I recieve the data all at once rather then while.. Perhaps it is my ignorance about how http works and that there is no other way? Thanks in advance. -Dave From guido at debris.demon.nl Mon May 24 03:44:26 2004 From: guido at debris.demon.nl (Guido Wesdorp) Date: Mon, 24 May 2004 09:44:26 +0200 Subject: MSIE6 Python Question In-Reply-To: <22b7fd40.0405231744.50d125f1@posting.google.com> References: <22b7fd40.0405231744.50d125f1@posting.google.com> Message-ID: <10b39urqsjv1l2a@corp.supernews.com> Ralph A. Gable wrote: > Can anyone point me to some URLs that > would help out? Or just tell me how to do it? I would be very > grateful. I can't go there right now, since it only works on IE (uses Active-X for the navigation, very nasty) but there should be a full reference of IE's COM API on msdn.microsoft.com somewhere, check for the VB API. That can be used from COM, as soon as you've instantiated the COM object you can call the methods and use the attributes from this API. I assume there are methods in there to either directly get the info you want or else to use JavaScript to get to the info. Good luck, Guido Wesdorp From rick.ratzel at scd.magma-da.com Wed May 19 14:41:30 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Wed, 19 May 2004 13:41:30 -0500 Subject: .py to binary In-Reply-To: References: Message-ID: <40abaa5a$0$90386$39cecf19@news.twtelecom.net> Take a look at freeze.py. It is located in Tools/freeze in the Python source distribution. Marco Terzuoli wrote: > Hi, > I would like to convert a .py file into a stand-alone executable, so that > anyone can run it without having to install the python interpreter. I know > there is a py2exe program for Windows, but I would like to do the same for > Linux. Is it possibile or Linux only allow to use python scripts? > Thanks for helping, > Marco From vincent.salaun at zslide.com Thu May 27 09:54:26 2004 From: vincent.salaun at zslide.com (vincent Salaun) Date: Thu, 27 May 2004 15:54:26 +0200 Subject: [newbie] conditional imports Message-ID: <40B5F312.70501@zslide.com> hi all, here is my pb : - i've written a python xml parser using minidom - i've written a Jython xml parser using java dom classes - because minidom doesn't work with jython :( - Only one generic parser would have been the best solution because it will be used by a Java application on one side and by a C++ application on the other side but i've failed to find a python xml lib working both in python and jython .... So, now i'd like to put these 2 modules together as much as possible, to finally have only one, if possible... To do that, i thought using python shortcuts (actually, the content of these 2 modules is quite similar, only method names change) Here is my idea: ############################################################# #module myBothJavaAndPyParser : #if the module is used by the Java app :: from javax.xml.parsers import DocumentBuilder, DocumentBuilderFactory from org.w3c.dom import * factory=DocumentBuilderFactory.newInstance() builder = factory.newDocumentBuilder() parseString=self.builder.parse #else: from xml.dom import minidom,Node parseString=minidom.parseString class myParser: def __init__(self): #... def parse(self,toParse): return parseString(toParse) ..... ############################################################# But when i instanciate this class, i don't know how to do to know which imports and aliases must be done ... i tried to put the imports in the __init__ (and using a boolean) but then i can't access to aliases Any suggestions ? And i have another problem concerning shortcuts : how to make a shortcut on an attribute ? For example : Using java, for a Node, we have the getParentNode() method : myNode.getParentNode() In python, it's an attribute : myNode.parentNode How to do to make a shortcut in this specific case ? And if a make the shortcut in another way : #if used by Java : # imports ... parentNode=Node.getParentNode But now, i will uses this syntax : myNode.parentNode() .... and it won't work anymore using python imports .... i'm new to python, please help !! thx in advance ;) vince From ville at spammers.com Thu May 13 16:55:45 2004 From: ville at spammers.com (Ville Vainio) Date: 13 May 2004 23:55:45 +0300 Subject: things I wish python could do References: Message-ID: >>>>> "rzed" == rzed writes: >> Maybe lambda should be renamed as lameda? ;-) rzed> Or: lambada -- the forbidden function. Or leave it to Lambda - the function that dare not speak its name. (I guess I need to get some sleep now) -- Ville Vainio http://tinyurl.com/2prnb From dmq at gain.com Tue May 25 07:36:01 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 04:36:01 -0700 Subject: Method binding confusion References: <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> Message-ID: On Mon, 24 May 2004 17:21:07 -0700, Josiah Carlson wrote: >It can be done. > > >>> import math > >>> > >>> def mypow(x, y): >... return x**y >... > >>> class MathA: >... pow = math.pow >... > >>> class MathB: >... pow = staticmethod(mypow) <== *** >... > >>> ma = MathA() > >>> mb = MathB() > >>> > >>> ma.pow(2,4) >16.0 > >>> mb.pow(2,4) >16 Yes. This is the solution I came up with. It's a valuable exercise for students, but I warn them not to worry about what's going on in Python, just look at the error message and see if you can fix the problem. The error message is the familiar: TypeError: mypow() takes exactly 2 arguments (3 given) This message, and the knowledge that calling from an instance adds an extra argument, should be sufficient clue to add the staticmethod wrapper. -- Dave From kirk at eyegor.jobsluder.net Sat May 15 12:23:56 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Sat, 15 May 2004 16:23:56 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: On 2004-05-12, Aahz wrote: > In article , > Kirk Job-Sluder wrote: >> >>And here is the fundamental question. Why should I spend my time >>writing a module in python to emulate another tool, when I can simply >>use that other tool? Why should I, as a resarcher who must process >>large quantities of data, spend my time and my employer's money >>reinventing the wheel? > > Why should your employer pay for the time for all of its employees to > learn all of those other tools, when Python will do the job? As was brought up earlier. Creating custom python scripts to reinvent the wheel is also loaded with training costs. I would argue the following: 1: Using an existing idiomatic tool takes advantage of standardization. "perl -pi -e" exhibits the same behavior on multiple platforms and even different versions of perl. It is an idiomatic expression that is very well documented, and for which 100s of examples through a quick google search. 2: Memorizing two lines is more difficult than memorizing one line. 3: The alternative proposal, writing a site-specific module is even worse when it comes to training requirements. Or to turn this around, why should anybody learn to use tar, find, less, rsync or diff when you can do the same thing in python? From ajsiegel at optonline.com Mon May 24 12:25:28 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 24 May 2004 16:25:28 GMT Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> Message-ID: <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> On Mon, 24 May 2004 07:35:05 GMT, Arthur wrote: > >We agree as to the dynamics at work. With some part of that dynamics, it seems to me, being that many of us take our own understanding of the difference between tuples and lists (some of which might be deeper than others, mine on the lighter side) and then ascribe and reconcile that understanding with Guido's words. Which is part of the tautaology factor. It works fine, until we try to communicate with each other, around those words. Art From jollinofrenoamano at sogno.net Mon May 10 04:32:57 2004 From: jollinofrenoamano at sogno.net (Jollino) Date: Mon, 10 May 2004 10:32:57 +0200 Subject: Python for Nokia Series 60 References: <2g7c6lF52kr4U1@uni-berlin.de> <2g7siqF57e6rU1@uni-berlin.de> Message-ID: In article <2g7siqF57e6rU1 at uni-berlin.de>, "jarod" wrote: > But you haven't answered to my question. Why not think to the use of Jython > ? Do you know nothing about Java ? Personally, I don't... :) But I'm downloading it right now, I'll have a look at it (on the Mac, though, not on the phone - I haven't received my 6600 yet). Ciao! -- Jollino - per rispondere togli il freno a mano Photo portfolio and posters at http://www.nicolucci.net From j.dot.willeke at verizon.dot.net Sun May 2 10:08:28 2004 From: j.dot.willeke at verizon.dot.net (Jon Willeke) Date: Sun, 02 May 2004 14:08:28 GMT Subject: Pass a list to diffrerent variables. In-Reply-To: References: Message-ID: Robbie wrote: > Peter Otten wrote: > >> Both methods shown above result in a (shallow) copy of the original list. > > Thanks, that works fine but I am working with a 2d list... > and I dont understand why this happens > d = [[1,2,3],[1,2,3],[1,2,3],[1,2,3]] > d > [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] > f = list(d) > f > [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] > d[0][0]="a" > d > [['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] > f > [['a', 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] > What exactly is this doing? And how can I stop it? That's why Peter cautioned that the list() constructor yields a shallow copy. The is operator and the id() function will reveal that d[0][0] and f[0][0] are the same list. You want the copy.deepcopy() function. From lbates at swamisoft.com Tue May 18 18:03:18 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 18 May 2004 17:03:18 -0500 Subject: Creating self-contained apps References: Message-ID: I do this with py2exe for Windows. I also use InnoSetup to create self installation .EXE file for Windows distribution. Seems to work quite well. HTH, Larry Bates Syscon, Inc. "Ed Leafe" wrote in message news:mailman.58.1084908123.6949.python-list at python.org... > Is it possible to create a version of Python, along with several > specific modules, and somehow package it together to be distributed as > a single unit? I remember that Zope did something similar in the past, > but can't recall how that was accomplished. I looked into bdist in > DistUtils, but couldn't find enough info on it to determine if it would > do what I want. > > I have an app that requires a specific version of Python, along with > specific versions of various modules. What I need is a single file that > I can distribute that will run my packaged version of python, assuring > that the user, no matter what Linux distro they are using, will be able > to run it? And while I'm at it, is this also possible in Windows? > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ > > From cookedm+news at physics.mcmaster.ca Thu May 13 14:52:38 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 13 May 2004 14:52:38 -0400 Subject: Help with Distutils References: Message-ID: At some point, Johan Svedberg wrote: > Hi! > > I just started playing around with Distutils and there is one thing I > could use some help with. I'm wondering if there is some convenient way > to access the directories where the data_files was installed? If you're using the data_files argument to setup(), it's behaviour is described in the manual. Basically, if the specified directory is absolute, the files go there. Otherwise, the directory is relative to sys.prefix (or sys.exec_prefix if extension modules are installed). For example (from the documentation): ### setup.py setup(... py_modules = ['mod'], data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']), ('config', ['cfg/data.cfg']), ('/etc/init.d', ['init-script'])] ) ### I'll assume sys.prefix is '/usr'. b1.gif and b2.gif will installed by default /usr/bitmaps', and data.cfg in /usr/config. init-script will be installed in /etc/init.d. Now, there's a difficulty. If I run the setup.py script like this: $ python setup.py install --prefix=/usr/local then b1.gif, for instance, gets installed in /usr/local/bitmaps. So you can't hard-code /usr/bitmaps as the path to look at in your application. One thing you can do is use the __file__ variable that's defined in a module to find out where that module is installed, and work your way up. With the above call to setup.py, the module 'mod.py' would be installed in /usr/local/lib/python2.3/site-packages, and within mod.py, __file__ would be '/usr/local/lib/python2.3/site-packages/mod.pyc', so you could walk the tree up. However, there's more problems. I install somethings in my home directory like this: $ python setup.py install --home=~/usr Now mod.__file__ is '/home/cookedm/usr/lib/python/mod.pyc'. Things can get more complicated if the --install-lib option is used. Ugh. One solution that I've seen used several times is to install data files in the package directory: ### setup.py from distutils.core import setup from distutils.command.install_data import install_data class my_install_data(install_data): def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'install_dir')) install_data.finalize_options(self) setup(... packages = ['mypackage', 'mypackage.data'], data_files=[('mypackage/data', ['bm/b1.gif', 'bm/b2.gif'])], cmdclass = { 'install_data' : my_install_data } ) ### b1.gif and b2.gif will now be installed in the same directory as the modules in mypackage.data. A file mypackage.data.__init.py can look like this: ### mypackage.data.__init__ import os.path def data_dir(): mod_loc = os.path.dirname(__file__) return os.path.abspath(mod_loc) ### Then in your main code, ### mypackage.do_stuff_module import mypackage.data ... data_dir = mypackage.data.data_dir() b1gif = open(os.path.join(data_dir, 'b1.gif')) ### Hope this helps. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From peter at engcorp.com Wed May 26 06:42:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 06:42:04 -0400 Subject: Command Prompt (again) In-Reply-To: References: Message-ID: EAS wrote: > 2 days ago, I used the following script to get a command prompt on my > system: > > import os > os.system('cmd.exe') > > However, yesterday, when I tried to use it again, it did nothing but return > "-1" > to the screen. Anyone know what happened and how to fix it? Screwed up the path? Try putting a "print os.getenv('PATH')" just before the call to os.system. Also try changing it, temporarily, to command.com instead, just to see what happens and if the screwup is limited to cmd.exe. Also, consider rewinding the source back to a previously working version. That will tell you if the problem is in your own code or in the environment (and here I just mean the surrounding system, not just the "environment variables"). Of course, to do this you would have to have been using a revision control system... but everyone does that, right? ;-) -Peter From spamtrap at nowhere.net Mon May 10 12:52:14 2004 From: spamtrap at nowhere.net (Steven) Date: Mon, 10 May 2004 17:52:14 +0100 Subject: Watch That Post References: Message-ID: <0rOnc.20115$7n5.16403@pathologist.blueyonder.net> Premshree Pillai wrote: > Hello, > > I recently posted a simple Python script--Watch That > Post--that lets you watch a URL for any changes. > > I wrote it to watch posts on LiveJournal, but it can > watch any URL. > > It's at http://premshree.seacrow.com/code/python/watch I tried running it. It works fine until it tries to run the watch function a second time, then it does this: Traceback (most recent call last): File "watch.py", line 76, in ? watch() File "watch.py", line 58, in watch size2 = len(urllib.urlopen(url).readlines()) File "/usr/lib/python2.3/urllib.py", line 76, in urlopen return opener.open(url) File "/usr/lib/python2.3/urllib.py", line 181, in open return getattr(self, name)(url) File "/usr/lib/python2.3/urllib.py", line 410, in open_file return self.open_local_file(url) File "/usr/lib/python2.3/urllib.py", line 420, in open_local_file raise IOError(e.errno, e.strerror, e.filename) IOError: [Errno 2] No such file or directory: 'www.kde-apps.org' I really like the idea, Steven From mwh at python.net Wed May 19 11:58:06 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 19 May 2004 15:58:06 GMT Subject: Popen3-style os.execl? References: Message-ID: Chris Green writes: > Michael Hudson writes: > > > Um. Can't you pass a list to the Popen3 constructor? > > Well, by golly ya can. Since cmd is only ever one argument in the > docs, I've never known that you could do this. Ah, uh, right: this isn't documented. I'm not sure why... as noted, it doesn't work on Windows, but then if you were talking about execl, you presumably aren't that concerned. Cheers, mwh -- Reading Slashdot can [...] often be worse than useless, especially to young and budding programmers: it can give you exactly the wrong idea about the technical issues it raises. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#reasons From afilip--usenet at freenet.de Wed May 19 04:47:37 2004 From: afilip--usenet at freenet.de (Arnold Filip) Date: Wed, 19 May 2004 10:47:37 +0200 Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: Jason Mobarak wrote: > Arnold Filip wrote: > >> Daniel Klein wrote: >> >>> Hello, >>> >>> I'm quite new to Python, and since a not-so-superficial look into the >>> docs didn't answer my question (although it still feels quite basic), >>> I decided to turn to this place: >>> >>> Is there a way to 'extract' a dictionary into the current namespace? >>> That is, if you have >>> {'foo' : 23, 'bar' : 42} >>> you would get a variable foo with value 23 and a variable bar with >>> value 42? Such a function would of course only work on string keys >>> and would probably have to check that, but still, it sounds practical >>> enough that surely someone else thought of it before. >>> >>> Daniel >>> >> >> How about this: >> >> In [1]: d = {'foo' : 23, 'bar' : 42} >> >> In [2]: for item in d.items(): >> ...: exec "%s = %d" % item >> ...: >> >> In [3]: foo >> Out[3]: 23 >> >> In [4]: bar >> Out[4]: 42 >> > > That's disgusting. I agree. But IMHO at least for a newbie that's the easiest way to do it. No need to know anything about the "internals" of python. > At least with manipulating __main__ your not also > bringing in the possibility of excuting arbitrary code. > > >>> d = {'foo' : 23, '__import__("os").system("echo executed a system command"); bar' : 42} > >>> for item in d.items(): > ... exec "%s = %d" % item > ... > executed a system command > >>> foo,bar > (23, 42) Concerning the security issue, the system call in your example can be easily prevented: >>> d = {'foo' : 23, '__import__("os").system("echo executed a system command"); bar' : 42} >>> for i in d.items(): ... exec "(%s) = %d" % i ... Traceback (most recent call last): File "", line 2, in ? File "", line 1 (__import__("os").system("echo executed a system command"); bar) = 42 ^ SyntaxError: invalid syntax > > Granted, the reasons for wanting to do this may be ill-concieved, > there's probably a better, more obvious solution -- since doing the > subject of this thread is neither easy nor elegant. Totally agree. Hey Daniel, may be you should point out _what_ you want to achieve rather than _how_ you can do this and that. Cheers, Arnold From tjreedy at udel.edu Mon May 10 13:22:06 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2004 13:22:06 -0400 Subject: Processing huge datasets References: <79Knc.15953$k4.322398@news1.nokia.com> Message-ID: "Anders S??ndergaard" wrote in message news:79Knc.15953$k4.322398 at news1.nokia.com... > I'm trying to process a large filesystem (+20 million files) and keep the > directories along with summarized information about the files (sizes, > modification times, newest file and the like) in an instance hierarchy > in memory. I read the information from a Berkeley Database. > Is there a clever way of processing huge datasets in Python? > How would a smart Python programmer advance the problem? I would start with 2 gigs of RAM, which would allow about 90 bytes per entry after allowing 200 megs for os and interpreter. Even that might not be enough. tjr From python at quixs.com Sat May 8 08:48:21 2004 From: python at quixs.com (Lars Heuer) Date: Sat, 8 May 2004 14:48:21 +0200 Subject: Calling constructor of unknown classes Message-ID: <195317594.20040508144821@quixs.com> Hi all, I try to do the following: map = {'some.thing':'ClassName'} try: mod = __import___(map.keys()[0], {}, {}, map.values()[0]) # Now I want to return an instance of the class in # map.values()[0] # I've to do something like "return mod.(map.values()[0])()" How to return the instance of the 'unknown' class? I've only the name as string. I tried eval, but I don't get it work. Thanks, Lars From MRothfuss at louchapter13.com Wed May 12 09:08:37 2004 From: MRothfuss at louchapter13.com (Mike Rothfuss) Date: Wed, 12 May 2004 09:08:37 -0400 Subject: Idea for Python T-shirt Message-ID: Or: "Python--it doesn't byte" -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 8:43 AM To: Simon Wittber; python-list at python.org Subject: RE: Idea for Python T-shirt EXCELLENT SUGGESTION!! Also: "I'll have the Python." "Excellent choice, Sir." -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Simon Wittber Sent: Tuesday, May 11, 2004 8:57 PM To: python-list at python.org Subject: RE: Idea for Python T-shirt A python T-Shirt? Funnily enough, I was thinking on this last night. Something eloquent, something slightly obscure, which only other Pythonistae would recognize: "import this" Sw. -- http://mail.python.org/mailman/listinfo/python-list From noemail at noemail4u.com Thu May 6 08:12:37 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Thu, 06 May 2004 12:12:37 GMT Subject: Need Help in Python References: <77632a66.0405041826.37568aef@posting.google.com> Message-ID: <154eba01da3bc4d337e453163f9096e2@news.teranews.com> """ Starter module for drawing boxes with characters. No warranty or suitability for use is expressed or implied. Daniel 'Dang' Griffith sez, "Have a nice day!". """ # for reference boxchars = [chr(i) for i in xrange(129, 219)] # handy abbreviations; roll your own naming convention UL = upperleft = topleft = chr(218) LL = lowerleft = botleft = bottomleft = chr(192) LR = lowerright = botright = bottomright = chr(217) UR = upperright = topright = chr(191) vert = vertical = chr(179) horiz = hor = horizontal = chr(196) nl = newline = '\n' # precompute the invariants top = '%c%%s%c' % (UL, UR) mid = '%%s%c%%s%c\n' % (vert, vert) bot = '%c%%s%c' % (LL, LR) all = '%s\n%%s%%s%s' % (top, bot) def box(w, h, fill=' ', indent=''): """ Return a string that appears as an 'box' when printed. This is, of course, highly depending on the local character representation. The box is filled with spaces by default. The box is left-aligned by default. To indent it, provide the indentation string. This will be added to the middle and bottom of the box. The caller is responsible for drawing the box at the appropriate starting position. """ # exceptional cases if w < 1: raise ValueError("A box must have a width of at least 1.") if h < 1: raise ValueError("A box must have a height of at least 1.") # pathological cases--return value is not *really* a box if w == 1: return h * (vert + nl) if h == 1: return horiz * w # normal case end = horiz * (w - 2) return all % (end, (h - 2) * (mid % (indent, fill * (w - 2))), indent, end) # --dang From skip at pobox.com Wed May 12 13:27:36 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 May 2004 12:27:36 -0500 Subject: logging package In-Reply-To: <40A24D45.8070600@cenix-bioscience.com> References: <40A24D45.8070600@cenix-bioscience.com> Message-ID: <16546.24200.97779.897039@montanaro.dyndns.org> Neil> Is the logging package thread-safe? Yes: http://www.python.org/doc/current/lib/node296.html Odd that you had trouble finding that information since it's in a section entitled "Thread Safety". Perhaps you saw that but it didn't answer your question adequately? Skip From autarkis at bad-data.net Mon May 24 06:16:44 2004 From: autarkis at bad-data.net (Autarkis) Date: Mon, 24 May 2004 12:16:44 +0200 Subject: xchat plugin - stuck References: <20040523190326.34af0393@jediknight.unstable.bad-data.net> Message-ID: <20040524121644.51d8710a@jediknight.unstable.bad-data.net> Nevermind, Problem solved. It was too stupid to explain - just forget me and my post. Python feels great! Am Sun, 23 May 2004 19:03:26 +0200 schrieb Autarkis : > Hi all > > I don't have a lot of experience in programming. I use python as a replacement for mIRC scripting in xchat. > > I made a module that looked like this. > From noamr at correctme.users.sourcephorge.net Fri May 21 10:31:30 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Fri, 21 May 2004 17:31:30 +0300 Subject: Specify start and length, beside start and end, in slices Message-ID: Hello, Many times I find myself asking for a slice of a specific length, and writing something like l[12345:12345+10]. This happens both in interactive use and when writing Python programs, where I have to write an expression twice (or use a temporary variable). Wouldn't it be nice if the Python grammar had supported this frequent use? My idea is that the expression above might be expressed as l[12345:>10]. This change, as far as I can see, is quite small: it affects only the grammar and byte-compiling, and has no side effects. The only change in syntax is that short_slice would be changed from [lower_bound] ":" [upper_bound] to ([lower_bound] ":" [upper_bound]) | ([lower_bound] ":>" [slice_length]) Just to show what will happen to the byte code: l[12345:12345+10] is compiled to: LOAD_GLOBAL 0 (l) LOAD_CONST 1 (12345) LOAD_CONST 1 (12345) LOAD_CONST 2 (10) BINARY_ADD SLICE+3 I suggest that l[12345:>10] would be compiled to: LOAD_GLOBAL 0 (l) LOAD_CONST 1 (12345) DUP_TOP LOAD_CONST 2 (10) BINARY_ADD SLICE+3 Well, what do you think? I would like to hear your comments. Have a good day (or night), Noam Raphael From rogerb at rogerbinns.com Tue May 25 01:32:25 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 24 May 2004 22:32:25 -0700 Subject: Prothon should not borrow Python strings! References: <2hfv4nFch1lmU3@uni-berlin.de> Message-ID: <4c2bo1-skr.ln1@home.rogerbinns.com> Greg Ewing wrote: > What if the file you're reading is a text file? On Windows, Linux and Mac (and most other operating systems) it is stored as a sequence of bytes. To convert the bytes to a sequence of characters (ie text) you have to know what the encoding was that produced the sequence of bytes. This can be non-trivial, but pretending that the issue doesn't exist leads you down the path and issues present today in Python and several other languages. Roger From NOmanlio_perilloSPAM at libero.it Wed May 26 15:11:43 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 26 May 2004 19:11:43 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> Message-ID: On Sun, 23 May 2004 18:36:52 GMT, JanC wrote: >Manlio Perillo schreef: > >> I'm using the Cookie module (on the client side). > >Do you know the ClientCookie module? > Yes, I know; but the standard Cookie module is sufficient. Thanks and regards From donn at u.washington.edu Fri May 28 12:39:01 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 28 May 2004 09:39:01 -0700 Subject: terminological obscurity References: <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: In article , Steve Holden wrote: ... > The important thrust of this apparently endless discussion is to > highlight the possible need for some way *other than indexing* to get > information out of a tuple. Really, most places where tuples are used, a > programmer might find it more convenient to extract the elements as > attributes - by name rather than position - hence the changes to the > os.path.stat() return value in version 2.2. People got tired of > accessing the individual values by using the appropriate index. > > I'm guessing (though in this forum I am likely to be proved wrong at > some length) that most uses of tuples could senibly be replaced by > simple "bunch"-type objects in the Alex Martelli sense: > > >>> class bunch: > ... def __init__(self, **kw): > ... self.__dict__.update(kw) > ... > >>> a = bunch(my=0, word=1) > >>> a.word > 1 > >>> > > However it's a bit late to start insisting on this usage when the tuple > has been embedded in the language so long. Sure, the stat and tm structs are a good example of what they're a good example of. Once a tuple has more than a handful of elements, you're past the cognitive limit for really workable tuples. For tuples of more reasonable size, I think most of us prefer to unpack. Even if I have to check on the order first, I'd rather write client, client_addr = service.accept() for k, v in q.items: etc. That's why the tuple has been embedded in the language so long without sprouting these features, because it works well when used well. Donn Cave, donn at u.washington.edu From moughanj at tcd.ie Wed May 12 23:51:20 2004 From: moughanj at tcd.ie (James Moughan) Date: 12 May 2004 20:51:20 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> Message-ID: <16752bcc.0405121951.7454b9be@posting.google.com> David MacQuigg wrote in message news:... > On 10 May 2004 16:53:06 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >David MacQuigg wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... > >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: > > < snip topics we have finished > > > >You are not solving a problem; that's the problem. :) If there were a > >real programming task then it would be more trivial to show why your > >object model is broken. > > I could give you an example from IC Design, but for the course I > teach, I chose to use a similar hierarchy based on something everyone > would understand - a taxonomy of animals. Nothing in this example is > something you wouldn't find in a real program to model an integrated > circuit. Instead of animal names like Cat, we would have the names of > cells in the hierarchy, names like bgref25a. Instead of a variable to > count the number of animals at each level, we might have several > variables to track the total current on each of several supply lines. > Like the counts in the Animals.py hierarchy, we need the total current > to each cell, including all of its subcells. > As far as I understand it, this is fairly different; the way I would implement it, each cell would be an instance, not a class. I would have to look at some kind of code/spec to really know, though. Do you have an example of a piece of software were you follow this approach? > I'm sure there are other examples from other specialties. In > accounting, I can imagine a hierarchy of accounts, with a total for > each account including all of its subaccounts. Don't just assume that > the problem isn't real because you haven't encountered it in your > work. Sorry, but that's not how you would do an accountancy package in OO. Again each account would be an instance, not a class, otherwise adding a new account would require either code modification or metaclass hacking. Instances scope down, and having a count of the sub-accounts stored in an object would be OK in my book. Though you wouldn't need to, since the container for the instances would do it for you. But even this isn't how you would organize an accountancy program. You'd use a database. > > > > >If you can't take it below 70 pages and you only have 4 hours... maybe > >it's not such a great idea to try this? I can't see your students > >benefiting from what you're proposing to do, if you have so little > >time. > > I think I could do it in 30 pages and 4 hours total ( lecture, lab, > and homework ), but not if I need to cover the topics that both Mark > Lutz and I consider important to basic OOP in the current version of > Python. The 30 pages assumes the unification of methods and functions > that I have proposed. > 70 -> 30 because of this? Really? Anyway, I guess you know what you have time to do, it being your course 'n all. :) > > > >> > >> What data are we talking about? numMammals is specific to Mammal. > >> genus is specific to Feline, but *inherited* by instances of a > >> subclass like Cat. > > > >The numAnimals etc... data, which is stored in Animals but gets > >arbitrarily altered by the actions of subclasses of Animal, and > >therefore is not specific to animal; it doesn't represent the state of > >the Animal class or of Animal objects, but of a whole bunch of > >subclasses of Animal. > > The total current to an IC is the sum of the currents to all of its > subcircuits. That current is a single number, for example, 35 > microamps. It has a name "Iss". Iss is a characteristic of the IC > which appears in data sheets, etc. It is a variable representing the > state of the entire IC. It does not represent the state of any > subcircuit in the IC, even though it gets "altered" whenever one of > those subcircuit currents changes. > So the IC is an instance which stores or accesses data about the instances which it contains, i.e. circuit elements; not a class which you sub-class to get subcircuit elements. I'm discussing classes and class heirarchies, not instance heirarchies. > Looks like this whole argument comes down to what we mean by the word > "specific". Let's drop it and focus on the more interesting topics in > this thread. > >From here, it looks like the problem is the difference between an instance and a class? > >> > >> These are normal programming errors that can occur in any program, no > >> matter how well structured. I don't see how the specific structure of > >> Animals.py encourages these errors. > > > >Imagine if your structure had been implemented as one of the basic > >structures of, say, Java. That is, some static data in the Object > >class stores state for all the subclasses of Object. Now, someone > >coming along and innocently creating a class can break Object - > >meaning that may break anything with a dependency on Object, which is > >the entire system. So I write a nice GUI widget and bang! by some > >bizzare twist it breaks my program somewhere else because of an error > >in, say, the StringBuffer class. This is analagous to what you are > >implementing here. > > I'll need an example to see how these general worries can affect the > Animals_2 hierarchy. What I see is quite robust. I added a Feline > class between Mammal and Cat, and I had to change only two lines in > the Cat class. ( And I could avoid even that if I had used a "super" > call instead of a direct call to the Mammal functions.) And if someone unfamiliar with the code neglects to call the superclass initializer when they create a new animal, then the code will break in unpredictable places. Not calling the superclass is a common problem - but easily fixable, *providing* the effects show up in the subclass, and not at some other random place in the heirarchy. > > >While errors are always going to happen, OOP calls on some conventions > >to minimize them. The most absolutely vital of these is that it's > >clear what can break what. Generally I should never be able to break > >a subsystem by breaking it's wrapper; definitely I should never be > >able to break a superclass by breaking it's subclass; and I > >*certainly* shouldn't be able to break a part of the system by > >changing something unconnected to it. The whole of OOP derives, more > >or less directly, from these principles. Expressions like 'A is a > >part/type of B' derive from this philosophy, not the other way around. > > Sounds good. > > >Your program breaks with this concept. It allows an event in Cat to > >affect data in Mammal and in Animal, which also has knock-on effects > >for every other subclass of these. Therefore it is bad object > >oriented programming. > > We are modeling the real world here. When you add a lion to a zoo, > you add one to the count of all animals. When you add a lion to a zoo, you add one entry in the lion table of your database. When you want to know the number of animals in the zoo, the database query counts the number of entries in all of the animal tables. *Real* databases are built that way because of experience; repetition of data invariably causes out-of-synch problems. I worked on a project a couple of years ago to port a legacy database into MySQL, and it was made damned close to impossible by this sort of thinking; how the heck do you port a database which has had it's shortcomings patched over to the point where it depends on the inconsistent results for it's output? :-\ > When you add 2 microamps to > the core currents in a bandgap voltage reference, you add that same 2 > microamps to the total supply current. > Again, I'd be inclined to handle this problem at the instance level, not the class level. > I'm no expert in OOP, but what I have seen so far is not near as clear > in structure as the origninal Animals_2 example. > When you have to troll through a 20K line program where the functionality for a single subsystem is scattered through multiple classes in a heirarchy, it puts a really different perspective on what 'clear structure' is. Likewise, when everything is modularized explicitly and you can alter a complex system which you barely understand to include completely new core functionality in an hour or two of work. > >It takes us back to the days before even structured programming, when > >no-one ever had any idea what the effects of altering or adding a > >piece of code would be. > > > >It is therefore not a good teaching example. :) > > I'll need to see something better before I abandon the curent example. > The problem may be our expectations of OOP. I see classes as modeling > the real world, including variables that are altered by changes in > subclasses. You seem to have some computer science notion of what a > class should be. I'm not saying its wrong, but unless it helps me > solve my real-world problems, in a better way than what I am doing > now, I won't use it. > You're right, I don't give a damn whether classes model the real world; what matters, in general order of preference, is: - Robustness - Maintainability - Programmer time - Efficiency I will sell any theoretical principle to the salt mines for those. 'Classes-model-the-real-world' is an abstract theory, an evolutionary holdover from when OO was the Next Big Thing in AI. If it leads you to design a non-robust, hard to maintain system then, in my book, it gets dropped. > I'm reminded of the criticism Linus Torvalds got when he first > published Linux. The academic community thought it was the worst, > most fundamentally flawed design they had ever seen. It did not fit > some expectation they had that a "microkernel" architecture was the > proper way to design an OS. Luckily, Mr. Torvalds was not dependent > on their approval, and had the confidence to move ahead. > I've been trying to explain why the pattern in your example will cause bugs; you've been justifying it in terms of OOP metaphors. *shrug* The comparison is clear enough to me... :) > >> >> I'm not sure what you mean by "side effects" here. The show() > >> >> function at each level is completely independent of the show() > >> >> function at another level. > > >> > > >> >But the inventory data isn't independent. It's affected by classes > >> >somewhere else in the heirarchy. Worse, it's done implicitly. > >> > >> The "inventory data" actually consists of independent pieces of data > >> from each class. ( numCats is a piece of inventory data from the Cat > >> class.) I'm sorry I just can't follow this. > >> > > > >numMammals OTOH is not just a piece of data from one class - it's a > >piece of data stored in one class, but which stores data about events > >in many different classes, all of which are outside it's scope. > > Exactly as we see in objects in the real world. Objects perhaps, but not classes. This seems to be the distinction which is driving this whole problem; you are regarding extending a class as if it were adding a member to an instance. > >> > > > >That's the way it has to be, if you want to write it like that. > >However there is nothing to say that a given problem must use a > >certain class structure. If you come up with a solution like this > >then it's near-guaranteed that there was something badly wrong with > >the way you modelled the domain. Either the program shouldn't need to > >know the number of instances which ever existed of subclasses of > >mammal or else your class structure is wrong. > > Trust me, the need is real. We just need to find the optimum example > to show how Python solves the problem. > Mail me some code where you need to do this in a real system, and I'll show you how to refactor it. :) > In my work as a software product engineer, I've learned to deal with > two very common criticisms. 1) The user doesn't need to do that. 2) > The user is an idiot for not understanding our wonderful methodology. > These are generally irrefutable arguments that can only be trumped by > a customer with a big checkbook. > > I generally don't engage in these > arguments, but on one occasion, I couldn't resist. I was trying to > show an expert how a complicated feature could be done much more > easily with simpler functions we already had in our program. > > His argument was basically -- every expert in this company disagrees > with you, and you're an idiot for not understanding how our new > feature works. I replied that I was the one who wrote the User Guide > on that feature. He started to say something, but it was only a > fragment of a word, and it kind of fell on the table and died. There > was a few seconds of silence, while he tried to figure out if he could > call me a liar. I just looked right at him without blinking. > > Forget what you have learned in books. Think of a real zoo. Think > how you would write the simplest possible program to do what Animals_2 > does -- keep track of all the different classes of animals, and > display the characteristics of any animal or class, including > characteristics that are shared by all animals in a larger grouping. What you're asking is how would I implement something simply, providing that I have to implement it with method X. Give me a functional spec - what the system needs to do from the user point of view - and I'll tell you how I would do it. In the case of a real zoo, I can pretty much guarantee that it would begin >>>import PySQLdb > > >And, as general rule, you should think carefully before using classes > >to store data; that's typically what objects are for. I used static > >data in programs quite a lot before I realised that it too-often bit > >me later on. > > Classes *are* objects. In Python, classes are 'first class objects' - you can pass them around as references, alter them and so on. That's in the same way as functions are 'first class objects'. That's a different and older piece of terminology than the term 'object' in OOP, which unhappily coincides with it. Wherever I can, I'll convert the discussion over to use the term instance if you're more comfortable with the terminology, but in the canonical definition a class is not an object. Objects get created from classes, and the term is equivalent to instance for practical purposes (though you get into occasional pieces of terminology like 'object instance' where it's just convenient to not have to say 'object object', and 'object variable' would get kinda confusing too.) Check any basic text on OOP for confirmation, say http://java.sun.com/docs/books/tutorial/java/concepts/ > I think you mean instances. I make a > distinction between class variables and instance variables, depending > on whether the variable is different from one instance to another. > Every instance has a different cat.name, but all cats share the genus > "feline". In fact, they share that genus with all other members of > the Feline class. That is why I moved it from Cat to Feline as soon > as our example was big enough to include a Feline class. > > > > >OK: start with the basics. We need iterative counting data about the > >individual elements of the heirarchy. > > > >The first thing is that we need to factor out the print statements. > >Your back-end data manipulation modules should never have UI elements > >in them. So, whatever form the data manipulation comes in, it should > >be abstract. > > You are adding requirements to what I already have. OK if it doesn't > slow the introductory presentation too much. > > >Secondly, we want to keep the data stored in each class local to that > >class. So, Mammal can store the number of Mammals, if that turns out > >to be a good solution, but not the number of it's subclasses. OTOH we > >could remove the data from the classes altogether. > > Think of a real zoo. If you ask the zookeeper how many animals he > has, will he tell you only the number that are animals, but are not > also lions or tigers or any other species? That number would be zero. > In a real zoo, it would not require brain-surgery on the zookeeper to introduce a new type of animal. :) Also, as I say, in a real zoo you would use a database for this task. Any good database design person would balk at the idea of even storing the number of a particular animal as an explicit variable in the database. Think about that. > I really do want numMammals to display the total number of all > mammals, whether or not they are a member of some other class in > addition to Mammal. > > If I were to guess at your objection to this, I would assume you are > worried that the different counters will get "out-of-sync", if for > example, someone directly changes one of these variables, rather than > calling the appropriate functions to make a synchronized change. > > My answer to that is to make the counter variables private. I've > added a leading underscore to those names. numMammals is now > _numMammals. > OOS due to an explicit variable alteration is pretty much the worst-case scenario, yes. It would require quite an incompetent coder to do it, but it could still easily happen. The more likely problem is the failure to call the superclass constructor - which may even be harder to debug, since at least in the other case you can run through the program in a debugger and find where the variable is being changed, or just grep numMammals. Your faith in private variables is touching. :) > >Thirdly, it would probably be nice if we had the ability to implement > >the whole thing in multiple independant systems. Currently the design > >only allows one of "whatever-we're-doing" at a time, which is almost > >certainly bad. > > ??? Supposing I want to store data for two zoos. If the data on the number of animals is stored at class-level, then I literally can't do that without closing down the program and opening up a different data set. Munging the code to have numMammals_at_zoo_1 isn't a good solution either. :) > > >After a bit of brainstorming this is what I came up with. It's not a > >specific solution to your problem; instead it's a general one. The > >following class may be sub-classed and an entire class-heirarchy can > >be placed inside it. It will then generate automatically the code to > >keep a track of and count the elements of the class heirarchy, > >returning the data you want at a method call. > > > >This is done with a standard OO tool, the Decorator pattern, but > >ramped up with the awesome power of the Python class system. :) > > My non-CIS students are not familiar with the Decorator pattern. I > fear that will make this example incomprehesible to them. > > > > >The above code is 51 lines with about 10 lines of comments. For a > >project of any size, this is a heck of an investment; I believe it > >would take a fairly determined idiot to break the system, and *most > >importantly*, they would be able to trace back the cause from the > >effect fairly easily. > > This is an impressive bit of coding, but I can assure you, as an > introduction to OOP, it will blow away any non-CIS student. It may > also be difficult to modify, for example, if we want to do what > Animals_2 does, and provide a custom display of characteristics for > each class. > Hmm, do you mean the talk method or the formatting of the inventory data? Because of the rather convoluted scoping rules you have to call say animal_farm..talk(self) to access the superclass from within the talk method, which is a minor annoyance I guess. To format the show method differently for each class would be a little more awkward, though you're not doing that at the moment. > One possibility is to make this an Animals_3 example. Animals_1 was a > simple two-class structure. It served to introduce instance > variables, and some basic concepts like inheritance. When we moved to > Animals_2, we pointed out the limitations of Animals_1, like not > having enough classes to put variables like 'genus' where they really > belong. > > Maybe we should go one more step, and make this a third example. We > can point out the limitations of Animals_2 in the introduction to > Animals_3. I can see the benefit of moving the print statements to > the top level. This is needed if we ever want to make the classes in > Animals_2 work in some kind of framework with other classes. The > show() functions in Animals_2 could be modified to return a list of > strings instead of printing directly to the console. > > I've posted your program as Solution 3 to the exercise at > http://ece.arizona.edu/~edatools/Python/Exercises/ Could you give us > a brief description of the advantages and disadvantages compared to > the original. I'm not able to do that, because I'm having difficulty > restating what you have said above in terms that students will > understand. I cannot, for example, explain why your solution is more > robust. > Advantages: Robustness; no requirement for a programmer to keep a count of instances or update the count of the super class by calling it's initializer. This minimises the chance of programmer error. Avoids replication of data, eliminating OOS errors. Maintainability; all of the code for counting is contained in a single module, so modifications will not require changes to multiple similar pieces of code throughout the class structure. Agility; we can maintain more than one zoo in a program by creating new instances of of the animal_farm class. Class level data would limit us to data on a single zoo system. Generality; the Collection class can be used for any problem of this type. > >Admittedly the solution is on the complicated side, though perhaps > >someone with more experience than me could simplify things. > >Unfortunately, a certain amount of complexity is just a reflection of > >the fact that your demands strain the OO paradigm right to it's limit. > > You could possibly implement the same thing in Java with a Factory > >pattern, and perhaps the reflection API. > > Your vast experience may be blinding you to the problems non-CIS > students will have with these more complex solutions. I may be > pushing a paradigm to some limit, but these are real-world problems > that should be easily solved with a good OOP language. > This isn't something I'd show a programming beginner either! I'd choose a different way of demonstrating a class heirarchy, myself. > -- Dave > > >(Of course I'm none too sure I could do that after many years of > >hacking Java vs a few weeks of Python!) > > > > > >> Take a look at http://ece.arizona.edu/~edatools/Python/Exercises/ and > >> let me know if Animals_2b.py is what you had in mind. If not, can you > >> edit it to show me what you mean? > >> > >> -- Dave From NOSPAM at easyconnect.fr Mon May 24 05:20:03 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Mon, 24 May 2004 11:20:03 +0200 Subject: setup Message-ID: <40b1bf45$0$2327$afc38c87@news.easynet.fr> Hi I dont understand how i can setup python with linux and minimalist unix. I would like minimum lib, maybe a static python. And very few modules, I read some documentation in README, in Module dir and on www.python.org but did not understand very weel how choose my modules I would like to buid a minimalist python to make work one program, it need only sockets, os and few things. I dont want threads but it complains about socket module after make test if i try confugure --with-threads=no. Seems that there is two problems, building python, and configuring python modules. Link to some doc welcome. Is there yet a country with a town and with a street named Guido van Rossum, or a statue with humanity benefactor written ? From dieter at handshake.de Fri May 7 14:41:01 2004 From: dieter at handshake.de (Dieter Maurer) Date: 07 May 2004 20:41:01 +0200 Subject: PEP 328 update References: Message-ID: Aahz writes on Sun, 2 May 2004 15:20:32 -0400: > PEP 328 (``import`` changes) has been updated and is available at > http://www.python.org/peps/pep-0328.html > > Comments on the revised version are welcome. One area where feedback is > particularly desired is on the frequency of relative imports inside > packages in current code, both in absolute terms and as a percentage of > all imports. When people do not like the PEP, it is almost always because of the backward incompatibilty. Fortunately, importing is a purely local affair. Why not allow to importing module to specify whether it wants to have the new or the old import semantics? E.g. by some kind of declaration... It would still be necessary for a module which relies on the old import semantics to get changed. But this change could be automated, a simple "os.walker" script could visit the complete package structure and add these declarations in all modules. Without such a declaration, lots of stupid work is necessary to bring old style modules in line with the new semantics. This is especially painful for modules that use local(!) imports of the form import a....x I fear, this must become something like from .a.... import x as x_rename from . import a In order to be able to access it later in the form "a....x". How horrible! Dieter From python-list at qbcon.com Tue May 11 08:26:34 2004 From: python-list at qbcon.com (Andreas Pauley) Date: Tue, 11 May 2004 12:26:34 +0000 (GMT) Subject: General Ledger/Accounting Libraries Message-ID: <20040511120735.E23196@bsd4.intranet.qbcon.com> Hi All, Our company is currently evaluating Python as a language for writing financial/accounting type software (among others). What libraries or packages are available in this domain for use? I've had a look at Quantlib, but it doesn't seem like exactly the type of library we're interested in. The programmers are looking for something that can be used as a General Ledger, or be used to implement a General Ledger. They're also looking for libraries that can help in the calculation of various types of interest rates, for example. On Sourceforge there's a PHP-based application called "Open Accounting" with all the relevant buzzwords in our domain. Something similar in Python would be of great help: """ An easy-to-use, web-based Accounting and Inventory system that features Sales, Purchasing, Manufaturing, General Ledger, Accounts Receivable, Accounts Payable. Additionally, has multi-currency, advanced tax manipulation and multi-language support """ Thanks, Andreas From eurleif at ecritters.biz Wed May 19 00:07:36 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 19 May 2004 04:07:36 GMT Subject: .py to binary In-Reply-To: References: Message-ID: Marco Terzuoli wrote: > I would like to convert a .py file into a stand-alone executable, so that > anyone can run it without having to install the python interpreter. I know > there is a py2exe program for Windows, but I would like to do the same for > Linux. Is it possibile or Linux only allow to use python scripts? A large portion of RPM code is written in Python, so any RPM distro (Red Hat, SuSE, Mandrake...) should have Python installed by default. I think Debian might too, so you shouldn't worry about making an installer. From lvirden at yahoo.com Mon May 10 09:44:05 2004 From: lvirden at yahoo.com (lvirden at yahoo.com) Date: 10 May 2004 13:44:05 GMT Subject: Tkinter on way out? (was: Newbe-books) References: <109hm398jc2uk3e@corp.supernews.com> <109nflv4sqeg8f7@corp.supernews.com> Message-ID: According to Cameron Laird : :In article , wrote: :>Sorry - I hit the wrong button. I guess I misunderstood wxPython - :>I thought it was designed around a specific toolkit. Does it :>provide kde and gnome desktop compatibility? If not, then it :>seems strange that pythonians would move from one non-standard :>library to another. : . :I don't know what "kde and gnome desktop compatibility" means. :I'm unconvinced the KDEers and GNOMEans do, though I'm willing :to learn. I find it exceptionally difficult to think of *any* :GUI toolkit as "standard", without considerable qualification. : :The wxPythoneers are a good group. From all I know, Tkinter :remains more broadly portable than wxPython. What I meant by such is this: Do python applications, written using wxPython, take advantage of the user's currently used KDE and/or GNOME themes, and do they communicate with appropriate desktop facilities (sessions, drag and drop, clipboard, etc.) when necessary? -- In God we trust. Even if explicitly stated to the contrary, nothing in this posting should be construed as representing my employer's opinions. From tim.one at comcast.net Sun May 30 08:31:36 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 30 May 2004 08:31:36 -0400 Subject: API : constness ? In-Reply-To: Message-ID: [Beno?t Dejean] > i don't understand why the ANSI const keyword is never used in the API. It is used in the API, and more than once, but it isn't used as often as it could be used. It's more likely to appear in newer API functions. When Python was first written, most compilers were K&R, and Python avoided ANSI features until about a decade later (a C89 compiler is required now). A lot of the C API survived unchaged across all that time. There's no objection to slamming in consts now, but nobody has cared enough to bother doing so. From ssk at chol.nospam.net Wed May 12 13:12:00 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Wed, 12 May 2004 17:12:00 GMT Subject: if Request("something") == None: doesn't work Message-ID: Hello! I use Python for ASP programming. I found something weird. Response.Write(Request("something")) It draws "None" when there's no value for something. Actually I expect "" instead of "None". So I changed it like if Request("something") == None: Response.Write("") else: Response.Write(Request("something")) Strangely, the result of comparison is False. if str(Request("something")) == "None": works! Also, if len(Request("something")) == 0: works! What's wrong? ssk From rodelrod at hotmail.com Fri May 28 06:01:23 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Fri, 28 May 2004 12:01:23 +0200 Subject: accessing elements in multi-dimensional sequences Message-ID: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> Is there an elegant way to directly refer the 2nd dimension of a multi-dimensional sequence (like the nth character in a list of strings). An example would be deleting the newline in all the strings from a list obtained through readlines without recurring to 'for' loops. I would expect this to work: >>> d ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n', '0922210996\n'] >>> del d[:][-1] >>> d ['0891931243', '0325443777', '0933477028', '0699624617', '0922210996'] But it doesn't, d remains unchanged. Another attempt produced what seemed to me like a counter-intuitive result >>> b=d[:][:-1] >>> b ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n'] Regards from a python newbie, Rodrigo Daunarovicius From tdelaney at avaya.com Tue May 11 04:10:36 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 11 May 2004 18:10:36 +1000 Subject: Unification of Methods and Functions Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01799DA0@au3010avexu1.global.avaya.com> Antoon Pardon wrote: > I'm a bit sick of this argument. There is a lot om implicity > going on in python. if obj belongs to cls then obj.method() > is syntactic sugar for cls.method(obj). That looks like > a big implicite way to handle things in python. Actually, they're not strictly the same. The instance knows which class it is an instance of - that's why the syntactic sugar can work. What you've stated is saying: class C: def f (self): pass c = C() then c.f() is identical to calling C.f(c) Now, in the above case that's correct. However, when subclasses get introduced that goes out the door. class D (C): def f (self): pass d = D() Now, d.f() is *not* identical to C.f(d). Instead it should be D.f(d). Without knowing the class that d is an instance of, it is not possible to call the correct method without the syntactic sugar. d.f() is closer to syntactic sugar for d.__class__.f(d). However, even that's not strictly correct, because c.f and d.f are bound methods - they know which instance they are bound to without any further reference to that instance. Yes - there is a lot hidden here - but what is hidden is purely implementation details. Tim Delaney From SeeBelow at SeeBelow.Nut Thu May 13 18:56:44 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Thu, 13 May 2004 22:56:44 GMT Subject: Where do I find what colors and fonts are available? Message-ID: <40A3FD3E.B1B71DA8@shaw.ca> I'm learning Tkinter, from Grayson's book and some online sources. I don't know how to find out which color names and font names are available on my system. I'm using Windows 2000. I assume that info is in some file or files somewhere, buy I don't know the file name or directory. Thanks, Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From FBatista at uniFON.com.ar Fri May 14 09:52:29 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 14 May 2004 10:52:29 -0300 Subject: Loop and the list Message-ID: It would be nice if you just post the trouble function and the values that you pass to the function and makes it behave strange. Thanks. Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 #- -----Mensaje original----- #- De: Krzysztof Szynter [mailto:dygimailNo at SPAMpoczta.fm] #- Enviado el: Viernes 14 de Mayo de 2004 10:47 AM #- Para: python-list at python.org #- Asunto: Loop and the list #- #- #- Hi all #- #- Have got a big problem. This is my code: #- #- -----BEGIN #- #stale programowe #- G = 6.67E-11 #- Mz = 6E+24 #- Rz = 6.37E+6 #- TX = range(10,780,2) #- TY = [] #- #- def skoknatezenia(ilpkt): #- "Oblicza skok" #- dr = ((2*Rz)-Rz)/ilpkt #- return dr #- #- def natezeniep(TX,TY,dr): #- "Liczy natezenie w przedziale " #- cnt = 0 #- for i in range(0,2*Rz,dr): #- TY.append((G*Mz)/((Rz+cnt)*(Rz+cnt))) #- cnt = cnt + dr #- return TY #- #- def maxvalue(TY): #gets an index of the max value in the TY list #- max = 0 #- for i in range(0,len(TY)): #- if (max True: #- try: #- Koniec2 = False #- while Koniec2 <> True: #- ilpkt = raw_input("Podaj ilosc punktow do #- wykreslenia 200):\t") #- try: #- int(ilpkt) #- ilpkt = int(ilpkt) #- Koniec2 = True #- except: #- print "Ilosc punktow musi byc liczba calkowita!\t" #- continue #- Koniec = True #- except: #- print "Nieoczekiwany blad. Sprobuj jeszcze raz." #- #- dr = skoknatezenia(ilpkt) #- TY = natezeniep(TX,TY,dr) #- print TY #first main point #- max = maxvalue(TY) #- print "max =",max #- TY = normowanie(TY) #normalize the function #- print TY #- -----END #- #- I don't understand why function maxvalue returns "9". When i start a #- program and check TY list in 'first main point', the max #- value has an index #- 0'. Then putting the list into the function maxvalue, gives #- me the index #- '9'. ;--/ #- #- Where is the mistake? #- #- ps #- Apologise for the Polish text's, in the code. I'll answer #- for any question. #- #- -- #- Krzysztof Szynter :'''. :. : * #- Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... #- http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... #- dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... #- -- #- http://mail.python.org/mailman/listinfo/python-list #- From timr at probo.com Mon May 31 20:37:54 2004 From: timr at probo.com (Tim Roberts) Date: Mon, 31 May 2004 17:37:54 -0700 Subject: http file post References: Message-ID: Dave wrote: > >Ive been trying to figure out how I can write to a file from an HTTP >post while it is being uploaded. So far ive realized that my script >isn't getting the data until the browser is done uploading. What I want >to accomplish is a way to track the progress of a file upload. This IS possible, but you'll have to do some work. I assume this is a CGI script, and that you're using cgi.FieldStorage() to fetch the POST contents. The key problem for you is that cgi.FieldStorage() (and, more specifically, cgi.FieldStorage.read_binary) does not return until the entire transmission is complete. Now that you know that, your path should be clear: all you need to do is make your own custom version of FieldStorage that updates a status variable somewhere. Piece of cake! -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tzot at sil-tec.gr Sun May 16 15:50:18 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 16 May 2004 22:50:18 +0300 Subject: web security question. References: <40A623E7.50807@cfl.rr.com> Message-ID: On Sat, 15 May 2004 09:40:47 -0500, rumours say that Jeff Epler might have written: >There's no reason to believe that the implementation of Python, >written in C, is free from buffer overflow bugs, string format bugs, or >any other of the classes of bugs that affect C programs. [snip] This message is related: http://groups.google.com/groups?selm=mailman.1042778911.1136.python-list%40python.org I didn't test if Tim's snippet produces a segfault, though. PS I have used Martin's quote when advocating for Python to other people. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From just at xs4all.nl Fri May 14 09:30:35 2004 From: just at xs4all.nl (Just) Date: Fri, 14 May 2004 15:30:35 +0200 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> Message-ID: In article <2gjokgF3mvvdU1 at uni-berlin.de>, Michael Walter wrote: > > not the application programmer. When you have the high level concepts > > written > > down by others, you don't need continuations. > Would you have an idea on how a higher-level replacement for > continuations in web application development? I'm excited (and _not_ > being any sarcastic or stuff, honestely!). Co-routines. Just From __peter__ at web.de Sun May 2 05:03:59 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2004 11:03:59 +0200 Subject: reading data columns into separate lists References: <354e45f1.0405020048.47db6957@posting.google.com> Message-ID: Viswa wrote: > I would like to read the ascii data from a file with many columns > into a list. I want the type to be float. > > data=open('dat1.dat','r') > > lines=data.readlines() > print lines > > Here, the data x1,x2,x3,x4 are separated > by tabs and end with new line. > 1\t2\t3\t4\n > ... > ... > > Is there a way to read the delimiter separated data > straightaway to a list of fixed type. from random import random # generate sample data (10 lines, 5 columns) f = file("tmp.txt", "w") for n in range(10): f.write("\t".join([str(random()) for n in range(5)])) f.write("\n") f.close() # read it into a list of lists rows = [map(float, line.split()) for line in file("tmp.txt")] print len(rows), "rows read" print "contenst of 4th row:" print rows[3] For more heterogeneous data you may have a look at the csv module (new in Python 2.3). Peter From nid_oizo at yahoo.com_remove_the_ Tue May 25 17:48:00 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 25 May 2004 17:48:00 -0400 Subject: Update with pickle In-Reply-To: References: Message-ID: Leif K-Brooks wrote: > Nicolas Fleury wrote: > >> I want to update the content of an object with a dumped object of the >> same type so that all reference to existing object are still valid. > > Add interfaces to your object's class for mutability rather than using a > low-level hack. Something like this (untested): Thx for your answer, but according to what I read about __slots__, this feature has never been intended to be used that way either, so it's also a kinda low-level hack, no? It is still an interesting solution. Regards, Nicolas From pruggera at san.rr.com Fri May 21 15:41:11 2004 From: pruggera at san.rr.com (Phil) Date: Fri, 21 May 2004 19:41:11 GMT Subject: COM server being passed an instance of an interface Message-ID: I am using a Pascal like language (Wealth-Lab) on W2K and call this server: class HelloWorld: _reg_clsid_ = "{4E797C6A-5969-402F-8101-9C95453CF8F6}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, WL ): # WL is an instance of a interface class that exists in the client # In VB this would look like Public Sub Hello(ByVal objWL As WealthLab.IWealthLabAddOn3) self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) How do I get the instance of the interface to have its methods? The Python Trace Collector gives me: Object with win32trace dispatcher created (object=None) in _GetIDsOfNames_ with '('Hello',)' and '2048' in _Invoke_ with 1002 0 3 () Traceback (most recent call last): File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 40, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, in _invokeex_ return func(*args) File "G:\Python\Dev\COM Server - win.py", line 27, in Hello return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) AttributeError: 'PyIDispatch' object has no attribute 'BarCount' pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 129, in _Invoke_ return DispatcherBase._Invoke_(self, dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 42, in _Invoke_ self._HandleException_() File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 107, in _HandleException_ reraise() File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 40, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, in _invokeex_ return func(*args) File "G:\Python\Dev\COM Server - win.py", line 27, in Hello return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) exceptions.AttributeError: 'PyIDispatch' object has no attribute 'BarCount' in _Invoke_ with 0 1024 2 () in _Invoke_ with 0 1024 2 () From fowlertrainer at anonym.hu Tue May 4 03:15:37 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Tue, 4 May 2004 09:15:37 +0200 Subject: [off] Zope - Please help me ! Postgre DA Field Types Message-ID: <121800388.20040504091537@anonym.hu> Hello ! Hello ! I want to continue the my project. http://www.zope.org/Members/fowlertrainer I need to get all of the base field types with postgresql da. http://www.zope.org/Members/spinwing/ZSQL_Results rec = context.retrieve_fields_from_test_table() print "-" * 80 print "Table field names" print "-" * 80 for name in rec.names(): print name print "-" * 80 print "Fields definitions" print "-" * 80 dict = rec.data_dictionary() for key in dict.keys(): print dict[key] Base field types: - char - varchar - int - smallint - bigint - float - decimal - boolean - blob - memo - double prec. - text - date - time - timestamp The fields must be named f*, where * is the type of field. Example: fint, fchar, fmemo. Because I have not postgresql server (windows :-( ), anybody help me to I get the field types ? Example - The MySQL field types: {'name': 'fbool', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fbit', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fdate', 'type': 'd', 'null': 1, 'width': 0} {'name': 'ftime', 'type': 't', 'null': 1, 'width': 0} {'name': 'fdouble', 'type': 'n', 'null': 1, 'width': 0} {'name': 'fyear', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fdatetime', 'type': 'd', 'null': 1, 'width': 0} {'name': 'finteger', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fchar', 'type': 't', 'null': 1, 'width': 0} {'name': 'ftext', 'type': 't', 'null': 1, 'width': 0} {'name': 'fvarchar', 'type': 't', 'null': 1, 'width': 0} {'name': 'fts', 'type': 'd', 'null': 0, 'width': 0} {'name': 'ftinyint', 'type': 'i', 'null': 1, 'width': 0} {'name': 'id', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fblob', 'type': 't', 'null': 1, 'width': 0} {'name': 'fmediumint', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fsmallint', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fnumeric', 'type': 'n', 'null': 1, 'width': 0} {'name': 'fint', 'type': 'i', 'null': 1, 'width': 0} {'name': 'fdecimal', 'type': 'n', 'null': 1, 'width': 0} {'name': 'fbigint', 'type': 'l', 'null': 1, 'width': 0} {'name': 'ffloat', 'type': 'n', 'null': 1, 'width': 0} {'name': 'freal', 'type': 'n', 'null': 1, 'width': 0} Can anybody help me ? Thanx for it. -- ?dv/Kind of Regards: fowlertrainer at anonym.hu mailto:fowlertrainer at anonym.hu From svein+usenet01 at brage.info Fri May 21 10:06:44 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Fri, 21 May 2004 16:06:44 +0200 Subject: Python compilers? References: <30260531.0405180848.42e2919d@posting.google.com> <8089854e.0405210201.2a9b6de@posting.google.com> Message-ID: Peter Hansen wrote: > Fuzzyman wrote: > >> Funnily though, most people call Java a compiled language, but it only >> compiles to Java bytecode which runs on the virtual machine. Python >> precompiles to python bytecode which runs on the python virtual >> machine. So arguably it is *as* compiled as Java..... > > Actually, there are compilers that produce native machine code from > Java for several CPUs available, and they are used at least in the > embedded world. > There is also GCJ as part of the GCC, which can compile both .class and .java files. Its libraries aren't complete yet, but I'm sure it's only a matter of time. From mcherm at mcherm.com Wed May 19 09:08:43 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 19 May 2004 06:08:43 -0700 Subject: alternatives to making blocks like { } or other ?? Message-ID: <1084972123.40ab5c5bbeadf@mcherm.com> Tim Williams writes: > I have to put my 2 cents in here. I love Python, but the one thing I > miss is using {} or something to enclose blocks. I edit in emacs > python-mode, and believe in indentation, but sometimes I'll > inadvertently change a line of code's indentation and it throws the > logic off. I found a bug in one of my programs recently where a line > of code should have been outside of an 'if', but wasn't because I hit > TAB one too many times. A {} block would've caught that. I know that's > just being careless, but I need all the help I can get! I don't mind using C-derived languages occasionally, but one thing that bothers me is having to use {} or something to enclose blocks. I use various editors, and I believe in both delimiting and indenting, but sometimes I'll inadvertently change indentation or move the position of a brace and either way it throws the logic off. I created a bug in one of my programs recently just by adding logging. It looked like this: if (some_complicated_condition) log_message("Error has occurred: taking corrective action"); take_corrective_action(); When I read through the code it LOOKED like it worked, but of course the corrective action was taken even when it wasn't needed. I've also seen more complex examples like this: if (condition_1) { code_1; } else if (condition_2) if (condition_2_a) { code_2_a; } // nothing to do for 2b else { code_3; } But the ones that I hate the MOST are the ones that my unit tests can't catch. A typical example looks like this: if (condition) { code; goes; here; } else { more; code; } Notice how that one line ("here;") is indented wrong? Obviously, that doesn't meet our coding standards, yet there's no way for the compiler to catch it, because the compiler looks only at the braces and ignores the indentation! I know that's just being careless, but I need all the help I can get! If only there were a better language I could use. -- Michael Chermside From apardon at forel.vub.ac.be Mon May 24 08:25:41 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 May 2004 12:25:41 GMT Subject: Method binding confusion References: Message-ID: Op 2004-05-22, David MacQuigg schreef : > On Mon, 03 May 2004 19:52:02 +0200, Peter Otten <__peter__ at web.de> > wrote: > >>The machinery behind the observed behaviour is now somewhat clearer - I >>think you can predict a function's behaviour as a method by checking >>hasattr(func, "__get__"). But still the *reason* (or simply use-case) for >>this dichotomy of functions (to me) remains unclear. Why are not all >>functions created equal? > > All functions and methods *should* be unified. See the section > "Unification of all function forms" in PrototypeSyntax.doc at > http://www.ece.arizona.edu/~edatools/Python > > I'm astonished at how a problem like this can be tolerated in a > language that claims to be simple. > > Here is my simplification of the example which started this thread: > > import math > > def mypow(x, y): > return x**y > > class MathA: > pow = math.pow > > class MathB: > pow = mypow > > ma = MathA() > mb = MathB() > > print ma.pow(2,4) #=> > 16.0 > print mb.pow(2,4) #=> > # TypeError: mypow() takes exactly 2 arguments (3 given) > > This problem, and a lot of others that confuse beginners could be > eliminated if all functions and methods had exactly the same sequence > of arguments (no special first argument). I agree that what you show here is a problem, because the behaviour of the language here is not consistent. However I get the impression that a lot of confusion you see with beginners is your own confusion you are passing on. -- Antoon Pardon From NOmanlio_perilloSPAM at libero.it Sat May 29 02:34:08 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 29 May 2004 06:34:08 GMT Subject: http encodings Message-ID: Hi. RFC 2068 (Hypertext Transfer Protocol -- HTTP/1.1), introduces 4 encoding names: identity gzip (x-gzip) compress (x-compress) deflate Unfortunately standard Python library does not includes these codecs in the codec registry, ad example with an http_encodings package. This will allow one to do: data = read().encode( getheader('Content-encoding').split() ) Actually identity codec is banal. -gzip: it is easy to implement using gzip module (I have written the encode and decode methods, but it should be possible to write also StreamWriter and StreamReader classes) -deflate: codec is the same as zlib_codec? -compress: where can I find it? Thanks and regards Manlio Perillo From stephen.no at spam.theboulets.net.please Tue May 25 09:32:13 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Tue, 25 May 2004 08:32:13 -0500 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: Message-ID: Just thought I'd throw this comment about the prothon tutorial in this thread: These need to be fixed: >>>"abc".upper() # convert string to uppercase XXX >>>"ABC".lower() # converts string to lowercase XXX at the url: http://prothon.org/tutorial/tutorial3.htm -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From franck.lepoutre at caramail.com Thu May 13 04:06:41 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Thu, 13 May 2004 10:06:41 +0200 Subject: Dabo 3-tier desktop framework for data-aware apps References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> Message-ID: <40a32ba4$0$2964$79c14f64@nan-newsreader-07.noos.net> "john fabiani" wrote in message news:u_roc.7515$ft5.2134 at newssvr27.news.prodigy.com... > I'm a newbie in python but with 20 years in VFP. So I'm following this > project with great interest. Ditto... well only 18 years on foxpro :) >Why recreate what UT already has? Just > add a new forum. UT supports java, C# and many other forum - why not > one for DaBo? BTW have you reviewed gnue? Just received Ed feedback on the subject. I'll post an announcement for DABO on UT to-day on Dabo team's behalf. > I picked python because I believe it's a very close match to VFP in many > ways. I think the classes are a match, no typing is a match, and many > other items. Of course list, dictionary, tuples are not matches and > along with the biggy no direct access to data. But DBAPI 2.0 looks sort > of like SPT with one exception - transactions are handled by the > connection - so no begin transaction. Either commit or rollback. > Another interesting point is there is no buffering like VFP it's handled > by the DBM (I'm using postgres) I've come thru the the same experience. The recent addition of decimal and datetime support will definitely help vfp-ers. Thanks to the python developpers for this. > The thing I miss the most is creating a cursor from the data. Something > like "Select * from curreport where some_selection into cursor > curreport". Normally I'd make a general select and then refine the data > to meet my needs. but I'm still learning how to view the data at the > moment so maybe it will come. The VFP db-aware UI side is missing. Let us hope Dabo will fill part of the gap. > I also have not discovered the way to print reports or any routines that > will generate the detail bands etc... But I have faith that they are > out there. I really hope that I don't have to hand code reports. Well ... "ReportLab" is a code-based reporting tool, not a db-aware visual tool "? la crystal" . It clearly does fit the bill at this stage as a replacement for the vfp report writer. A wx* visual report writer would be a great addition to wxpython. I've not heard of any at this stage. Fran?ois From __peter__ at web.de Sun May 9 05:15:38 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 May 2004 11:15:38 +0200 Subject: Logging module, a few questions References: <409cf0da$0$21804$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > I'm using the logging module in Python 2.3.3, with a format string > containing %(asctime). But it now dumps a full date +timestamp in > the log, which is nice but sometimes I only want the timestamp > (no date). Is there an easy way to change this? How can I make > %(asctime) dump only the time? >>> import logging as lg >>> logger = lg.getLogger("sample") >>> hd = lg.StreamHandler() >>> fm = lg.Formatter("%(asctime)s %(message)s", "%H:%M:%S") > I'm using a configuration file to set up the logging. I think in a config file that would be [formatter_xxx] format=%(asctime)s %(message)s datefmt=%H:%M:%S > Which brings me to another thing. > In java's log4j, it's easy to "silence" or "enable" specific > parts of a logging hierarchy, by doing: > > log4j.category.nl.company = DEBUG > log4j.category.nl.company.lib = WARN > log4j.category.org.apache = WARN > > and so on. > > I see no easy way of doing the same for Python's logging module; > it seems that I have to create a handler for each of the different > parts of the hierarchy of which I want to set the loglevel. > Am I missing something? >>> hd.setFormatter(fm) >>> root = lg.getLogger() >>> root.setLevel(lg.WARNING) >>> root.addHandler(hd) >>> logger.warn("so what") 10:15:59 so what >>> logger.info("so what") >>> logger.setLevel(lg.INFO) >>> logger.info("so what") 10:16:50 so what >>> root.info("so what") But does it apply to the whole branch? >>> sublogger = lg.getLogger("sample.sub") >>> sublogger.info("so what") 10:26:11 so what >>> logger.setLevel(lg.WARNING) >>> sublogger.info("so what") >>> Peter From arker at newton.astro.ca Mon May 17 08:58:19 2004 From: arker at newton.astro.ca (Dennis Craven) Date: Mon, 17 May 2004 12:58:19 GMT Subject: [PYGTK] Insert Backspace into text widget? References: Message-ID: <4ceaf81a6ca64dbe97ba4a5a6518b0fc@news.teranews.com> On Mon, 17 May 2004 08:27:22 -0400, Peter Hansen wrote: > What exactly do you expect to see when you insert a backspace > into the buffer? (Backspace is a control character, so it > is not normally "inserted into a buffer" unless you are > actually trying to display it in some way. Are you expecting > it to move the insertion point backwards one position, or what?) What you say makes sense. And yes, that is what I'm trying to do. I want to move the insertion point backwards one position, deleting the character that was at that position. Just like pressing the backspace key. Maybe the insert(iter, text) function is not the answer I'm looking for... Do you know of a way to accomplish this? Thanks, ~djc From frank at chagford.com Thu May 13 11:27:48 2004 From: frank at chagford.com (Frank Millman) Date: 13 May 2004 08:27:48 -0700 Subject: General Ledger/Accounting Libraries References: Message-ID: <246a4e07.0405130727.233a0545@posting.google.com> aahz at pythoncraft.com (Aahz) wrote: > In article , > Andreas Pauley wrote: > > > >Our company is currently evaluating Python as a language for writing > >financial/accounting type software (among others). > > > >What libraries or packages are available in this domain for use? > > The most important library is the new Decimal package, which hasn't been > released for production yet. You could start by using FixedPoint instead > until Python 2.4. Unfortunately, neither includes support for some of > the more complicated calculations you want to do; the Python community > will welcome your assistance on this (there are other people who also > want to use Python for financial calculations, and Decimal is the first > step). > I have found that doing accurate decimal arithmetic is fiddly, but not impossible. This is how I do it in my system. In my database, I declare the various numeric columns with the maximum scale that I think will be necessary. Monetary columns have a scale of 2, quantity columns have a scale of 6, etc. When I read the data in, I scale it up so that I store it internally as an integer. For data input/display purposes, I have a user-defined scale for each column, which can either be absolute (eg all quantities are shown to 2 decimals) or parameter (eg get the scale for each product from the product table, so they can vary). When I write back to the database, I scale down from the internal integer to the scale defined in the database. It does lead to some awkward code. For example, to calculate a value from a quantity and a price, I have to say value = int(round(price * value / 1000000.0)) This requires you to know what scale is used for each column, so mistakes are easy to make. As you say, the Decimal package, when it is released, will make life much easier. Frank Millman From jcarlson at uci.edu Thu May 6 02:23:52 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 05 May 2004 23:23:52 -0700 Subject: Ideas for Python 3 In-Reply-To: References: Message-ID: >>>L = [:x:x**2, :x:x+4, :x:x/5, :x:2-x, :x:x*7 ] >> >>Ick. > > Could you be more specific? :>) Sure, the general format of your anonymous function syntax given above does not offer anything that a new user can search for. Generally, new users of any language are one of two types: Self starter (looks in the help files) Asker (asks people before even checking the help files, searching google, etc.) The asker may become a self-starter, but usually only after repeated "dude, use google" replies on c.l.py. Your proposed syntax removes the ability for the self-starter to search the docs for a keyword (which is currently 'lambda'), forcing them to become an asker. > You seem to be suggesting that the current syntax is preferable. Is > this really what you would prefer: > > L = [(lambda x:x**2), (lambda x:x+4), (lambda x:x/5), > (lambda x:2-x), (lambda x:x*7)] You fail to notice that: L = [:x:x**2, :x:x+4, :x:x/5, :x:2-x, :x:x*7] needs to be: L = [(:x:x**2), (:x:x+4), (:x:x/5), (:x:2-x), (:x:x*7)] ...unless of course you want to remove the ability for anonymous functions/lambdas to return tuples. The only difference between the syntax you offer is the replacement of 'lambda ' with ':', which I don't believe is an advancement in the language. > The barrier *should* be low, but it isn't. In Learning Python, 2nd > ed., there is a 5-page section under "Advanced Topics" devoted to > lambdas. Some experts like the association with lambda calculus, even > though that doesn't help beginners. In fact, it only serves to make > lambdas seem even more mysterious. The benefit of lambdas *could* be > provided in a simple, self-explanatory syntax that requires zero pages > in a textbook and has none of the mystique that turns off beginners. How about this for a manual page for lambda... In other languages, Python's lambda would be considered an 'anonymous function', that is, a function that does not require a name.: >>> (lambda arg: arg*arg)(9) 81 Certainly you can give lambdas names with standard assignments.: >>> square = lambda arg: arg*arg >>> square(9) 81 The equivalent function definition is below.: >>> def square(arg): ... return arg*arg ... >>> square(9) 81 Generally, lambdas are functions with a single expression in its body whose value is returned. Just like normal function definitions, lambdas can take multiple arguments, contain keyword arguments, return any Python type, etc., as long as the function body is a single expression, and whose parameters match standard function definition syntax, the lambda is valid. (leave annotation and/or link to what an expression is) An ugly example of this is as follows.: >>> f = lambda a, b=1, *args, **kwargs: (a, b, args, kwargs) >>> f(1,2,3,c=4) (1, 2, (3,), {'c': 4}) Which is equivalent to: >>> def f(a, b=1, *args, **kwargs): ... return (a, b, args, kwargs) ... >>> f(1,2,3,c=4) (1, 2, (3,), {'c': 4}) > Lamdas add an unnecessary keyword and unnecessary burdens to the > syntax of the language. The benefit is very small -- being able to > cram a function definition in a tight space. Due to the mystique of > lambdas, it took me a while to realize that was their only benefit. And removing the keyword would remove their 'mystique'? No, all it would do is remove a keyword from Python. If we used your alternative syntaxes, the 'mystique' would still exist and be unsearchable. Removing the functionality entirely would result in no longer seeing the below (which you use as an example): L = [(lambda...), (lambda...), ...] But it being replaced with: def fun1(arg): return ... def fun2(arg): return ... ... L = [fun1, fun2,...] Neither of which are terribly attractive, but I prefer the lambda version. >>>f :(x): return x**2 # a simple function >>>:x:x**2 # equivalent lambda expression >>> >>>-- or -- >>> >>>f = def(x): return x**2 >>>def x:x**2 >> >>Ick on the four options just given. > > The parentheses are optional when we have colons around the arguments. > Leaving them out is my preference, but I would be just as happy with > > L = [:(x):x**2, :(x):x+4, :(x):x/5, :(x):2-x, :(x):x*7 ] I'm not icking on the parenthesis, I'm icking on the general syntax. While Python 3 is supposed to be a mythical creature that fixes all of the problems with previous versions, I don't believe that the syntax options you provide are a fix. In fact, what about the following... L[:x:x**.5] Using current python syntax, that is a slice into a sequence. With your syntax, that is an anonymous function that takes an argument and returns its square root, that is used as an index into some mappable type. Are you also talking about changing slice syntax? As for a. f :(x): return x**2 b. f = def(x): return x**2 c. def x:x**2 a. Also looks like a bad slice to me. b. What was wrong with: def f(x): return x**2 c. Now you're just replacing the lambda keyword with the def keyword. > This would more strongly highlight the argument x, and still have a > form that parallels the standard function definition. > > How about this: > > f(x): return x**2 > (x):x**2 > > Neat and clean, but I don't know if there would be parser problems First looks like magic. Second looks like a slice. Neither are neat and clean. > with the short form. Unlike the long form, which can only occur at > the beginning of a line, the short form might occur in a dictionary > item, where the colon could lead to ambiguity. Maybe we could say > lambdas in dictionaries must be enclosed in parentheses, or maybe just > not allow them at all where they might cause ambiguity. With the 'lambda' (or other equivalent) keyword, there does not exist ambiguity. Your removal of the keyword seems to not add any understandability to the syntax (or the one-line-function 'problem'), but adds ambiguity to the meaning of an equivalent anonymous function. I thought Python was about removing ambiguity, not encouraging it. >>>I am especially interested in feedback from users who have recently >>>learned Python. I suspect that many experienced users will have long >>>forgotten any difficulties they had while learning. >>Learning lambda expressions are trivial when you have experience with >>derivatives of LISP. While I generally don't like to point users off to >>go RTFM, in this case, 5 minutes of manual reading (without LISP >>experience) will go a long way toward understanding lambda expressions. > My users ( EE students and professional design engineers ) have no > experience with LISP. I agree, 5 minutes should be enough to explain > lambdas properly, but unfortunately, they are not explained properly > in the texts I have seen. So why are you explaining lambdas to them? If they are having difficulty understanding them, then don't teach it. Since you are also advocating the removal of the lambda functionality entirely, I see no reason to show them something that they are going to struggle with understanding. If you are still going to teach them lambdas, then do it by example. Give a simple function definition, translate it into a lambda, then have them do it. I find that learn-by-example works pretty well, at least for simple algorithms like definition-to-lambda. If your students can't translate a few simple function definitions to lambdas, then Iyou should ask yourself if they deserve to get degrees in their field. > In my humble opinion, GvR should have ignored the experts who told him > lambdas were great, and just applied some simple common sense to find > a better solution. I don't believe that lambdas were a solution to a problem. I believe the /desire/ was to have a way of defining simple functions in a general fashion. They do just that, allow simple functions to be defined in a general fashion, albeit using a slightly altered function syntax. Their ability to be placed in lists, gain names, etc., was a side-effect of them being Python objects. - Josiah From rick.ratzel at scd.magma-da.com Fri May 21 17:21:24 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Fri, 21 May 2004 16:21:24 -0500 Subject: better way of executing expression/statement in C? In-Reply-To: References: Message-ID: <40ae72d5$0$90377$39cecf19@news.twtelecom.net> This might be slightly less kludgy...I tested it by implementing a crude input loop. Here is the output: [rlratzel at triumph ~/exp] ./pyexec >> a=3 RESULT: NULL >> b=4 RESULT: NULL >> a+b RESULT: 7 >> c=4 RESULT: NULL >> a+c RESULT: 7 >> import os RESULT: NULL >> Done. Here is the code: file: pyexec.c -------- #include #define INLEN 1024 /* * get string rep of a Python obj */ const char* getPyObjStringRepr( PyObject* pyObj ) { if( pyObj == NULL ) { return "NULL"; } else { return PyString_AsString( PyObject_Str( pyObj ) ); } } /* * print the results of evaluating Python expressions and statements */ int main( int argc, char** argv ) { PyObject* mainModObj; PyObject* mainDictObj; PyObject* returnObj; PyObject* resultObj; char userInput[INLEN]; Py_Initialize(); /* * create a different display hook to set a result var * rather than print to stdout and set __builtin__._ */ PyRun_SimpleString( "import sys, __main__" ); PyRun_SimpleString( "def my_displayhook(o): __main__.__result=o" ); PyRun_SimpleString( "sys.displayhook=my_displayhook" ); /* * get the __main__ symbol table for evaluating within the top-most * scope and retrieving the result */ mainModObj = PyImport_AddModule( "__main__" ); if( mainModObj == NULL ) { return -1; } mainDictObj = PyModule_GetDict( mainModObj ); /* * start an eval loop...only print 2 arrows since we are * not really trying to be Python */ printf( ">> " ); /* * start the loop */ while( fgets( userInput, INLEN, stdin ) != NULL ) { /* * run a string from the command line like the interactive interp * does, handling both expressions and statements */ returnObj = PyRun_String( userInput, Py_single_input, mainDictObj, mainDictObj ); if( returnObj == NULL ) { PyErr_Print(); return -1; } /* * get the result as set by the displayhook and print it out */ resultObj = PyDict_GetItemString( mainDictObj, "__result" ); printf( "RESULT: %s\n", getPyObjStringRepr( resultObj ) ); Py_DECREF( returnObj ); if( Py_FlushLine() ) { PyErr_Clear(); } /* * if a result was set, delete it so statements which dont return * a value dont return a prior set value */ if( resultObj != NULL ) { PyRun_SimpleString( "del __main__.__result" ); } printf( ">> " ); } printf( "Done.\n" ); return 0; } -------- Not sure if that is exactly what you were looking for, but it does allow one to execute statements and expressions and process the result (if any). -Rick Ratzel David Faden wrote: > Hi, > > Given arbitrary Python source code input by the user, I want to get the > result of executing that source as an expression if it is an expression > and otherwise execute the source as a statement. Currently, I'm > accomplishing this as follows (in a category on NSString), but it seems > kludgy to rely on detecting a syntax error. > > - (PyObject*)executePythonSourceWithGlobals:(PyObject*)globals > { > const char* source = [self UTF8String]; > PyObject* result = PyRun_String(source, Py_eval_input, globals, > globals); > if (!result && PyErr_ExceptionMatches(PyExc_SyntaxError)) { > PyErr_Clear(); > result = PyRun_String(source, Py_file_input, globals, globals); > } > return result; > } > > How would you accomplish this? How does the interpreter do it? > > Thank you. > > David > AIM: pitulx > > From michele.simionato at poste.it Fri May 14 05:21:18 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 14 May 2004 02:21:18 -0700 Subject: Stackless python and microthreads References: Message-ID: <95aa1afa.0405140121.52a6d8e0@posting.google.com> "Mike C. Fletcher" wrote in message news:... > Continuations (which are the coolest things since programming was > invented) were forced out of Stackless Python around the end of version > 2.0 for political reasons IIRC. Current Stackless doesn't have > continuation support at all, so any version of micro-threads written to > use continuations is just dead-on-arrival for the current version. > Stackless 1.0 and 2.0 were only for pre-2.3 releases of Python AFAIK. > > In a former life I got paid to work on extending the continuation-based > micro-thread implementation... continuations are the most awesome toys > you can imagine... we will all mourn their passing in time... > > Good luck, > Mike Uhm ... My experience with continuations (in Scheme) is limited, but I really wonder if continuations have a place in a high level programming language. I mean, continuations are basic building blocks: you can build on top of them exception systems, generators, coroutines, microthreads, etc, and it is an interesting learning experience to understand how this is done. However, to pass from continuations to something useful takes a LONG way. Continuations are a too low level concept. A high level language should already provide the right high level tools. I mean, the language designer should implement generators, exception systems, microthreads, etc. not the application programmer. When you have the high level concepts written down by others, you don't need continuations. So I guess now Stackless has microthreads built inside, and the application programmer is not forced to write them on top of continations. Speaking in general, generators and the current exception system are more than enough for my typical needs in Python: which kind of applications do you have in mind where you would like to have continuations? (a part from microthreads and things like changing the language introducing new control structures, etc, all stuff than should not be left to the application programmer, IMHO). Michele From __peter__ at web.de Thu May 6 11:36:31 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 17:36:31 +0200 Subject: Scope rule pecularities References: Message-ID: Antoon Pardon wrote: > work arounds to make it work. The point is that although a += b > is supposed to be syntactic sugar for a.__iadd__(b), you need > a global (and even that won't help if you have nested functions > and the a is on an intermediate level) to make the first work > but not for the second. a += b is not just syntactic sugar for a.__iadd__(b), it also rebinds a: >>> class A: ... def __iadd__(self, other): ... return "marker" ... >>> a = A() >>> a.__iadd__(None) 'marker' >>> a <__main__.A instance at 0x4029bbac> >>> a += None >>> a 'marker' >>> The equivalent a += b would then roughly be a = a.__iadd__(b). Peter From __peter__ at web.de Wed May 26 08:58:17 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 14:58:17 +0200 Subject: Cleaner idiom for text processing? References: Message-ID: Peter Hansen wrote: > Peter Otten wrote: > >> But if that lets you sleep better at night, change Peter Hansen's >> suggestion to use islice(): > > No! Yours is much more elegant! Wonderful... zero overhead. I should mention I've picked up the trick on c.l.py (don't remember the poster). Peter From jcarlson at uci.edu Fri May 7 03:46:23 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 07 May 2004 00:46:23 -0700 Subject: Scope rule pecularities In-Reply-To: References: Message-ID: > Well I would say that seems to go against the intention as stated > in the reference manual. += and associated should attempt the > operation in place. If you do an operation in place there is > no need to rebind the variable. Except when the /referenced object/ is immutable. Name rebinding is necessary to reference the newly created immutable object that was created through the +=, -=, /=, %=, *=, &=, |=, or ^= operations. If you have some magical way of not rebinding the name, I'm sure we'd all like to hear it. - Josiah From Mike at DeleteThis.Geary.com Wed May 5 15:44:27 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 5 May 2004 12:44:27 -0700 Subject: Improvement ? References: Message-ID: <109ih0s4i7ugk40@corp.supernews.com> Jean-Marc Ranger wrote: > With Python 2.3.3 for Windows, I understand why > os.makedirs("C:\SomeDirectoryThatDontExist\.\AnotherDirectory") > fails throwing an exception saying "OSError: [Errno 17] File exists" - > the period is like a request to create the same directory a second time. > > But is this the expected behavior ? I personaly would prefer to see > this operation succeed - and don't like the idea of writing a > workaround :) It feels like a bug to me. I would expect os.makedirs to run its argument through os.path.abspath first. But, you can easily do that yourself: >>> os.path.abspath("C:\\SomeDirectory\\.\\AnotherDirectory") 'C:\\SomeDirectory\\AnotherDirectory' >>> Also, you got very lucky with your backslashes: >>> "C:\SomeDirectory\.\AnotherDirectory" 'C:\\SomeDirectory\\.\\AnotherDirectory' >>> "C:\someDirectory\.\anotherDirectory" 'C:\\someDirectory\\.\x07notherDirectory' >>> -Mike From sholden at holdenweb.com Thu May 27 08:11:51 2004 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 27 May 2004 08:11:51 -0400 Subject: Downloading SCXX In-Reply-To: <10b9tgg4q0p6j2e@corp.supernews.com> References: <10b9tgg4q0p6j2e@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Peter Hansen wrote: > >>Nick Jacobson wrote: >> >> >>>I've been trying to download SCXX, but the website >>>http://www.mcmillan-inc.com/ has been down for the last few days. >>>Where else can I find it? Thanks in advance. >> >>I believe attempts to reach mcmillan-inc.com have failed for the >>last few *months*, not just the last few days. I don't recall >>seeing any comment about it except (or did I just imagine it?) a >>comment from someone that Gordon was indeed alive, but occupied >>with other things... >> >>-Peter > > > Gordon's alive, enjoying the spring weather, and > has non-specific plans to restore the Web site. In the meantime, be grateful to Paul Baranowski for http://paulbaranowski.org/Downloads/installer_6a2.tar.gz regards Steve From jmcalvar at telecable.es Wed May 12 11:33:55 2004 From: jmcalvar at telecable.es (=?ISO-8859-1?Q?Jos=E9?=) Date: Wed, 12 May 2004 17:33:55 +0200 Subject: connexion to all the servers In-Reply-To: References: Message-ID: Now the problem is different. I can do the first part, and is good, but if I try to send a message from server to the clients, I can only send the first message, and can't the other three. Here I have the code. Code from client (first request): #!/usr/bin/env python from socket import * import sys from os.path import * from os import * sock = socket(AF_INET,SOCK_STREAM) sock.connect(('192.168.4.115', 6969)) tm = str(getsize("/var/log/apache2/access_log")) message = tm if ( tm > 50 ): sock.send(message) sock.close() Code from server (second request): #!/usr/bin/env python from SocketServer import BaseRequestHandler, TCPServer from socket import * import sys class manejador(BaseRequestHandler): def handle(self): print "Conected Client: ", self.client_address datos = self.request.recv(4096) self.request.close() print "los datos: ", datos while ( datos != 0 ): a=['172.26.0.138','192.168.4.111','192.168.4.112', '192.168.4.113','192.168.4.114'] for i in range(len(a)): web = a[i] sock = socket(AF_INET,SOCK_STREAM) sock.connect((web, 6970)) message = "adelante" sock.send(message) sock.close() TCPServer((('',6969)), manejador).serve_forever() and this is the client server script, the last: !/usr/bin/env python from SocketServer import BaseRequestHandler, TCPServer import sys, socket from os.path import * from os import * class manejador(BaseRequestHandler): def handle(self): print "Cliente Conectado: ", self.client_address datos = self.request.recv(4096) self.request.close() archivo = isfile("./rotatelogs") if ( archivo == False ): print "success" else: print "errorrrr" TCPServer((('',6970)), manejador).serve_forever() From claird at lairds.com Mon May 17 14:09:19 2004 From: claird at lairds.com (Cameron Laird) Date: Mon, 17 May 2004 18:09:19 -0000 Subject: pexpect module References: Message-ID: <10ahvufel3af44b@corp.supernews.com> In article , Gianluca Trombetta wrote: >hmmm, i'm not so stupid...:-). >The command ls -l | more was an example...i'm not really need to run ls -l | >more in an automate program. >But I need to run some cisco commands like "show ip bgp summary", this >command print a table and put a "More" by default, if the table is too big >for a single terminal screen. >So I need to remove this behavior because if I match the " --More-- " with >expect module i can match only the first one "More", then this the program >crash and receives a timeout. . . . Crashing isn't good, of course. There definitely are solutions. They likely depend on details, to the level that it's not enough to address Cisco commands "like" show ip ... Instead one needs to focus on exactly which commands are in play. While I don't have my Cisco manuals handy, I believe there's an environment variable or command-line flag that instructs show ... to report all its results without screen formatting. Find that, and use *that* form of the command. It will simplify your pexpecting. -- Cameron Laird Business: http://www.Phaseit.net From segphault at sbcglobal.net Sun May 23 10:14:42 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sun, 23 May 2004 14:14:42 GMT Subject: Issues in compiling Python to machine code References: <40b089a5$0$16599$5a62ac22@freenews.iinet.net.au> Message-ID: On Sun, 23 May 2004 21:23:19 +1000, Johnathan Doe wrote: > I've been thinking about what the issues would be in compiling > Python into native machine code, and since type information is > important in Python, it seems possible that Python code can > be compiled into native machine code (albeit with a lot of > extra effort). > > For instance, type information is discovered when something is > assigned to a variable or an anonymous piece of data is used > in a program. Compiling Python bytecode into native machine > code could involve a pass over the bytecode to look at all the > uses of a variable or anonymous variable, call some Python > function to discover its variable, then record it in the symbol > table. > > Another issue is what to do with objects. Finding the offset > to a pointer which is the object's constructor, for instance, > if that's the way it's done internally in Python. > > And then freeing the memory used by an object when it's no > longer needed. Perhaps freeing memory for an object can be > done by inserting machine code to return memory back to the > heap after the first pass over the bytecode and recording the > place a variable is last used (hopefully then it won't be > used in some other way later of course... perhaps it can > record all cases where that variable is referred to by another > name and track them, too.) > > Seems like compiled Python would need a lot of support code, > in any case, that gets run at certain times: before the program > starts, whenever a variable is accessed, before an object is > used (to allocate memory), whenever something happens to data > within an object (allocate/reallocate/destroy), and so on... > > Are there any reasons why Python would be *impossible* to compile? > > Thanks :) we have talked about this here before, I think. Native compilation wont improve runtime speed of a dynamically typed language. Despite this, there are actually a few projects out there endevouring to do it anyway. If you want better speed from a python application, try a customized python runtime engine like Psyco. --SegPhault From fperez528 at yahoo.com Sat May 15 16:26:17 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 15 May 2004 14:26:17 -0600 Subject: bug in inspect (was cgitb vs traceback) References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> <40A5D206.3000901@jessikat.fsnet.co.uk> <40A5D94D.6010708@jessikat.fsnet.co.uk> <40A6743B.7050500@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > It's bug 954364. Your method is exactly what I did ie inject the patched > functions into inspect at run time. Python may not be so easy to patch > in future if altering other module's name spaces becomes harder. Many thanks, Robin. Indeed, I worry about module namespaces becoming 'protected', since I use a LOT the ability to inject things where I need them at runtime. I suspect if they actually go ahead with this approach, IPython is going to break in horrible ways. I really hope this kind of thing is done _optionally_, but that python continues to 'treat programmers as adults'. I know what I'm doing is hackish, but I do it knowingly (and because I need to). So please, python, assume I'm old enough to know how to handle a sharp blade and don't wrap it in foam for me. Sometimes I need to cut things harder than a banana :) Best, f From NAIGIMSESRIMAIL at gims.com Sat May 15 17:02:47 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sat, 15 May 2004 23:02:47 +0200 Subject: ALERT - GroupShield ticket number OB19_1084654959_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: bhoel at web.de Sent: -181348352,29637311 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From cjw at sympatico.ca Sat May 22 12:59:32 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 22 May 2004 12:59:32 -0400 Subject: terminological obscurity In-Reply-To: References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> Message-ID: David Eppstein wrote: > In article <40aec6ff$0$17254$a1866201 at newsreader.visi.com>, > Grant Edwards wrote: > > >>>Can't it be said, in helping to distinguish a Python list from the >>>standard collections in, say, Java and C++ - that among its most >>>important attributes is the ease with which one can work with a list >>>as a collection of objects of *heterogenous* type. "Type" here being >>>used in the sense that programmers generally use the word. >> >>I think the fact that Python lists can be heterogogenous is one >>of the most brilliantly useful things in the language, but >>apparently we're not supposed to use lists like that. > > > It's not heterogeneity of type you're supposed to avoid, it's > heterogeneity of purpose. That is, you should be intending to treat > each cell of the list similarly. > Section 3.2 of the Python Reference Manual has Tuples: The items of a tuple are arbitrary Python objects. Lists: The items of a list are arbitrary Python objects. The generality of that seems clear. Can we not leave 'purpose' to a book of best practices? Colin W. From cs993442 at cs.yorku.ca Wed May 5 11:44:08 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Wed, 05 May 2004 11:44:08 -0400 Subject: Zero-fill shift In-Reply-To: References: Message-ID: <40990BC8.7000306@cs.yorku.ca> Great, this works. 8-) Unfortunately, I've run into another problem. In the Java algorithm, two integers are added. This often results in an overflow and a negative number, which is the desired result. However, I can't seem to duplicate that in Python, as adding two integers that are too large just results in a long (and using the int() method doesn't work). I've tried various solutions, but haven't come up with something that duplicates this behavior exactly. For reference, here's the Java code I'm trying to duplicate: while(n-- > 0) { sum += delta; y += (z << 4)+a ^ z + sum ^ (z >>> 5) + b; z += (y << 4)+c ^ y + sum ^ (y >>> 5) + d; } with the following initial values: y = 1751477356 z = 1864398703 a = 2002870900 b = 858797621 c = 1751607922 d = 875968626 sum = 0 delta = 0x9E3779B9 n = 32 Any help would be greatly appreciated. ^^; Thanks! --Daniel > def srl(a, b): > return (a & 0xFFFFFFFFL) >> b > > "a & 0xFFFFFFFFL" behaves as if you had written "(unsigned int) a" in C. From davidf at sjsoft.com Thu May 13 11:54:56 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 13 May 2004 17:54:56 +0200 Subject: PEP: import version In-Reply-To: References: Message-ID: Peter Otten wrote: > Manlio Perillo wrote: > > >>A possible syntax is this: >>import wxPython version '2.4' > > > Why not just > > import wxPython2_4 as wxPython > > and a symlink or something equivalent pointing to the latest version > to also allow > > import wxPython We've been discussing different approaches to allow version import on the wxPython list. See the wiki entry at http://wiki.wxpython.org/index.cgi/VersionSelection My latest code is attached, which allows selection via command-line parameters, assuming wxPython is installed in well-named subdirectories. See the wxpython users list for more info David -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: wxselect.py URL: From peter at engcorp.com Sat May 22 09:01:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 May 2004 09:01:16 -0400 Subject: cannot import csv In-Reply-To: <425cc8d1.0405220458.9668650@posting.google.com> References: <425cc8d1.0405220458.9668650@posting.google.com> Message-ID: mir nazim wrote: > hi, > i m unable to import csv module. > it says: > > ImportError: no module named csv. > > plz help me. > > is csv module not a part of standard dist? c:\>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 >>> import csv >>> csv.__file__ 'c:\\a\\python23\\lib\\csv.py' It surely is on Python 2.3, anyway. -Peter From dai4happy at yahoo.com Sat May 8 10:11:53 2004 From: dai4happy at yahoo.com (angel) Date: Sat, 8 May 2004 22:11:53 +0800 Subject: Help me. How to open a new IE window? References: Message-ID: It's work. Thanx again! angel "Dave Brueck" ??????:mailman.355.1084020373.25742.python-list at python.org... > angel wrote: > > I want python(win32com) to open a new IE window. > > Source is: > > /******/ > > import win32com.client > > msie = win32com.client.Dispatch("InternetExplorer.Application") > > msie.Visible = 1 > > msie.Naviagte(http://www.python.org) > > /******/ > > The problem is the program always grabs a existed IExplorer window or > > Explorer window. It never opens a new window. > > I ran into that same problem. Try this: > > msie = win32com.client.DispatchEx('InternetExplorer.Application.1') > > It seems to work for me. > > -Dave > From dmq at gain.com Sat May 22 16:18:57 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 22 May 2004 13:18:57 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> Message-ID: <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> On Sat, 22 May 2004 12:10:51 -0600, "Dave Brueck" wrote: >David MacQuigg wrote: >> If Python were consistent, and *always* used a special first argument, >> there wouldn't be a problem. The magic first argument would be no >> more difficult than magically setting a global variable. The problem >> is that some methods require a magic first argument, and others >> require that it *not* be there. In one case you call cat1.talk() and >> in another it is Cat.talk(cat1). > >But the above explanation misses one very important point: one is used 99.9% of >the time, the other 0.1% of the time, if that. Mentioning them side by side >like you do implies that they are both equially common, which is not remotely >the case. I can't comment on the usage statistics you cite, but it seems to me that unbound methods are more important than these statistics would imply. They are necessary to make the language complete, so you can do things that would otherwise require creating an artificial instance just to call a method. Learning Python also treats unbound methods as much more "normal" than your argument would imply. >> I know this is not terribly >> difficult to understand -- one is a bound method, the other unbound. >> Still it is a problem for beginners, and it leads to unecessary >> complexities like static methods. > >I don't see how this is at all related to static methods. A method is some >piece of functionality that is specific to a particular class. If you have some >function already lying around, why would you want it as a method, much less a >static method? (I can think of a couple of rather contrived examples, but >nothing compelling or common in a normal application - help me out here) Here is an example from our CDP ( Circuit Design Platform ): class Bag: def __init__(self, **kwargs): self.__dict__.update(kwargs) def load(infile): strng = infile.read() exec( 'bag = Bag(\n' + strng + ')' ) return bag load = staticmethod(load) We need to load a "statefile" with a deeply nested hierarchy of parameters, which will then be represented by a "Bag" of parameters at each level of the hierarchy. The load method needs to be called before any Bag exists, so we add the magic "staticmethod" line, and don't worry about 'self'. Sure, we could move the load function outside of the Bag class, but that would disrupt the natural structure of the program. The load function is unique to Bags, and it belongs in the Bag class. See the thread "classes vs dicts" and the discussion following my post on 5/13 for more on statefiles and Bags. See also http://www.ece.arizona.edu/~edatools/Python/Statefiles for the latest on our solution to the statefile problem (how to handle thousands of deeply-nested setup parameters). >> The recent discussion on "Method binding confusion" 5/2/04 shows that >> even experts can get confused. Here is the example, reduced to its >> simplest terms: >[snip example that IMO doesn't reflect any sensical use case] >> How would you explain this to non-CIS students in a class on circuit >> design, where there is very little time to discuss programming? > >What kind of an instructor would bring this up in an introductory programming >course? If you're short on time, there are oodles and oodles of more commonly >used topics to cover. Seems like my challenging statement was misleading. I have no intention of bringing up strange binding problems in an introductory class. This was a challenge to those who think that Python's binding syntax is simple. Even an example as strange as this would be no problem for a student if the new syntax were adopted. >I find the current distinction between methods and functions as one that makes >quite a bit of sense. It doesn't really cause problems, and I've yet to see a >proposal that is cleaner while still making as much sense (IOW, perhaps it IS >imperfect, but I can't think of anything better, and apparently nobody else can >either). Have you read the proposal at http://www.ece.arizona.edu/~edatools/Python ?? The folks at prothon.org also think they have a better solution. There are some good ideas amongst all the crud. Unification of methods and functions is one. It remains to be seen if they can do this without introducing other equally bad complexities. Smooth the carpet in one place, and the wrinkles pop up somewhere else. When you say the distinction between methods and functions makes sense, I assume you mean it has some value to the user. I would like to hear more about this, because I am assuming just the opposite. In my OOP chapter, I rely on the fact that students already understand functions. I use the term "method" only when it is necessary to make a distinction. Otherwise, everything is just a function, and there is only one kind. >Most importantly, I've yet to see it cause any real or lasting problems for >beginners - either (1) nobody cares unless you point it out and make an issue >out of it, or (2) they ask, you take 30 seconds to explain it, and they say, >"oh, ok" and move on. Occasionally someone particularly bright (and/or with >experience in certain other languages) will really grasp the 'why' behind the >difference, and you'll see the light go on as they begin to understand the >power available to them. I think there is a tendency to assume that whatever you have learned is just the way things have to be. I was assuming that about Python until someone prodded me to look at Ruby. That got me interested in other languages, like Prothon. It wasn't until I looked at Prothon that the light came on regarding this unification issue. Until that time, I was assuming, like everyone else, that static methods, lambda functions, and lots of other warts were fundamentally necessary. The best introductory text on Python is Mark Lutz' Learning Python, 2nd ed. He takes 96 pages to cover OOP, and he doesn't waste time on unnecessary topics like metaclasses. I believe an improvement in Python's syntax could make it possible to cut the number of pages in half, and still reach the same level of proficiency in solving real-world problems. Why is it we can see there is clutter in Perl, but we can't see it in Python? -- Dave From me at privacy.net Wed May 26 04:28:48 2004 From: me at privacy.net (Duncan Booth) Date: 26 May 2004 08:28:48 GMT Subject: newbie: how to capture/write to stdio on NT References: Message-ID: "Sholtz" wrote in news:jLMrc.5349$Tn6.1709 at newsread1.news.pas.earthlink.net: > I am trying to figure out how to 'control' the input & output using > popen/popen2 etc on Python 2.3 > I have found examples for unix such as the one below but I can't get > it to work on Windows NT. > > If I use the os.popen module I can read OR write not both. > > > # Open command in a pipe > # which reads from stdin and writes to stdout > > import popen2 > pipe = popen2.Popen4("wc -l") # Unix command > pipe.tochild.write("line 1\nline 2\nline 3\n") > pipe.tochild.close() > output = pipe.fromchild.read() > As the documentation for popen2 says, the methods such as popen4 exist on windows, but the classes don't. So you have to use: >>> import popen2 >>> pipeout, pipein = popen2.popen4("more") >>> pipein.write("line 1\nline 2\nline 3\n") >>> pipein.close() >>> print pipeout.read() line 1 line 2 line 3 >>> Also be sure to read the section of the documentation about flow control issues. If there can ever be more than 4k of output waiting to be read your code will deadlock. If the program is trying to read input, then you won't get any output until it has read enough or you close the input. The simplest thing is to always be sure to read pipeout on a different thread than you use to write to pipein. You cannot use 'select' on windows pipes. From mhammond at keypoint.com.au Sat May 8 22:55:03 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Sun, 09 May 2004 12:55:03 +1000 Subject: How python ActiveX to access DHTML document? In-Reply-To: References: Message-ID: angel wrote: > Hi > > I want to write an ActiveX by using python. And I know how do, but I don't > know how python to access DHTML Document.If using cpp, it can be done by > following source. > /****/ > CComPtr spContainer; > m_spClientSite->GetContainer(&spContainer); > CComQIPtr spDoc(spContainer); > if (spDoc) > spDoc->put_bgColor(CComBSTR(_T("pink"))); > /****/ > Who can tell me how to do the same in python? Thanx IOleContainer isn't supported by win32com. Let me know if you are interested in helping add it (it is very hard to add new interface support correctly without a usecase) In the meantime, try and find an IDispatch based way of doing it. Mark. From htx1 at gmx.de Tue May 11 09:33:31 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Tue, 11 May 2004 15:33:31 +0200 Subject: Performance of cPickle module In-Reply-To: References: Message-ID: sh at defuze.org wrote: > [...] > If I had to use a database, the database would keep track of my users and I > would only need to do a SQL statement. Would the cPickle more efficient in my > case than a database ? > > To give a bit of code let's say that I have something like : > > import cPickle > > class UserData: > def __init__(self,name,email): > self.name = name > self.email = email > > class Users: > def __init__(self): > self.users = {} > self.hasChanged = false > > def _deserialize(self): > if self.hasChanged == false: > self.users = cPickle.load('users.dat') > else: > #parse the xml file... > > Is it an efficient method ? > > Thanks > - Sylvain Hi, this may be interesting for others, too. I modified the example given above a little, entered 1000 users and saved and loaded the Users object 1000 times using cPickle on an Athlon 1GHz. The results are: [...] 995 996 997 998 999 real 5m26.115s user 3m59.570s sys 0m5.060s That are 0.326s per save/load-roundtrip. -rw-r--r-- 1 holger users 173972 2004-05-11 15:23 test.pickle For 10 users: [...] 995 996 997 998 999 real 0m5.148s user 0m2.710s sys 0m0.740s 0.005s per roundtrip. -rw-r--r-- 1 holger users 1708 2004-05-11 15:25 test.pickle That should be fast enough for a weblog application. The http/cgi-overhead and the concurrent access on the pickled objects when writing them will probably be the harder problems. Greetings, Holger Here's the program: #!/usr/bin/python import string, random, cPickle def randString (l): return "".join ([string.letters [random.randrange (l)] for i in range (l)]) class UserData: def __init__(self,name,email): self.name = name self.email = email class Users: def __init__(self): self.users = {} u = Users () for a in range (1000): u.users [randString (20)] = (UserData (randString (40), randString (40))) for a in range (1000): print a f = open ("test.pickle", "w") p = cPickle.Pickler (f) p.dump (u) f.close () f = open ("test.pickle", "r") p = cPickle.Unpickler (f) u = p.load () f.close () From roy at panix.com Thu May 20 11:55:44 2004 From: roy at panix.com (Roy Smith) Date: Thu, 20 May 2004 11:55:44 -0400 Subject: comparing strings and integers References: <3064b51d.0405191326.124a3ab3@posting.google.com> <3064b51d.0405200725.c19102d@posting.google.com> Message-ID: In article <3064b51d.0405200725.c19102d at posting.google.com>, beliavsky at aol.com wrote: > Thanks to S. Nowaczyk and others for the helpful replies. If one wants > > if (a > b) > > to raise an exception when the comparison is not "sensible", maybe an > alternative way of writing it is > > if ((a - b) > 0) > > This should work when 'a' and 'b' are numerical and will fail if one > is numerical and the other is a string. A down side is that it does > not permit string comparisons, but I rarely compare strings except for > equality in my code. How do you define "sensible"? From beliavsky at aol.com Fri May 14 11:58:04 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 14 May 2004 08:58:04 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 References: Message-ID: <3064b51d.0405140758.4c556d8e@posting.google.com> Thanks to the Python developers for their continuing work. I wonder why the Linux installation needs to be more tedious than the Windows counterpart. The problem is of course not specific to Python. There are many Linux distributions, running on different kernels, but maybe binaries that have been tested on the "major" distributions like Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. Compare the instructions: WINDOWS "Windows users should download the Windows installer, Python-2.3.4c1.exe, run it and follow the friendly instructions on the screen to complete the installation. Windows users may also be interested in Mark Hammond's win32all, a collection of Windows-specific extensions including COM support and Pythonwin, an IDE built using Windows components. LINUX All others should download either Python-2.3.4c1.tgz or Python-2.3.4c1.tar.bz2, the source archive. The tar.bz2 is considerably smaller, so get that one if your system has the appropriate tools to deal with it. Unpack it with "tar -zxvf Python-2.3.4c1.tgz" (or "bzcat Python-2.3.4c1.tar.bz2 | tar -xf -"). Change to the Python-2.3.4c1 directory and run the "./configure", "make", "make install" commands to compile and install Python. The source archive is also suitable for Windows users who feel the need to build their own version." From fumanchu at amor.org Sun May 23 17:53:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 23 May 2004 14:53:57 -0700 Subject: Named integers and enums Message-ID: Hallvard B Furuseth > Is this possible without too much code? > > class Named_int(object, int): > def __str__(self): return self.name > __repr__ = __str__ > __slots__ = 'name' > # This does not work: > def __init__(self, name): self.name = name > # ...and it would be nice to freeze the name: > __setattr__ = __delattr__ = None > > x = Named_int(3, "foo") > print "%s = %d" % (x, x) # print "foo = 3" > > Named_int(3, "foo") says "TypeError: an integer is required". > I've tried other ways to specify both parameters, but no luck so far. > BTW, this is Python2.2. I don't know if we'll be able to upgrade > anytime soon. Because you are subclassing from an immutable, you need to override __new__ (instead of, or in addition to, __init__): >>> class named_int(int): ... def __new__(cls, val, name): ... self = int.__new__(cls, val) ... self.name = name ... return self ... >>> x = named_int(3, "foo") >>> x 3 >>> x.name 'foo' Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From richardshea at fastmail.fm Sun May 2 05:47:59 2004 From: richardshea at fastmail.fm (Richard Shea) Date: 2 May 2004 02:47:59 -0700 Subject: urllib2/cookies - surely there's a better way ? References: <282f826a.0404292248.7b71c7d6@posting.google.com> <84KdnfW3OoNKow_dRVn-vg@powergate.ca> Message-ID: <282f826a.0405020147.29f4945@posting.google.com> Peter Hansen wrote in message news:<84KdnfW3OoNKow_dRVn-vg at powergate.ca>... > Richard Shea wrote: > > (about urllib2 and cookies) > > Search for "ClientCookie"... That's great ! I actually laughed when I read the doco - I was only looking for something to parse cookies with but this does the whole thing ! I haven't yet used it but I've had a few wriggles getting to where the 'import ClientCookie' works so I thought I might tell the newsgroup what I did to make it work (although that might be fairly obvious to many). First of all I was installing on a W98 machine. I tried using the install procedure "python setup.py build" but I got the message "error: package directory 'ClientCookie' does not exist". I do have a slightly weird setup so I wasn't all that surprised. Anyway I then took the fallback option of copying the 'ClientCookie' directory from the .ZIP manually. In order to make this work you need to ensure that sys.path contains a path to ClientCookie before it finds the standard libraries. I chose to do that by editing the registry at HKLM/SOFTWARE/Python/PytonCore/2.3/PytonPath and adding a new entry there with a value which pointed at the clientcookie directory (ie C:/a/b/ClientCookie-0.4.18/ClientCookie) however although I got an extra entry at the 'right' place in sys.path this didn't allow me to "import ClientCookie" and eventually I modified the Registry entry to read C:/a/b/ClientCookie-0.4.18 and now everthing seems to be fine. This is probably pretty straightforward stuff for most pepole but I still find some aspects of 'import' a dark art so I thoguht I was worth sticking it into the archives. Thanks again for the tip. Regards Richard. From tismer at stackless.com Thu May 27 17:40:39 2004 From: tismer at stackless.com (Christian Tismer) Date: Thu, 27 May 2004 23:40:39 +0200 Subject: Stackless python and microthreads In-Reply-To: References: <1084504249.836501@yasure> Message-ID: <40B66057.7040200@stackless.com> Matt Leslie wrote: ... > Anyway, stackless would be good for this because I need lots of threads > so simulate large scale P2P systems. This is true. For performance comparison reasons, and to make Stackless "complete" in a way, I just developed real thread support and measured context switch speed. Now it is not longer a claim, but the truth (going to be Stackless 3.1): Stackless soft-switched channels are 10 times faster than using real threads. Stackless tasklets are 10000 times smaller than threads on Windows. > The thing is although there was a > fair amount of documentation on microthreads I can find nothing usefull > on tasklets! Can anyone point me at some? Please? The stackless mailing > list has turned up nothing so far... There isn't much, of course. There is the beginning of a glossary on the website, there are lots of exmaples in preparation after the last sprint, but actually there is still a lack of documentation. The C API is there, just look into stackless_api.h. Then, for a description of individual functions, import stackless help(stackless) gives you a lot of information. Feel free to ask me for support, I will help as much as I can. cheers - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From JasonHarper at pobox.com Tue May 11 20:17:03 2004 From: JasonHarper at pobox.com (Jason Harper) Date: Tue, 11 May 2004 17:17:03 -0700 Subject: Tkinter vs. wxPython? References: <408E9DCA.EC753FE6@shaw.ca> <408EE7A6.321ED53A@shaw.ca> Message-ID: <40A16CBD.E4D1A630@pobox.com> Mark Hughes wrote: > The image support is > terrible (especially since the cropping function from Tk has never been > implemented in Tkinter, and the maintainers don't seem to give a damn), Easily fixable from the Python side: def subimage(src, l, t, r, b): dst = PhotoImage() dst.tk.call(dst, 'copy', src, '-from', l, t, r, b, '-to', 0, 0) return dst Jason Harper From simoninusa2001 at yahoo.co.uk Tue May 18 12:48:52 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 18 May 2004 09:48:52 -0700 Subject: Python compilers? References: Message-ID: <30260531.0405180848.42e2919d@posting.google.com> Leif K-Brooks wrote: > > Is anyone working on a python-to-native compiler? > > I'd be interested in taking a look. > If it's faster code execution, the primary slowdown with a very > high-level language like Python is caused by high-level data structures > (introspection, everything being an object, etc.), not the code itself. > A native compiler would still have to use high-level data structures to > work with all Python code, so the speed increase wouldn't be very much. I think the main slowdown most people would see is the startup time - the interpreter takes way too long to start (why the company where I work won't replace Perl/PHP with Python). > If it's ease of distribution you're looking for, I think distutils can > make standalone programs on Windows, and most Linux distros have Python > installed by default. Oh that one is funny - do most distro's have PyQT and wxPython (and their supporting Qt/GKT libs) installed by default, oh and which ones come with 2.3 by default? > If you just think a compiler would be cool (or would like to see how it > would be done), check out Psyco, Pyrex, and probably some other > projects. Pyrex even combats the speed issue by allowing native C types > to be used in addition to Python high-level types. I thought Pyrex was a hybrid of C and Python (like Jython/Java) not actually a Python-to-C convertor? And Pysco is just a different VM isn't it? I could really push Python where I work if there was a native compiler, my company uses C/C++/Java/Qt and were looking at QSA as a way to allow the user to script things, but as all of our products integrate with our software protection system, we can't be distributing source or easily decompiled bytecode! We could replace the whole lot with PyQt and use an embedded Python interpreter for the scripting! Ah the frustration :-( From chris at suse.local Fri May 21 13:48:05 2004 From: chris at suse.local (Chris) Date: Fri, 21 May 2004 12:48:05 -0500 Subject: python hello.py hello_msg("Hello no", 3)??? Help, please! References: <1O-dnXbH1_NxTzHd4p2dnA@powergate.ca> Message-ID: <10asfp2a30jsobc@corp.supernews.com> Peter Hansen wrote: > Carl wrote: > >> This is perhaps a very simple and stupid question! >> >> How do you run a specific function (with actual values for the >> parameters) within a module from the command prompt? That is, with >> "python ..." >> >> For instance, how do I run hello_msg("Hello no ", 3), which is a function >> within the module hello.py, from the console? >> >> def hello_msg(msg, num): >> print msg + str(num ** 3) +'!' >> #hello_msg("Hello no ", 3) > > Use the -c option. > > python -c "import modulename; modulename.hello_msg('test', 5)" Or, from the command prompt, 'import modulename' From nicksjacobson at yahoo.com Mon May 3 13:58:45 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 3 May 2004 10:58:45 -0700 Subject: pychecker proposal Message-ID: I think that PyChecker should be part of the "batteries included" library that comes with Python. It can be a very useful tool for catching errors and bad style. If it were in the standard library, newbies would be aware of it sooner. It could catch some of their mistakes, making for a smoother learning curve. e.g. when I started learning Python, I named a variable str, which caused an exception when I called str() in an unrelated part of the code. This led to some confusion...PyChecker would have flagged it as shadowing a built-in function. What do you guys think? From tjreedy at udel.edu Sat May 1 16:21:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 May 2004 16:21:17 -0400 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> Message-ID: "Dave Benjamin" wrote in message news:slrnc96kat.20s.ramen at lackingtalent.com... > PHP and JavaScript both try to blur the distinction between object and > dictionary. The result is that you can't tell a key from an attribute, and > this can sometimes be problematic. PHP goes a step further and removes the > distinction between array and dictionary. Perhaps this is easier for people > to learn, since they can master one concept and apply it everywhere, but I > much prefer having arrays, dictionaries, and objects as separate concepts > with their own protocols. I like having classes and modules for the same > reasons. In thinking about dictionaries versus modules (and classes/instances), I come up with two reasons to have both. 1. A dictionary is a generic association mechanism, with the key being any hashable object. A module is a association mechanism specialized for the important and common special case of keys that are name strings, and which therefore can be written in code without quotes. 2. A module, because of its specialization, has a more graceful syntax for accessing objects bound to a name known at the time of coding (and compilation): mod.name versus dic['name']. A dictionary, because of its generalization, has a more graceful syntax for accessing objects bound to a (name) key that is only accessible indirectly, at runtime, via a name bound to the (name) key: dic[namename] versus getattr(mod, namename) (or hasattr() or setattr()). (For multiple indirect accesses, one can avoid hasattr, etc by doing modic = mod.__dict__; modic[namename]; ...) One could propose to combine the syntaxes by allowing dict.name instead of dic['name'], but this conflicts with the fact the dicts have several instance methods, and that dicts therefore need an attribute namespace in addition to and separate from the association they represent. Allowing mod[namename] as a substitute for hasattr(mod, namename) might be more feasible (by giving the module type object __xxxitem__ methods), but I can see objections. One-way unification and indexing restricted to namestrings both could be confusing. It would also make it easier to write syntacitically valid but sematically invalid code, whereas the xxxattr names remind that the access key must be a valid attribute name. Quoting from a previous post quoting by someone else: > Modules are an encapsulation mechanism, just like class instances, so > I'd say the large and obvious overlap counts as unnecessary I don't see this. 'Class instance' is an abstract concept, not a particular object. A particular module *is* an instance of the module typeclass, so of course modules are like 'class instances': they are a particular type of class (type) instance. Or, if you will, instances of a particular classtype. In other words, module and modules are part of the current typeclass and instance system, not a disposable alternative. (Classic classes are duplicative and are only kept for back-compatibility, so I ignore them in discussions like this.) The particular features of the module type are dual. First, it has a specialized __init__ method that initializes instances from a file rather than a set of arguments. Second, while it does have the standard minimal set of special attributes (__doc__, etc) it does not have any attributes intended for post-initialization access via the instances. Therefore, we are free to give module instances any attributes we want. This freedom is what makes them usable as generic name capsules. (Modules do have individual __init__-set __name__, __file__, and __doc__ attributes, but these can usually also be overriden also without problem.) Terry J. Reedy From jjl at pobox.com Thu May 20 14:58:33 2004 From: jjl at pobox.com (John J. Lee) Date: 20 May 2004 19:58:33 +0100 Subject: Serious trouble with https (Python 2.2.3 & 2.3.3), How to check for working ssl? References: Message-ID: <87ekpflycm.fsf@pobox.com> Andrew MacIntyre writes: > On Wed, 19 May 2004, Phillip wrote: [...] > > I just downloaded the sources onto Debian Linux and did the configure, > > make, make install dance. [...] Me too (on Debian woody). Install libssl0.9.6 (or a newer version, maybe) AND libssl-dev, and recompile. Or install a debian binary package of Python 2.3. John From dmq at gain.com Tue May 4 15:29:57 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 04 May 2004 12:29:57 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <95aa1afa.0405012134.2b43ad6f@posting.google.com> Message-ID: <3mqf90hh5qh619mf3tv473eh9vf2kbnt05@4ax.com> On Tue, 04 May 2004 16:54:34 +1200, Greg Ewing wrote: >David MacQuigg wrote: > >> On 1 May 2004 22:34:27 -0700, michele.simionato at poste.it (Michele >> Simionato) wrote: > > >>>Probably you do not realize that methods and functions are *already* >>>unified in Python: they are both examples of descriptors. > > >> Interesting! I wish that unification at the primitive level had been >> provided in the original design of Python. > >It was. Methods have always been no more than functions that >happen to live in classes, and they still are. Descriptors are >a red herring here; they're just a generalisation that allows for >some new things. They don't unify anything that was previously >existing but not unified. The unification I'm talking about is what the *user* sees. Currently in Python , depending on the method style, you might need obj1.func() or obj2.func(obj1) depending on the types of obj1 and obj2. This is unnecessary complexity. It adds nothing to the fundamental capabilities of the language. All methods and functions *should* look the same to the user. For an example of how this *could* be done see the PrototypeSyntax documents at http://ece.arizona.edu/~edatools/Python/ For an example of how the presentation of OOP in Python could be cut in half, see the Prototypes documents linked on that same page. Ruby and Prothon got it right. There are no special "static methods". Python should have done the same in its original design. Now it will take an incompatible change in Python to fix it. I'm hoping this will be done in Python 3. If not, something like Prothon will eventually replace Python. -- Dave From http Tue May 25 16:56:07 2004 From: http (Paul Rubin) Date: 25 May 2004 13:56:07 -0700 Subject: Slice assignment for strings? References: Message-ID: <7xoeoctee0.fsf@ruckus.brouhaha.com> "Jens Lippmann" writes: > So, my questions are: > - How do I get it right? > - If slicing seems to be the favorite way to address substrings, why > is it impossible to use it on a left side of an assignment? You can use the array module for what you're doing. See the docs. From peter.maas at mplusr.de Wed May 26 09:14:45 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 26 May 2004 15:14:45 +0200 Subject: Why a class when there will only be one instance? In-Reply-To: <40B3F448.EB711333@shaw.ca> References: <40B3E861.29B033D5@shaw.ca> <40B3F448.EB711333@shaw.ca> Message-ID: SeeBelow at SeeBelow.Nut wrote: > Even easier is not to make anything a class unless there will be two or > more instances of it. I still don't get what advantage making a class > buys for you. To use classes even in single instance cases has some advantages: - There is a unique way of organizing your code. - There is an easy transition to the multiple instance case. - It makes writing meta code (e.g. for documentation, transformation ...) easier. - Code organisation should resemble the real world problem to be modeled (for the sake of clarity): if emphasis is on an entity (e.g. a document) use an object, if emphasis is on activity (e.g. computing the cosine) use a function. These advantages outweigh by far lexical arguments (self. takes soooo long to type) or temporary arguments (instance count is currently = 1). Of course this is largely a matter of taste but I am a 'burnt child' because I had to deal with the one-instance argument in multi-developer projects and found the defender's code quite messy. :) > Other people have mentioned "code reuse". Again I don't see how a class > helps to make code reusable. Inheritance. > I find methods in a class more difficult to reuse than simple function > definitions. (unless there are multiple instances.) Why? Methods are functions with an instance argument: class person: def tellName(self): print self.name >>> p = person() >>> p.name = 'Peter' >>> intro_c = person.tellName >>> intro_c(p) Peter >>> intro_i = p.tellName >>> intro_i() Peter Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From ville at spammers.com Sat May 15 19:04:36 2004 From: ville at spammers.com (Ville Vainio) Date: 16 May 2004 02:04:36 +0300 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> Message-ID: >>>>> "Valentino" == Valentino Volonghi aka Dialtone writes: Valentino> And it has stan which is an s-expr-like syntax. Valentino> Here is a little helloworld example: Valentino> docFactory = rend.stan( Valentino> T.html[ Valentino> T.head[ Valentino> T.title['Hello'], Valentino> ], Valentino> T.body[ Valentino> T.p['Welcome to the wonderful world of Nevow!'], Valentino> ], Valentino> ] Valentino> ) Just a thought: it would be more s-expr like if it just had the "function"ish part inside the list in the normal prefix notation: [T.html, [T.head, [T.title, 'Hello']], [T.body, [T.p, 'Welcome...]]] In a way this seems slightly clearer (especially the , chars n/w ] chars seem very suspicous to me. -- Ville Vainio http://tinyurl.com/2prnb From ivoras at __geri.cc.fer.hr Mon May 17 15:15:24 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Mon, 17 May 2004 21:15:24 +0200 Subject: HTTP 1.1 pipelining In-Reply-To: <4860c084.0405170736.13c6e8b4@posting.google.com> References: <4860c084.0405170736.13c6e8b4@posting.google.com> Message-ID: noviceUser wrote: > can some one guide me how to use HTTP 1.1 pipelining in Python. > > Client will generate 3 get requests continuously as shown below and > then read the response for each GET request. > > Algorithm > ---------- > GET(ur1_l) > GET(url_2) > GET(url_3) > readResponse(url_1) > readResponse(url_2) > readResponse(url_3) I don't think this is how HTTP/1.1 pipelining works. It is still a request-response protocol - the only "pipelining" is in the fact that it doesn't require a separate connection session for each request-response pair. That is: HTTP/1.0: GET(url_1) readResponse(url_1) GET(url_2) readResponse(url_2) GET(url_3) readResponse(url_3) HTTP/1.1: GET(url_1) readResponse(url_1) GET(url_2) readResponse(url_2) GET(url_3) readResponse(url_3) Or maybe you are thinking of establishing parallel connections? In that case look for some examples using threads and sockets... -- C isn't that hard: void (*(*f[])())() defines f as an array of unspecified size, of pointers to functions that return pointers to functions that return void. From tim.golden at viacom-outdoor.co.uk Tue May 18 03:40:20 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 18 May 2004 08:40:20 +0100 Subject: better csv modules and where have object-craft gone? Message-ID: | Only problem is object craft seemed to have disappeared off the face | of the net (ie I can't even resolve their name in DNS). Doubtless they can speak for themselves, but they seem to be up-and-running ok. This works for me: http://www.object-craft.com.au/ TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 Chris.Hornberger at blackrock.com Fri May 14 15:33:03 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Fri, 14 May 2004 15:33:03 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: """ What gives you the right to say this? *I'm offended.* Speaking of moral and ethics, there seem to be other things to care about, especially these days. Thomas """ Ok, so perhaps "moral" and "ethical" is slightly strong. Sheesh. Levity. Point being, if the developers of Python (and Perl and .... so on) spent so much time and energy creating something cross platform, it should be used thusly. I'm not saying it's "evil" not to do so, I'm saying that if you NEED platform-specific tools (which, let's be honest, happens WAY more frequently on Windows), then use a platform-specific tool. Forgetting extensions and addons for a moment (TCL/wxPython/Swing, etc), there's probably no better RAD/GUI tool than VB (your opinions vary, I'm sure). Nor is there a better "server side" scripting tool than Perl (I like Python better, but that's just me). Java does a wonderful job of bridging the "scriptable" and "gui-able" worlds. Of those three tools, two are cross platform, right out of the box. Any mechanic or tradesman will tell you, 1/2 the job is knowing which "right tool for the job" is right. *shrugs* Now that we're all done being offended because I used terms that were taken out of context.... From ebolonev at bonbon.net Tue May 18 03:53:54 2004 From: ebolonev at bonbon.net (Egor Bolonev) Date: Tue, 18 May 2004 18:53:54 +1100 Subject: proxy in urlopen() Message-ID: how they define proxy in urlopen? i've tried a=urlopen('url', proxies=('127.0.0.1:3128')) a=urlopen('url', proxies='127.0.0.1:3128') but it says there is an error ================================== Traceback (most recent call last): File "getlinks.py", line 3, in ? a=urlopen('http://forum.octopusnet.lan/', proxies='127.0.0.1:3128').read() File "C:\Python23\lib\urllib.py", line 69, in urlopen opener = FancyURLopener(proxies=proxies) File "C:\Python23\lib\urllib.py", line 544, in __init__ URLopener.__init__(self, *args, **kwargs) File "C:\Python23\lib\urllib.py", line 106, in __init__ assert hasattr(proxies, 'has_key'), "proxies must be a mapping" AssertionError: proxies must be a mapping Exception exceptions.AttributeError: "FancyURLopener instance has no attribute 'tempcache'" in > ignored ================================== From bobby.mathew at wipro.com Fri May 28 08:40:15 2004 From: bobby.mathew at wipro.com (bobby.mathew at wipro.com) Date: Fri, 28 May 2004 18:10:15 +0530 Subject: quey regarding file conversion Message-ID: Hi, I found the question you have posted for a file covertion from pdf. Did you get any solution? If can you please share it with me? Thanks and regards Bobby Mathew Confidentiality Notice The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain confidential or privileged information. If you are not the intended recipient, please notify the sender at Wipro or Mailadmin at wipro.com immediately and destroy all copies of this message and any attachments. -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen at -nospam-remove-this-xs4all.nl Mon May 31 12:57:13 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 31 May 2004 18:57:13 +0200 Subject: trivial patch for SimpleHTTPServer reporting wrong content-length for text files In-Reply-To: References: Message-ID: <40bb63e9$0$559$e4fe514c@news.xs4all.nl> http://sourceforge.net/tracker/?func=detail&aid=839496&group_id=5470&atid=305470 Is anybody using SimpleHTTPServer? It contains a special case for text files, that makes it open them in another way as other files. This causes the reported content-length to be unequal to the actual length of the request response data (which isn't correct, obviously). This trivial patch removes the special case from SimpleHTTPServer. Please review and/or make a vote for this patch; the current SimpleHTTPServer is unusable for text files... --Irmen de Jong. From gk_2345 at yahoo.com Wed May 26 20:28:02 2004 From: gk_2345 at yahoo.com (George Kinney) Date: Wed, 26 May 2004 20:28:02 -0400 Subject: Question from a beginner References: <44c2a239.0405261525.5b22cb88@posting.google.com> Message-ID: <2Iydnb_NG7uiqyjdRVn-uw@bright.net> "Rodney Dunning" wrote in message news:44c2a239.0405261525.5b22cb88 at posting.google.com... > Hello, > > I've just picked up python to create some 3D visuals (using VPython) > for a physics class I'm developing. While writing a program, I > developed a "bug" that is reflected in the code below. When executed, > *both* Test1 and Test2 are changed. Can someone explain this to me? > Why is Test2 changed? > > from visual import * > from __future__ import division > > ##Variable tester > > a = vector(1,0,0) > > Test1 = a > > Test2 = a > > print "Test1 = ",Test1 > print "Test2 = ",Test2 > > Test1.x += 3 > > print "Test1 = ",Test1 > print "Test2 = ",Test2 > > ##End code > > I've programmed extensively in Fortran-90. Is there anything in python > analogous to the PARAMETER keyword in Fortran-90, such as > > integer, PARAMETER :: i = 10 !*** the value of i cannot be changed, > period. > > Thanks for your help. In general, no. Python doesn't have a built in constant type or modifier. The other problem is a really common gotcha for newbies, you have created a variable Test1, and a reference to it, Test2. They both point to the exact same object in memory. You could do: Test1 = vector() Test2 = vector() and have separate, independant vars. From madsurfer2000 at hotmail.com Sun May 2 06:32:33 2004 From: madsurfer2000 at hotmail.com (-) Date: 2 May 2004 03:32:33 -0700 Subject: Web development class References: Message-ID: "Lorenzo Bolognini" wrote in message news:... > I wrote: > > > h1.red (assigning properties to html entities) > > Sorry, > > h1.color("red") I have no idea what the class you're looking for does, but this example is better implemented with standard CSS. Example From gherron at islandtraining.com Tue May 11 17:39:03 2004 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 11 May 2004 14:39:03 -0700 Subject: Python security settings In-Reply-To: <67B3A7DA6591BE439001F27362333512028772DA@xch-nw-28.nw.nos.boeing.com> References: <67B3A7DA6591BE439001F27362333512028772DA@xch-nw-28.nw.nos.boeing.com> Message-ID: <200405111439.03639.gherron@islandtraining.com> On Tuesday 11 May 2004 01:18 pm, Laughlin, Joseph V wrote: > import SimpleXMLRPCServer > rpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 3010)) > print "XMLRPC Server started!" > rpc_server.serve_forever() > > When I run this program, I can connect to port 3010 on the localhost, > but I can't connect to the port from any other machine (or from the > local machine using the machine's hostname). Why is this? > > Joe Laughlin > Phantom Works - Integrated Technology Development Labs > The Boeing Company Use SimpleXMLRPCServer.SimpleXMLRPCServer(("", 3010)) instead of SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 3010)) For server sockets (which this is creating), the host name specifies which name to accept connections as. A blank name means accept connectrions as any name (localhost, or any other host name the machine may have). Gary Herron From rogerb at rogerbinns.com Sat May 1 23:33:15 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 1 May 2004 20:33:15 -0700 Subject: Path ... where is my application's home dir? References: <408fbc0a$0$17256$a1866201@newsreader.visi.com> <1090aj86bk47k02@corp.supernews.com> Message-ID: Michael Geary wrote: > Roger Binns wrote: > > from win32com.shell import shell, shellcon > > path=shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0) > > CSIDL_PERSONAL is the user's "My Documents" folder, which is not the right > place for configuration files. It's for documents that the user explicitly > creates and saves. That is why I pointed to the list of CSIDL constants since the OP will need to use their judgement as to where to store stuff based on what it actually is. One should also take into account that if the user is using a roaming profile then some paths returned will be local and some will be remote. Roger From theller at python.net Mon May 3 05:54:56 2004 From: theller at python.net (Thomas Heller) Date: Mon, 03 May 2004 11:54:56 +0200 Subject: Automated installation framework References: Message-ID: Nikolai Kirsebom writes: > On Fri, 30 Apr 2004 15:46:33 +0200, Thomas Heller > wrote: > >>Have you read the paper? The title talks about packaging the Python >>distribution, but what Martin does is creating the msi installer using >>Python. In other words, a Python framework to create msi packages, >>which could contain anything... >> >>Sorry if I misunderstood again. >> >>Thomas >> > > Have read through it, and maybe it will do the job. Do you know where > I can find examples of use of this module. No. I suggest you contact Martin directly. Thomas From richardjones at optushome.com.au Thu May 6 23:10:02 2004 From: richardjones at optushome.com.au (richard) Date: Fri, 07 May 2004 13:10:02 +1000 Subject: MySQL vrs SQLite References: <4099890c$0$32558$afc38c87@news.optusnet.com.au> Message-ID: <409afe0a$0$21085$afc38c87@news.optusnet.com.au> Michael wrote: > It does block though - it doesn't loss data if more than one program > tries to access it at once? Yes. > Since SQLite stores data as strings that means data such as numbers will > take up more space than in a db such as MySQL? Yep. Richard From michael at foord.net Wed May 26 10:20:26 2004 From: michael at foord.net (Fuzzyman) Date: 26 May 2004 07:20:26 -0700 Subject: ANN : ConfigObj 3.0.0 - Simple config file parsing Message-ID: <8089854e.0405260620.230f8319@posting.google.com> There have been a couple of config file 'systems' announced recently, that focus on building more powerful and complex configuration files. ConfigObj is a module to enable you to much more *simply* access config files. This is version 3, which is a big overhaul. It extends ConfigObj to reading config files with sections and various other simplifications. I find ConfigObj extremely easy to use and use it for reading config files and data persistence...... http://www.voidspace.org.uk/atlantibots/pythonutils.html#configobj (also the home of caseless and listparse modules) INTRODUCTION and EXTRACT from docs ConfigObj ConfigObj allows you to read, modify and create config files in python with basically single line commands. If you give it a filename it will read the config automatically and you can access or change the values by treating it like a dictionary. ConfigObj 3 is a major upgrade to ConfigObj - it will now read and write config files with sections (like windows INI files) as well as various other improvements and simplifications. ConfigObj has the following advantages over other configuration systems : Ease of use Multiple (list) values for keywords Easy to create, modify *and* write files Easy to hand edit/create the config files comments are preserved quoting is optional will understand various different keyword/value dividers Because the programmers interface is the same as the Python dictionary, ConfigObj is also extremely useful for data persistence. The fact that it can store lists and all the files it creates are easily 'human readable' is a big plus for this. Most functionality can be achieved with dictionary like syntax. So it implements a system that is easy for your users to use and easy for you to examine the files that it creates. Feedback on this module, including the documentation, is very much welcomed. Questions, criticism, comments, bug reports and suggestions all welcomed. ConfigObj needs python 2.2+ ###################################################################### THE BASICS USAGE : from configobj import ConfigObj, pref_dict, exceptionlist config = ConfigObj(infile=[], indict = {}, **keywargs) You create a basic configobj by giving it a filename and any options you want to set. The options can either be in the form of keyword arguments or as a dictionary. A useful default dictionary is available to modify - but we'll look more at the options later. config = ConfigObj(filename) ConfigObj then reads the file and parses the values from it. Values are always read in as strings - or lists of strings. The file can either be a straightforward config file with just keywords and values, or it can be divided into sections. Each section then has it's own set of keywords. See the paragraph on config files to see the difference. You can then access the keywords in the same way as you access a dictionary : value1 = config['keyword1'] value2 = config['keyword2'] . . You can even use the same method to change the values, and write it out using the write method : config['keyword1'] = value1 config['keyword2'] = value2 . . config.write() ConfigObj inherits most of it's methods from the built in type dictionary - so most of the things you can do with dictionaries you can do with a configobj. Keywords in ConfigObj are case insensitive. This is done using a class called caseless. If you ever need a case insensitive dictionary or list you can use these ! This means that : print config['FISH'] is the same as : print config['fish'] It also means that the case of the keywords in your config files doesn't matter. ConfigObj will try and preserve the case you used when it writes files out though. If the config file has sections in it, then each section will be a dictionary of keywords and values. print config['section1'] {'keyword1': 'value 1', 'keyword2': 'value 2', 'keyword3': 'value 3'} You can create an empty new section with : config['section 2'] = None or you can just pass in a dictionary : config['section 2'] = {'keyword1': 'value 1', 'keyword2': 'value 2', 'keyword3': 'value 3'} You access values in a section with : value1 = config['section 1']['keyword1'] value2 = config['section 1']['keyword2'] You can also use ConfigObj to just read in *some* values from a file, and then just update those values in the file. This is done using a 'configspec' when you read a file and the 'writein' method to write it out again. But we'll see more about those later. You can even create a completely empty configobj from scratch : config = ConfigObj() config.filename = filename config['keyword1'] = value config['keyword2'] = value . . configobj.write() It can then be read back in with : config = ConfigObj(filename) Easy hey !! A blank configobj created with config = ConfigObj() will be a flatfile by default. The same applies if you specify a filename which doesn't yet exist. To make it a configobj with sections you need to specify : config = ConfigObj(flatfile=False) The last thing I'll mention when covering the basics is list values in config files. Values are always strings - if you want integers, or anything else, you can do the conversion yourself ! If a line in a config file is a list - 'keyword' = [value1, value2, value3] Then it will be read in and turned into a list (using the listparse module). If you pass in a list to a configobj then it will be written out as a list. This includes nested lists !! (lists of lists !! - unless you turn recursivelist off - see the options section). This means : config['keyword'] = [ value1, [value2, value3], value4] is perfectly valid. Regards, Fuzzy http://www.voidspace.org.uk From Chris.Hornberger at blackrock.com Wed May 12 16:30:12 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 16:30:12 -0400 Subject: problem running wxPython demo.py Message-ID: And that, my friends, is why *nix is a long way from displacing Windows on the desktop. This is a bit of a sore spot with me. When it comes to the OS, we programmers are no different than clerks, autocad users, kids doing homework, etc.... we're USERS. Just because we know HOW to build software, and in many cases, modify *nix and rebuild systems as necessary, doesn't mean we should have to. On windows, you pop in the CD, load the system, pop in the dev environment and load it up and get to work. Don't get me wrong, I like *nix, but bu11$hit dependency errors it's prone to are really irking me. That NTFS partition hasn't seen the light of day in quite some time, but believe me, I'm glad it's still there if I need it. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Ken Dere Sent: Wednesday, May 12, 2004 2:40 PM To: python-list at python.org Subject: problem running wxPython demo.py I am running Suse 9.0 with python 2.3-52 and python-wxGTK 2.4.1.2-43. Everything has been installed from the CD distribution and should work together. when trying to run the demo, I get: ken at linux1:/usr/share/doc/packages/python-wxGTK/demo> python demo.py Traceback (most recent call last): File "demo.py", line 3, in ? import Main File "/usr/share/doc/packages/python-wxGTK/demo/Main.py", line 16, in ? import wx # This module uses the new wx namespace File "/usr/lib/python2.3/site-packages/wx/__init__.py", line 45, in ? from wxPython import wx File "/usr/lib/python2.3/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: /usr/lib/python2.3/site-packages/wxPython/wxc.so: symbol _ZNK8wxRegion15ConvertToBitmapEv, version WXGTK_2.4 not defined in file libwx_gtk-2.4.so.0 with link time reference looking through google groups has turned up anything similar. any help is appreciated. Ken -- Ken D. -- http://mail.python.org/mailman/listinfo/python-list From rupole at hotmail.com Thu May 27 20:48:15 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 27 May 2004 20:48:15 -0400 Subject: Determine rights and privileges on Windows. References: Message-ID: <40b68877_1@127.0.0.1> The first parm to LsaEnumerateAccountRights is a policy handle returned from LsaOpenPolicy. I'll try to update the documentation. To list the privileges for the current process, you can use something like this: import win32process, win32security ph=win32process.GetCurrentProcess() th = win32security.OpenProcessToken(ph,win32security.TOKEN_READ) privs=win32security.GetTokenInformation(th,win32security.TokenPrivileges) for priv in privs: priv_state='' if priv[1]==0: priv_state='Disabled' if priv[1]&win32security.SE_PRIVILEGE_ENABLED: priv_state+=' SE_PRIVILEGE_ENABLED' if priv[1]&win32security.SE_PRIVILEGE_ENABLED_BY_DEFAULT: priv_state+=' SE_PRIVILEGE_ENABLED_BY_DEFAULT' print win32security.LookupPrivilegeName(None,priv[0]),priv[1],priv_state Note that the None parm to LookupPrivilegeName means to use the local machine, substitute your DC if you're in a domain. hth Roger "Peter Schmiedeskamp" wrote in message news:mailman.369.1085675362.6949.python-list at python.org... > Hello, I'm writing a python program (in Windows) from > which I would like to determine whether or not either: > 1. The user has administrative access on the current > PC. > or (better) > 2. The currently running process has administrative > access. > > For the first scenario, the > win32security.LsaEnumerateAccountRight() seems to to > be the ticket. The documentation doesn't describe > what this function requires as parameters. It appears > to require a PySID object and some sort of PyHANDLE > object. I've figured out how to get the PySID object, > but I'm not sure what type of PyHANDLE is required (or > how to create such a thing) > > My other alternative is to check the running process > for its authority. There appear to a number of > functions that sound potentially logical to use, > however I'm unable to determine which I should use. > > Has anyone done such a thing? Many thanks to anyone > who can give me a shove down the right path. > > -Peter > > > > > __________________________________ > Do you Yahoo!? > Friends. Fun. Try the all-new Yahoo! Messenger. > http://messenger.yahoo.com/ > From tzot at sil-tec.gr Tue May 25 15:22:54 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 25 May 2004 22:22:54 +0300 Subject: Prothon vs. Python integers References: Message-ID: On 25 May 2004 07:02:09 -0400, rumours say that Heather Coppersmith might have written: >What does it mean, for example, to multiply your credit >card number by three? I instantly become more attractive?-) -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From eurleif at ecritters.biz Wed May 12 23:30:54 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 13 May 2004 03:30:54 GMT Subject: if Request("something") == None: doesn't work In-Reply-To: References: Message-ID: Sam Sungshik Kong wrote: > If it's not None, str(something) should not return "None". What about str("None")? From p at ulmcnett.com Mon May 17 21:20:42 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 17 May 2004 18:20:42 -0700 Subject: module for working with the result set In-Reply-To: <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> References: <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> Message-ID: <200405171820.42139.p@ulmcnett.com> john fabiani writes: > following your thoughts on the keys and my mistake - can you > tell me how to get into a dict format? For MySQL, there is the DictCursor class. Here's an example, and you should even be able to use it as-is as I've opened up public access to my MySQL database: >>> import MySQLdb.cursors >>> conn = MySQLdb.connect(host='melder.paulmcnett.com', user='dabo', passwd='dabo', db='dabotest') >>> dictCursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) >>> print dictCursor.execute('select * from recipes where mingred like "%coriander%"') 14 >>> recordSet = dictCursor.fetchall() >>> for record in recordSet: ... print record['iid'], record['ctitle'] ... 184 Cucumber Salad 186 Garlic Shrimps 193 Chinese Salad with Crispy Won Tons 299 Chicken Curry 304 Kai Phat Khing 305 Kung Tom Yam 306 Ma Ho 308 Yam Krachup 332 Lentil Soup 817 Mixed Vegetable Curry 841 Thai Mushroom Soup 843 Rice Noodle Salad with Ginger 915 Santa Fe Stew 966 Mixed Potato Soup -- Paul http://www.paulmcnett.com From cmg at dok.org Tue May 18 16:01:39 2004 From: cmg at dok.org (Chris Green) Date: Tue, 18 May 2004 16:01:39 -0400 Subject: Popen3-style os.execl? Message-ID: Hey folks, I'm whipping up a quick CGI to wrap a command line app and I was a bit suprised to not find a execl-like Popen3 style object. I don't want to bother with the shell interpreting metacharaters by constructing a command line. Basically, I want something that acts just like Popen3 but allows me to specify cmd as a path + args. Does something like this exist in the standard library? If not, it sounds like a good candidate... Cheers, Chris -- Chris Green Don't use a big word where a diminutive one will suffice. From me at privacy.net Sat May 1 06:10:01 2004 From: me at privacy.net (Washu) Date: Sat, 01 May 2004 10:10:01 GMT Subject: IDE for Python References: Message-ID: Nuff Said wrote: > Why an IDE? Python is - IMO - (one of) THE languages, where > a good editor (tabs2spaces, comment blocks, select encoding, > syntax highlighting, auto-indentation, scriptable ...) is all > you really need. I personally like the debugging capabilities of a good IDE, specifically the ability to watch a variable as you step through it. I know you can perform the same thing through debugging statements but it's not as slick. The IDE of my choice for debugging purpose is Komodo from Activestate. For writing the scripts, I tend to like Glimmer, although most modern editors have some type of scripting language hightlighting scheme. From ptmcg at austin.rr._bogus_.com Mon May 24 15:56:28 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 24 May 2004 19:56:28 GMT Subject: win32com typelib difficulty Message-ID: Software versions: Python - 2.3.3 win32all extensions - build 163 OS- Win2000 SP4 I am having trouble in accessing a customer's proprietary COM type library. After running makepy against the customer's typelib, I am still unable to create a typed object, getting the following Python traceback (I have to sanitize the customer's product, I have replaced it with XYZ): Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32com.client >>> xyz = win32com.client.Dispatch("XYZApp") Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 84, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147467262, 'No such interface supported', None, None) >>> xyz = win32com.client.Dispatch("XYZ") >>> xyz >>> xyz._print_details_() AxDispatch container XYZ Methods: Props: Get Props: Put Props: >>> If xyz is a , how do I invoke methods on it? I've already tried the straightforward xyz.method1() call, and in this case I get: Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 477, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: XYZ.method1 although I know that method1() is defined for this interface. Any other suggestions on how to proceed with this TLB? I *really* want to be able to write test scripts in Python, not in VB. -- Paul From indigo at bitglue.com Sat May 29 02:06:08 2004 From: indigo at bitglue.com (Phil Frost) Date: Sat, 29 May 2004 02:06:08 -0400 Subject: extracting code objects from .pyc Message-ID: <20040529060608.GA23118@unununium.org> Could someone please tell me what should be done to extract a code object from a .pyc? Poking through the source I find examples of using PyMarshal_ReadLastObjectFromFile to get it, but when I tryed this myself it wouldn't work, so I'm wondering what I might be doing wrong. One difference is that the files have already been loaded to ram (by my bootloader), so I was using PyMarshall_ReadObjectFromString instead. From m4 at polite.se Wed May 26 10:22:21 2004 From: m4 at polite.se (Alex Polite) Date: 26 May 2004 14:22:21 GMT Subject: Saving recursive objects to disc. cPickle wan't work. Message-ID: <20040526142220.GA2289@matijek.v10a.ath.cx> I need to put recursive data structures on disc and found out that cPickle doesn't like recursion. What are my options? alex -- Alex Polite http://polite.se From tdelaney at avaya.com Sun May 30 21:56:57 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 31 May 2004 11:56:57 +1000 Subject: API : constness ? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE018807AB@au3010avexu1.global.avaya.com> Beno?t Dejean wrote: > it's also for a simple reason, eg using PyArg_ParseTupleAndKeywords > > using const helps gcc to move these data to the text segment > > static const char * const kwlist[] = { "uri", "open_mode", > "exclusive", "perm", NULL }; Does this give any performance or size improvement? > or a better (but tricky) storage could be used to avoid relocation > > bust casting again again like this > > PyArg_ParseTupleAndKeywords(args, kwargs, "should be const char *", > (char**)kwlist, ... > > is quite ugly ... If it will simplify calling code, I don't see any reason not to do it. However, there is a general policy of not doing large chunks of boilerplate fixing - instead it is encouraged to make these changes in code that is being actively worked on for some other reason. Small patches are good. Perhaps you should choose a few cases that bug you the most (e.g. PyArg_ParseTupleAndKeywords) and submit a patch just for those. Additionally, if you can show a performance improvement as a result (and importantly, no loss of performance on Windows ...) it's more likely to be reviewed kindly ... ;) Tim Delaney From Chris.Barker at noaa.gov Thu May 13 18:00:04 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Thu, 13 May 2004 15:00:04 -0700 Subject: Mac OS X and jpeg support.... In-Reply-To: <46850fd1.0405131142.5ff1d525@posting.google.com> References: <46850fd1.0405131142.5ff1d525@posting.google.com> Message-ID: Jerry wrote: > I tried installing via the package manage the PIL package and trying > to do anything with jpegs fails....I noticed that I did not have libjpeg > installed. I got the jpg-6b package and created libjpeg.dylib in /usr/local/lib. > > I tore out the PIL stuff from /Library and reinstalled the PIL package via > the package manager....I still get failures when trying to display a jpeg > file ( format not recognized...) > How can I get jpeg support going? There is another Package Manger Repository put together by Bob Ippolito, and I think it includes a PIL with jpeg support built in. Check out the archives of the Python-Mac mailing list. You should be abel to find it at www.python.org. If you don't find what you need in the archives, join the mailing list and post a question there. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From donn at u.washington.edu Mon May 24 13:22:25 2004 From: donn at u.washington.edu (Donn Cave) Date: Mon, 24 May 2004 10:22:25 -0700 Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> Message-ID: In article , Arthur wrote: > On Mon, 24 May 2004 05:54:11 -0000, "Donn Cave" > wrote: ... > >It's too bad if he said that. I think it has not led to mass confusion > >because if one interpretation of that 10 word summary makes it an utterly > >absurd proposition, most people are inclined to give him enough credit > >to look for another interpretation. > > We agree as to the dynamics at work. > > But seem to have different feelings about it. > > I honestly don't know what he meant here, or how seriously he meant > it. > > But there have been other instances, on other issues, where it has > been clearer to me what he meant. Some of those issues were of more > significance, to me, than this. And guess what, it was my conclusion > that he was simply and utterly wrong. And felt myself to be arguing > within a community that seemed to find it necessary to find him right, > by any means necessary. I may have been there, I sure remember other occasions where the two of you differed over things. I have too, and the way I remember it, I have taken your side as often as not. But it's never a case of `simply and utterly wrong', there's always some question of judgement in there. One never knows, but there's some reason to think that I'm not vastly smarter than everyone else, so it's prudent and generally more effective to look pretty hard for the sense in what I disagree with. Donn Cave, donn at u.washington.edu From kbaum at es.com Fri May 14 17:00:32 2004 From: kbaum at es.com (kbaum at es.com) Date: Fri, 14 May 2004 15:00:32 -0600 Subject: problem with regular expression? Message-ID: <6A4549342FC81B45B1C86E10C7AFC71C114222@cobra.corp.es.com> I'm trying to scan a (binary) file for a string matching a particular pattern, and am getting unexpected results. I don't know if this is a bug or just my own misunderstanding of regular expressions. The string I'm searching for is a "versioned file name" of the form: "AMS_epXXXx.flt", where 'XXX' is 1 to 3 numerals, the 'x' is lower case 'a-z', and the '_' and 'ep' are each optional. In other words, the following are examples that match: AMSep12a.flt ams_ep101b.flt ams_123z.flt ams12z.flt The regular expression pattern I'm using is: prefix='ams' pat = re.compile(prefix + r'(?:(_)?(ep)?([0-9]{1,3}[a-z])\.flt)', re.I) I'm using the parenthesized groups to conditionally process the match, i.e., if there is no '_' or 'ep' in the name, I still want the match but handle it differently. In my pattern above, group 1 is the (_) group, group 2 is the (ep) group, and group 3 is the "version string" group. The problem I'm having is that the following string of bytes (hex data from a file I'm scanning) returns a '_' in match group 1 even though it is outside the filename pattern that is properly detected: Here's a code snippet to illustrate: #============================================================================ import binascii, re prefix = 'ams' #... pat = re.compile(prefix + r'(?:(_)?(ep)?([0-9]{1,3}[a-z])\.flt)', re.I) #...scan file... #------------------------- # bytes in problem string (note that this section is arbitrary and not part # of the actual problem; it's just my attempt at converting the output of # a hexdump file utility into a python string so as to illustrate the problem # in a self-contained test case: # problem data in file: # # 000a 0004 0002 0020 414d 535f 6a75 6c00 # 0000 0000 0000 0000 0000 0000 0000 0000 # 0000 0000 000a 0004 003f 00d8 414d 5365 # 7031 3031 692e 666c 7400 0000 0000 0000 # 000a 0004 0002 0020 414d 535f 6a75 6c00 ....... AMS_jul. # 0000 0000 0000 0000 0000 0000 0000 0000 ................ # 0000 0000 000a 0004 003f 00d8 414d 5365 .........?..AMSe # 7031 3031 692e 666c 7400 0000 0000 0000 p101i.flt....... bytes = '000a000400020020414d535f6a756c000000000000000000000000000000000000000000000a0004003f00d8414d536570313031692e666c7400000000000000' ascii = binascii.a2b_hex(bytes) #------------------------- m = pat.search(ascii) print m.groups() print m.span(0), m.span(1), m.span(2), m.span(3) #output: ('_', 'ep', '101i') # (44, 57) (11, 12) (47, 49) (49, 53) # # Note that the '_' reported at position 11 in "AMS_jul" is outside the # range of the "real" matched string "AMSep101i.flt" at positions (44-57)! From paul at prescod.net Tue May 25 10:32:19 2004 From: paul at prescod.net (Paul Prescod) Date: Tue, 25 May 2004 07:32:19 -0700 Subject: Prothon should not borrow Python strings! In-Reply-To: References: Message-ID: <40B358F3.9040006@prescod.net> You make some good points, Robert. But bear in mind that we're trying to design 1.0 of a language and that the real language designer has no Unicode experience... Roger Binns wrote: >>Choosing an internal encoding is actually pretty tricky because there >>are space versus time tradeoffs and you need to make some guesses about >>how often particular characters are likely to be useful to your users. > > > There are two ways to deal with it. One is to convert to an internal > "UNICODE" format such as utf8, or using arrays of 16 or 32 bit integers. Agree: space versus time. > You also have to decide if you are going to normalise the string. > For example you can have characters followed by a combining accent. > On display they are one character, but often there is a codepoint > for the single character combined with the accent, so you could > reduce the two down to one. There are also other characters such as > those that specify the direction of the following text which are > considered noise in some contexts. First, it is probably too much work to normalize for a 1.0 language designer (even Python doesn't). Second, it is quite possibly the wrong thing to do at a programming language level. Just as sometimes you want to work with the raw bits of a file, sometimes you will want to work with the un-normalized representation of a string. > The other way of dealing with things is to keep the text as it > was given, and not do any conversion or normalisation on it. > This is generally more future proof, but does burden other code > with having to deal with conversion issues (for example NT/2K/XP > only uses 16 bits for codepoints which is less than the full > range now). Surrogate pairs are a little different than accent normalization...surrogate pairs are just a space-saving hack to make up for the difference between 16 bit implementations and the 20 bit space Unicode uses. > Another design to consider is to allow tags that cover character > ranges and then assign properties to those tags (such as locale, > encoding), but importantly allow multiple tags per character. > (If you have used the Tk text widget you'll understand what I > am thinking of). I'd say that's also beyond 1.0! >>By the way, if you have the courage to distance yourself from every >>other language under the sun, I would propose that you throw an >>exception on unknown escape sequences. > > > Perl did that first :-) Sorry for the confusion. At this point in the discussion I was not talking about Unicode issues any more. I was just talking about plain old escape sequences: >>> print "abc\q\y\z" abc\q\y\z > In addition to all the excellent notes from Paul, I would recommend > you consult with someone familiar with the locale and encoding > issues for Hebrew, Arabic and various oriental languages such > as Japanese, Korean, Vietnamese and Tibetan. Bonus points for > Tamil :-) That's probably a little daunting for 1.0. The question is what is the minimum possible he can get away with in the next few months. > ... > Since you are doing new language design, I also think there would > be great value in forcing things so that you do not have > strings embedded in the program, and they have to come from > external resource files. This also gives you the opportunity to > deal with string interpolation issues and get them right. > (It also means that "Hello, World" remains one line, but also > requires an external file with the message, or some other > mechanism). Seems a little over-strict for me. If I'm writing an HTML handling program I have to keep the HTML tags in a separate file? I think it is a good idea to have a built-in language mechanism for localization but it is another thing I'd put off beyond 1.0. Paul Prescod From noemail at noemail4u.com Mon May 17 09:01:37 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Mon, 17 May 2004 13:01:37 GMT Subject: looping over the files in a directory References: Message-ID: <1bf5f80748c77f9a43b0bc5c8481e624@news.teranews.com> On Fri, 14 May 2004 15:32:32 GMT, "Elaine Jackson" wrote: >Can anyone please tell me the actual syntax for saying something like this: > >for in : > > >(?) Muchas gracias. > >Peace Mark Nenadov posted a solution for a single directory. If you want to do so recursively, try something like this: import os for root, d, files in os.walk("."): for basename in files: filename = "%s/%s" % (root, basename) print filename # or open it, or whatever... --dang From Chris.Hornberger at blackrock.com Wed May 12 13:14:04 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 13:14:04 -0400 Subject: zlib and gzip Message-ID: Ok, fair enough. Can you supply (if it's non-sensitive information) some samples? I'm on this conference call for the next hour or so, so I'm glued to my desk. I have time to tinker. It's just a general status call. I just have to chime in from time to time. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: Bakken, Gregory A [mailto:gregory_a_bakken at groton.pfizer.com] Sent: Wednesday, May 12, 2004 1:10 PM To: Hornberger, Chris; python-list at python.org Subject: RE: zlib and gzip The short answer is I don't know. The longer answer is that I really don't know the driving force behind the compression/encoding that is being used. What I am doing is a more downstream process (so I am stuck with the chosen scheme). -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 1:04 PM To: Greg Bakken; python-list at python.org Subject: RE: zlib and gzip Silly questions first: Is it just a matter of 72 column-bounding to make it email-compliant? (keep in mind I haven't run your sample code yet, I'm sitting here perusing while on a conference call - meetings suck!!!) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Greg Bakken Sent: Wednesday, May 12, 2004 12:57 PM To: python-list at python.org Subject: zlib and gzip I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg -- http://mail.python.org/mailman/listinfo/python-list LEGAL NOTICE Unless expressly stated otherwise, this message is confidential and may be privileged. It is intended for the addressee(s) only. Access to this E-mail by anyone else is unauthorized. If you are not an addressee, any disclosure or copying of the contents of this E-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. If you are not an addressee, please inform the sender immediately. From thinkengine1 at yahoo.com Fri May 7 21:23:10 2004 From: thinkengine1 at yahoo.com (Thinker) Date: 7 May 2004 18:23:10 -0700 Subject: Iterating Dictionaries in a Function Message-ID: I could not get this simple code work. I am guessing that there is a bug in the Python dictionary iterator. def findx(st): d = {'a': 1, 'rty': 4, 'er': 2} for item in d.keys(): print item if cmp(item.upper(),st.upper()) == 0: print d[item] return d[item] else: return st When I call: findx('a') it finds the key. But when I call: findx('er') it does not find anything since it does not iterate; it just checks the first item in the dictionary. Does anyone see where the bug is? From mrjean1 at earthlink.net Wed May 12 11:28:46 2004 From: mrjean1 at earthlink.net (Jean Brouwers) Date: Wed, 12 May 2004 08:28:46 -0700 Subject: max value in list References: Message-ID: <120520040828462122%mrjean1@earthlink.net> [[ This message was both posted and mailed: see the "To," "Cc," and "Newsgroups" headers for details. ]] What about: m = max([max(i) for i in (list1, list2, list3, etc...)]) Example: >>> max([max(i) for i in ([2,3,4], [1,2,3], [4,7])]) 7 /Jean Brouwers ProphICy Semiconductor, Inc. In article , C GIllespie wrote: > Dear all, > > I have a few lists. What's the best way of finding the maximum number of all > the lists. > > For example, > > [2,3,4],[1,2,3],[4,7] > > The max is 7. > > Thanks > > Colin > > From frithiof.jensen at die_spammer_die.ericsson.com Fri May 28 05:02:27 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Fri, 28 May 2004 11:02:27 +0200 Subject: Sqlite syntax References: Message-ID: "firephreek" wrote in message news:mailman.17.1084816067.6949.python-list at python.org... > Is there some documentation out there that actually lists the Sqlite > syntax? http://sqlite.org/lang.html > Or even better, one that crosses over and talks about how it works with > python? That be mainly here: http://www.python.org/topics/database/ under http://www.python.org/peps/pep-0249.html > And since the databases aren't 'centralized' there's no way of knowing > what databases I have floating around is there? It is "lite" - which means that you have to remember where you put stuff ;-) A ConfigParser object is a good place to keep track of that sort of thing. From lbates at swamisoft.com Tue May 25 10:17:55 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 25 May 2004 09:17:55 -0500 Subject: Newbie Question References: Message-ID: <5P2dnQg5y5MMyC7dRVn-uA@comcast.com> t="userid at MACAddress" userid=t.split("@")[0]+"@honigman.com" Larry Bates Syscon, Inc. "Puchalski, Mark" wrote in message news:mailman.264.1085490427.6949.python-list at python.org... I have a script that I need to do the following: Taking a user id that is in the format 'userid at MACAddress', read the userid portion (varying length) and concatenate with @honigman.com. I'm not sure how to make this happen. Suggestions? Thanks. ------------------------------------------------------------------------------ Mark A. Puchalski Network Engineer Honigman Miller Schwartz and Cohn LLP Tel 313.465.7167 Fax 313.465.8267 ********************************************************************* Confidential: This electronic message and all contents contain information from the law firm of Honigman Miller Schwartz and Cohn LLP which may be privileged, confidential or otherwise protected from disclosure. The information is intended to be for the addressee only. If you are not the addressee, any disclosure, copy, distribution or use of the contents of this message is prohibited. If you have received this electronic message in error, please notify us immediately (313.465.7000) and destroy the original message and all copies. ********************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Thu May 13 07:00:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 07:00:36 -0400 Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> Message-ID: john fabiani wrote: > Peter Hansen wrote: > >> john fabiani wrote: >> >>> I'm guessing but I bet that simple text can be sent to a printer >>> using Python (looping of course). But in today's world most users >>> want graphics along with the data. Like an invoice with a logo, >>> boxes around the bill to and ship to, along with column lines. So >>> I'm hoping that someone has at least started a project to print reports. >> >> >> >> That would be "ReportLab", I would think... Google for it. >> >> -Peter > > I book marked it - but it looks like a web solution?????? I don't know quite what you mean by that, but it generates PDF files, so I suppose it's at least broader than what "web solution" implies to me. -Peter From tdelaney at avaya.com Mon May 10 21:11:13 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 11 May 2004 11:11:13 +1000 Subject: nested for loop Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01799B74@au3010avexu1.global.avaya.com> Wolfgang Buechel wrote: > Is there a shorter (and probably, with respect to exec time, faster) > way to write such a 4for loop? > (I want to scan 3x3, 4x4 matrices too (;-) In addition to the other suggestions, probably the simplest way to get an immediate speedup (on x86) is to use psyco. http://psyco.sourceforge.net/ Simply add: import psyco psyco.full() to the top of your script. For more complex scripts, you may want to consult the psyco docs for potentially better options. Tim Delaney From jzgoda at gazeta.usun.pl Sun May 9 15:36:07 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 9 May 2004 19:36:07 +0000 (UTC) Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: Olivier Scalbert pisze: > What is the python way of doing this : > perl -pi -e 's/string1/string2/' file Use sed. -- Jarek Zgoda http://jpa.berlios.de/ From tjreedy at udel.edu Mon May 17 10:57:55 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 May 2004 10:57:55 -0400 Subject: This program makes Python segfault - no other does References: Message-ID: "Juho Saarikko" wrote in message news:pan.2004.05.17.10.17.01.120134 at but.no.spam... > The program attached to this message makes the Python interpreter segfault > randomly. I have tried both Python 2.2 which came with Debian Stable, and > self-compiled Python 2.3.3 (newest I could find on www.python.org, 2.3.4 was just released. I believe it fixed two segfault bugs. > compiled with default options (./configure && make). I'm using the pyPgSQL > plugin to connect to a PostGreSQL database, and have tried the Debian and > self-compiled newest versions of that as well. Based on posts over several years, seq faults most often arise from 1. buggy compilers, especially at 'higher' optimization settings 2. buggy compiled extensions 3. byte code fiddling and only occasionally from 4. Python interpreter bugs which the developers consider high priority for squashing. > Specifically, I'm wondering if my habit of reusing old variable names in a > function once they are no longer needed might be causing the trouble; > maybe it causes confusion on the variable type ? Very dubious to me; at worst you should get an exception with traceback. > So, here's the program. Does anyone know what's wrong with it ? Since you don't seem to be fiddling with internals, there is no way I know to eyeball the code and tell which line is doing the 'impossible'. So I think it up to you to determing the offending line by uncommenting print statements and adding more as needed. Then see if you can reduce the program and still get segfaults. Terry J. Reedy From mark at prothon.org Sun May 23 15:21:53 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 23 May 2004 12:21:53 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: "moma" wrote > The lack of "class" type and direct creation and use of objects is very > handy for "Prototype-based Programming" (that's PROthon) > > Who said OO-programming must have a class type ? Unfortunately ten million textbooks say so. That is why when refering to Prototype-based Programming, we call it "Object-Centric" programming, not "Object-Oriented". From jcarlson at uci.edu Mon May 24 19:42:59 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 24 May 2004 16:42:59 -0700 Subject: Does Python have any kind of 'messaging'? In-Reply-To: References: Message-ID: > I used to like Objective-C and Gnustep, but I gave up for lack of > support and recognition of the language/platform under Unix. But it > did offer NSNotifications, a basic message class that could be posted > and received by all subscribers. Other than global variables used to > share data across threads, does Python have anything similar? No, but you can write one yourself quite easily, depending on the semantics of your messaging system. - Josiah import threading channels = {} lock = threading.RLock() def subscribe(id, funct, channel): lock.acquire() if channel in channels: channels[channel][id] = funct else: channels[channel] = {id:funct} lock.release() def unsubscribe(id, channel): lock.acquire() if channel in channels: try: del channels[channel][id] except KeyError: pass lock.release() def post(channel, message): lock.acquire() if channel in channels: for funct in channels[channel].itervalues(): funct(message) lock.release() From grante at visi.com Thu May 13 15:44:59 2004 From: grante at visi.com (Grant Edwards) Date: 13 May 2004 19:44:59 GMT Subject: struct doesn't handle NaN values? Message-ID: Perhaps I'm doing something wrong: the struct module docs say it's IEE 754, but I can't figure out how to get it to handle NaN values correctly (either packing or unpacking). >>> x = float('nan') >>> struct.pack("", line 1, in ? SystemError: frexp() result out of range >>> struct.unpack(" References: <7CBpc.467692$Pk3.138905@pd7tw1no> Message-ID: <20040516123128.GB16629@unpythonic.net> It works just dandy here, and since you didn't provide the error text there's really not much I can do for you. Jeff From andrew-pythonlist at puzzling.org Fri May 14 01:54:28 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 14 May 2004 15:54:28 +1000 Subject: Speed up properties?! In-Reply-To: <40A45DAD.2020906@konzept-is.de> References: <40A45DAD.2020906@konzept-is.de> Message-ID: <20040514055428.GE24078@frobozz> On Fri, May 14, 2004 at 07:48:29AM +0200, Dr. Peer Griebel wrote: > Hi, > > I have a class with some properties. I would like to verify that only > valid values are assigned to the properties using assert. Therefore I > code setters and getters and use property() to convert these to have a > real property. > > Since the verification is only performed in __debug__ runs the > property() is quite a lot of overhead. I tried to circumvent it. This > is my result so far: > > > class C(object): > def __init__(self): > self._x = 5 > if not __debug__: > self.x = property(self._x, self._x) This doesn't really do what you want: properties (and descriptors in general) only work their magic when they are attributes of classes, not instances. I think a simpler approach in your __init__ would do what you want: def __init__(self): if __debug__: self.x = 5 # ordinary attribute else: self._x = 5 # use properties The rest looked fine to me. -Andrew. From tdelaney at avaya.com Wed May 5 18:08:57 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 6 May 2004 08:08:57 +1000 Subject: software like VNC Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01729B4C@au3010avexu1.global.avaya.com> Why is this appropriate to c.l.python, and why can't you just use VNC? Tim Delaney -----Original Message----- From: python-list-bounces+tdelaney=avaya.com at python.org [mailto:python-list-bounces+tdelaney=avaya.com at python.org] On Behalf Of Alberto Vera Sent: Thursday, 6 May 2004 12:36 AM To: python-list at python.org Subject: OT: software like VNC Hello: Do you know another software that works like VNC or PCAnywhere? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From nspm at nspm.nsp Tue May 4 10:12:07 2004 From: nspm at nspm.nsp (Jean-michel) Date: Tue, 4 May 2004 16:12:07 +0200 Subject: Paris python user group? References: <408795ee$0$25893$79c14f64@nan-newsreader-02.noos.net> Message-ID: J'en suis ! Y a-t-il d?j? une mailing liste ? "francois lepoutre" wrote in message news:408795ee$0$25893$79c14f64 at nan-newsreader-02.noos.net... > Hi all french speaking, Paris-based python users, > Bonjour ? tous les utilisateurs parisiens de python, > > How many are we to use python in the *Paris* Area? > Enough to build some community life? > > Combien sommes nous ? utiliser python sur Paris? > Assez pour monter une assoc? > > Two years ago i discovered perl and, by the way, > their cheerfull and welcoming Paris user community > http://paris.mongueurs.net/ > > Il y a deux ans, j'ai d?couvert perl et, par la m?me > occasion, la chaleureuse ambiance des perl mongueurs > de Paris > > Informal meeting at "La Taverne R?publique" > 5, place de la R?publique every month. > Socialising, a few drinks, some food (pizzas > available for die-hard... but most would stick > to moules-frites:) > > Une r?union informelle ? la "Taverne R?publique" > 5, place de la R?publique chaque mois. > Une ambiance decomplex?e, quelques boissons > et des moules-frites (pizzas pour les accros). > > Great hours re-shaping IT late from 8pm into > the night... but I have since switched to python. > > Des heures agr?ables ? refaire notre industrie > ? partir de 8 heures du soir ... Mais depuis > je suis pass? ? python. > > Anyone to join for a "Paris python user group"? > Des volontaires pour un groupe parisien ? > > Same place, same programme, but there's > room for negociation, both for the drink > and the food :) > > Nous proposons le m?me lieu et la m?me > formule mais nous sommes pr?ts ? discuter :) > > Fran?ois et Jean > > From mike at nospam.com Thu May 6 16:30:20 2004 From: mike at nospam.com (Mike Rovner) Date: Thu, 6 May 2004 13:30:20 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: A. Lloyd Flanagan wrote: >> Actually, please don't set up yet another wiki. Instead, go to >> http://www.python.org/cgi-bin/moinmoin/ >> and start creating pages. (You'll need to create a user account.) > be added, from last year. Somebody should Just Do It. Thank you for actually doing it. Please make you pages belong to CategoryDocumentation. Links to official documentation will also be good. Some pages (like FrontMatter may better belong to subpages like PythonLibraryReference/FrontMatter). Pay some attention to wiki autocontens and autonumbering capabilities. Hope this helps. Mike From catcher at linuxmail.org Sat May 22 17:47:34 2004 From: catcher at linuxmail.org (Robert) Date: Sat, 22 May 2004 17:47:34 -0400 Subject: SciTE editor question References: Message-ID: "Brent W. Hughes" wrote in message news:sxPrc.97519$xw3.5665588 at attbi_s04... > I want to increase the number of files I can have open in the SciTE editor. > The SciTEDoc.html document says to change the number of buffers in a file > called SciTE.properties, but it doesn't say specifically how to specify > this. So I tried putting this in the properties file: > > buffers=5 > > It didn't work. Maybe I need to qualify it in some way, like sys.buffers=5. > Does anyone know about this? > > Brent > > P.S. If I'm in the wrong newsgroup for this question, please tell me which > NG to use. > > >From the docs: "Buffers SciTE may be configured to use between 1 and 100 buffers each containing a file. The default is 1 and this effectively turns off buffers. With more than one buffer, the Buffers menu can be used to switch between buffers, either by selecting the file name or using the Previous (F6) and Next (Shift+F6) commands. Setting more than 10 buffers may cause problems as some menus are fixed in length and thus files beyond that length may not be accessible. When all the buffers contain files, then opening a new file causes a buffer to be reused which may require a file to be saved. In this case an alert is displayed to ensure the user wants the file saved. " "How do I enable tabbed window mode in SciTE? Tabbed window mode is only available on Windows and GTK+ 2, not on GTK+ 1. Multiple buffers must be allocated by setting, for example, buffers=10 in your SciTEGlobal.properties. To have the tab bar visible upon starting SciTE, set tabbar.visible=1. You can also set tabbar.hide.one=0 to always show tabs, or 1 to hide when only one file is open. tabbar.multiline=1 splits tabs across various lines if neccesary. " HTH From wrobell at pld-linux.org Sun May 2 04:53:38 2004 From: wrobell at pld-linux.org (wrobell) Date: Sun, 2 May 2004 10:53:38 +0200 Subject: Building python on Linux with no X In-Reply-To: <4094B51A.1010500@zoran.com> References: <4094B51A.1010500@zoran.com> Message-ID: <20040502085338.GA14742@beton.hyperreal.info> On Sun, May 02, 2004 at 10:45:14AM +0200, Miki Tebeka wrote: > Hello Sandeep, > > >I have tried using the source rpm and the tarball to build python on > >RH9. In both cases I get a build failure on tkinter because I don't > >have X installed. > > > >Since I only care about the core python and the devel rpms, is there > >any way to only have those two rpms built from the source rpm? > I don't know about the source RPM however if you comment out _tkinter in > the Modules/Setup file it should not be build. > I didn't try but maybe ./configure --without-tkinter will work as well. there is also ftp://ftp.pld-linux.org/dists/ac/PLD/SRPMS/SRPMS/python-2.3.3-2.src.rpm just rpmbuild --rebuild python-2.3.3-2.src.rpm --without tkinter it is possible that it builds on rh box, too wrobell From fredrik at pythonware.com Mon May 24 17:23:52 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 May 2004 23:23:52 +0200 Subject: subclassing built-in types References: <40B26443.6010909@mediapulse.com> Message-ID: Gabriel Cooper wrote: > Traceback (most recent call last): > File "", line 1, in -toplevel- > x = myString("hello",40) > TypeError: str() takes at most 1 argument (2 given) this might help: http://www.python.org/2.2.3/descrintro.html#__new__ From grahamd at dscpl.com.au Thu May 13 02:34:43 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 12 May 2004 23:34:43 -0700 Subject: Real-time graphs References: Message-ID: wrote in message news:... > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? > > TIA > Stephen Where I once worked, they used Blt for Tkinter under the Pmw toolkit for Python. See: http://pmw.sourceforge.net http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc The latter site has some good illustrative examples. From zunbeltz at wm.lc.ehu.es.XXX Thu May 27 05:21:42 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 27 May 2004 11:21:42 +0200 Subject: wxpython moved? References: Message-ID: arsenal_hl at yahoo.com.hk (Arsenal) writes: > its official site www.wxpython.org has been dead for some time... was it moved? I have not any problem to access to this site. I don't think it's moving. -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From peter at engcorp.com Wed May 26 21:36:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 21:36:21 -0400 Subject: modifying mutable list elements in a for loop In-Reply-To: <49cab0597e8horkvlhfihfho075uivgm3j@4ax.com> References: <9d5509fa.0405260439.175797e@posting.google.com> <49cab0597e8horkvlhfihfho075uivgm3j@4ax.com> Message-ID: Arthur wrote: > On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen wrote: >>Treat that as "not safe if you don't know what you are doing". >>David's answer is on the mark, but furthermore you *can* modify >>the sequence being iterated over, if that's really what you >>want to do. > > OTOH: > > d={"a":1,"b":2} > for k in d: > d.pop(k) > > results in: > > RuntimeError: dictionary changed size during iteration > > I don't recall why I ran into this. But was mildly surprised. Interesting, but on second thought quite logical I think. After all, dictionaries are not *sequences*, so there is no defined order in which to iterate over their keys, so changes would have undefined results unless a copy was made of the keys at the start of the loop. I suspect that wasn't done because it would waste memory and time and the only benefit would be allowing in-loop modifications. Iterating over a sequences, on the other hand, is handled in a clearly defined fashion and therefore modifications to the sequence can be done during the loop if that makes sense (though mostly it doesn't). -Peter From grante at visi.com Sat May 15 01:19:13 2004 From: grante at visi.com (Grant Edwards) Date: 15 May 2004 05:19:13 GMT Subject: book on wxPython? References: Message-ID: <40a5a851$0$8512$a18e6209@newsreader.visi.com> In article , Ryan Paul wrote: > I have a copy of the python2.1 bible. Its a bit outdated, but > it has a really good section on wxpython. [...] Thanks, I'll check into it. >> wxWindows seems to be more low-level than the other GUI >> toolkits I've used (Tk, GTK, and Trestle[1]), and there are >> all sorts exposed details in wxWindows/wxPython that I find >> weird. > > wxWindows is far from low level. For an example of what I mean by low-level, there's a "hello world" example from an O'Reilly book I ran across earlier this evening: . The Tkinter example is 5 lines of code and includes a button that executes a command when it's pushed. The wxPython "hello world example" is twice as many lines of code and is just an empty frame: it doesn't even include the button (that would have made it three times as many lines of code). With Tk, a lot of the low-level details are handled automatically, but in wxWindows, you have to do them manually. Perhaps that gains you flexibility, but if you don't need that flexibility, all it gains you is pain: something that's one line of code in Tk seems to be typically three or four lines of code in wxPython. Another example: When you create a widget you have to tell it who its parent is. Then in a separate operation, you have to tell the parent about the child. Why is the link between child/parent set in two places? That's just a bug waiting to happen: splitting up a single piece of information and putting the two halves in two different places in the source code where they have to be maintained in concert has always proven to be a bad thing in my experience. Why can't the operation where you add a child to a parent also add the parent to the child? Does the child actually need to know who its parent is during the interval between the child's creation and the child being added to its parent? Perhaps it does. Is there an advantage to doing the parent/child linkage in two separate operations? Perhaps there is. But when there's no explanation of what the extra complexity/fragility buys you, it just looks sort of broken and "low-level". For a final example, in a previous thread I already went on and on about the integer widget and event IDs and separate "linking" functions used to connect handlers, events, and widgets. That seems much lower-level than just passing the callable when you create the widget or letting the widget object have attributes or get/set methods that can be used to set up the callable for an event. Again, there is some added flexibility to the wxWindows approach, but I don't need that sort of flexibility for the apps I write, so all I get is the fun of writing triple the lines of code. It's sort of like C vs. Python: C is a lower-level language, so you have more flexible control over many things. That flexibility is expensive: you have to write more lines of code, and that code is much harder to read, debug, and maintain. Since the programmer is responsible for more of the details, more of the details are wrong. > it is a cross-platform compatible wrapper that sits on top of > other toolkits. (Gtk on linux, for instance) It seems > 'low-level' because the python bindings have very unpythonic > syntax. No, not just the syntax, but some of the basic architectural design seems to be more low-level to me. Sizers, for example, appear to be an afterthought, and you have to sort of stick them onto your widgets manually. That functionality is part of the fundamental design of other GUI toolkits and just happens automatically. > People say that WAX fixes this. (I've never used it) I'm trying out wax, and it's definitely an improvement, but it's not ready for production yet. One of the widgets I want to use doesn't work right, and due to the baroqueness of wxWindows, nobody seems to know why. I'm going to take a whack at fixing some bugs, but I'll need to know a lot more about wxWindows and wxPython and sizers and whatnot than I do now. Hence the search for documentation. One page I found said that sizers were written in pure Python and therefore not part of wxWindows, and for documentation on how to use them, you should consult the wxWindows manuals. Huh? >> Anyway, I'd really love to find a good book on wxPython. I'm >> still working through wxPython tutorials, and I've read >> through some of the wxWindows ones (which are of limited value >> for somebody steadfastly determined to remain clueless about >> C++). > > I applaud your efforts to stay C++ free, and I sincerely hope > you have more luck in that endeavor than I did! So far, so good. > You might find that perusing wxPython examples helps more than reading > those insidious c++ tutorials. The WxPython demo includes a comprehensive > collection of examples, showing how to use just about every single widget. > You might want to take a look at it. I've been looking through those, and am still confused about a lot of things (e.g. parent links and sizers). I printed out some wxpywiki pages to read in my spare time... -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER. From lbates at swamisoft.com Mon May 17 10:17:07 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 17 May 2004 09:17:07 -0500 Subject: html to image or html to postcript to image References: Message-ID: I've written several applications to do just this. I do this using Python Imaging Library. It has methods for writing text onto an image that gets rendered as graphics. You can then save as any format you like (e.g. JPG, TIFF, PDF, etc.). HTH, Larry Bates Syscon, Inc. "Lukasz Indyk" wrote in message news:c8agcb$ihd$1 at atlantis.news.tpi.pl... > i want to convert html to image (format of the image does not matter). > is it possible in python? or mayby it is possible to convert html first > to the postscript, and then postscript to image? From CaptainN at altel.net Wed May 5 22:29:10 2004 From: CaptainN at altel.net (CaptainN at altel.net) Date: Wed, 5 May 2004 22:29:10 -0400 Subject: Web programming ... References: Message-ID: Just finished a semester-long project for Database Systems class using Python Server Pages and Python code imports. Interesting... I like how they work in general and it all interfaced perfectly with the Postgres DB API, but PSP in general could use more documentation. Right now... I'd say JSP and PSP are tied in my experience. "Sarah Tanembaum" wrote in message news:c7b2er$1q2uv$1 at ID-205437.news.uni-berlin.de... > Is python good for creating Web application? I do like the OOness of Python, > as a newbie, I'm trying to find out if Python has all its necessary > modules/utilities for Web programming just as extensive as, say, PHP or > Ruby(some say that Ruby is not ready for this sort of application and is not > yet mature as Perl, Python, and PHP - is it true?). > > > From knio at knio.h4xn3t.net Sat May 1 18:43:26 2004 From: knio at knio.h4xn3t.net (Knio) Date: Sat, 01 May 2004 22:43:26 GMT Subject: calling functions at the same time In-Reply-To: <4093d389$0$17262$a1866201@newsreader.visi.com> References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Knio wrote: > > >>You can't get greater then 1ms accuracy when measuring a time >>on todays machines, and that will be less when measuring time >>over a network... > > > Not sure what you mean by "todays machines", but on a > Pentium-class machine running Linux, you get approx 1us > resolution with calls to time.time(): > > [snip] ah, interesting.. on my windows machine (pentium 4) I only have a 1ms timer resolution. import time t = [] for i in range(10): t.append(time.time()) print t [1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999, 1083451302.5739999] From gianluca.trombetta at tin.it Tue May 18 07:19:32 2004 From: gianluca.trombetta at tin.it (Gianluca Trombetta) Date: Tue, 18 May 2004 13:19:32 +0200 Subject: pexpect module References: <20040517210708.GA28582@gate2.hazen.net> Message-ID: Great! I've disable the pager with the command "terminal length 0" and now it seem work very well. Thank you very much John and thank to all other! Regards, Gianluca Trombetta "John Hazen" ha scritto nel messaggio news:20040517210708.GA28582 at gate2.hazen.net... > * Gianluca Trombetta [2004-05-17 09:10]: > > But I need to run some cisco commands like "show ip bgp summary", this > > command print a table and put a "More" by default, if the table is too big > > for a single terminal screen. > > So I need to remove this behavior because if I match the " --More-- " with > > expect module i can match only the first one "More", then this the program > > crash and receives a timeout. > > Why don't you post your code and the traceback you're getting. I think > you should be able to expect the "More" multiple times. > > Try using expect with a list argument, and detect which one matched. > > [untested] > > console = pexpect.spawn("whatever_command_you_use") > # probably other stuff here (enabling, etc.) ... > console.sendline("sh ip bgp summ") > # look for more or prompt > return_index = console.expect([" --More-- ","#"]) > while return_index == 0: > console.send(" ") > return_index = console.expect([" --More-- ","#"]) > # matched prompt, so now you're good to go. > > > Note, that you may have to save the console.before in the while loop, so > you don't lose it before you match the prompt. > > HTH- > > John > > P.S. [OT]: The cisco command I use to disable the pager is: > # terminal length 0 > > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Thu May 13 22:19:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 22:19:43 -0400 Subject: Stackless python and microthreads In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > continuations are the most awesome toys > you can imagine... we will all mourn their passing in time... Will that be _before_, or _after_ we understand what they are? ;-) -Peter From guettli at thomas-guettler.de Mon May 10 10:36:48 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 10 May 2004 16:36:48 +0200 Subject: Processing huge datasets References: <79Knc.15953$k4.322398@news1.nokia.com> Message-ID: Am Mon, 10 May 2004 12:00:03 +0000 schrieb Anders S?ndergaard: > Hi, > > I'm trying to process a large filesystem (+20 million files) and keep the > directories along with summarized information about the files (sizes, > modification times, newest file and the like) in an instance hierarchy > in memory. I read the information from a Berkeley Database. > > I'm keeping it in a Left-Child-Right-Sibling instance structure, that I > operate on recursively. > > First I banged my head on the recursion limit, which could luckily be > adjusted. > Now I simply get MemoryError. > > Is there a clever way of processing huge datasets in Python? > How would a smart Python programmer advance the problem? Hi Anders, I use ZODB. http://zope.org/Wikis/ZODB/FrontPage/guide/index.html HTH, Thomas From eric_brunel at despammed.com Mon May 3 04:39:59 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 03 May 2004 10:39:59 +0200 Subject: Method binding confusion References: Message-ID: Peter Otten wrote: > A B Carter wrote: > > >>I'm a bit confused by the behavior of the following code: >> >> >>import math >>import myModule >> >>class Klass(object): >> def doOperation(self, x, y): >> return self.operator(x, y) >> >>class KlassMath(Klass): >> operator = math.pow >> >>class KlassMyModule(Klass): >> operator = myModule.pow >> >>km = KlassMath() >>kmy = KlassMyModule() >> >>km.doOperation(2,4) >>km.doOperation(2,4) > > > Should that be kmy.doOperation(2,4)? Please cut and paste actual code. (The > same goes for the tracebacks) > > >>The last call fails with "TypeError: takes exactly 2 argumetns (3 >>given)" I understand that in KlassMyModule the operator is being >>treated as a method and a reference to the class instance is being >>past as the first argument. And I also understand that Python is >>treating a function from the standard math libary differently from a >>function I defined in my own module. What I don't understand is why. > > > Assuming that myModule.pow (which you do not to provide) is a function that > takes two arguments, all these will fail: > > kmy.doOperation(2, 4) > kmy.operator(2, 4) > km.doOperation(2, 4) > km.operator(2, 4) > > If you want to avoid the automatic addition of self, use staticmethod: > > >>>>def mypow(a, b): >>> > ... return "%s ** %s" % (a, b) > ... > >>>>class MyClass: >>> > ... operator = staticmethod(mypow) > ... > >>>>MyClass().operator(2, 4) >>> > '2 ** 4' > > > Peter I can reproduce the OP's behaviour with old-style classes in Python 2.1.1: >>> class C: ... def op(self, x, y): ... return self.operator(x, y) ... >>> import math >>> class C1(C): ... operator = math.pow ... >>> o1 = C1() >>> o1.op(2, 3) 8.0 >>> def myPow(x, y): return '%s ** %s' % (x, y) ... >>> class C2(C): ... operator = myPow ... >>> o2 = C2() >>> o2.op(2, 3) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in op TypeError: myPow() takes exactly 2 arguments (3 given) I also cannot understand the difference between C1 and C2: math.pow and myPow are both functions with two parameters, so why does the first work and not the second? Or was it an "unwanted feature" that was removed in a later version? I also have some difficulty to understand the "automatic addition of self" you mention. In what case is it needed? I would have sworn the two classes worked... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From imbosol at aerojockey.invalid Thu May 20 23:03:51 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 21 May 2004 03:03:51 GMT Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> <7x1xlf8p9z.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > > Carl Banks writes: >> > The example above kills any attempt to turn a.bar() into a static >> > procedure call. >> >> Of course it does--but it's one method. A compiler, if it's good, >> would only make the optization on methods named "bar", and it could >> probably pare the number of possible classes it could happen to down >> to only a few. > > How could it possibly know? The reassignment of a.bar could happen > anytime, anywhere in the code. Maybe even in an eval. And if it happens anytime, anywhere in the code, the compiler will see it and create more general code. Or is that impossible? As for eval, well it would be silly to even allow eval in a compiled program; kind of defeats the purpose of compling. You might let it run in its own namespace so it can only affect certain objects. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From vignatov at colorpilot.com Mon May 17 06:52:30 2004 From: vignatov at colorpilot.com (Vladimir Ignatov) Date: Mon, 17 May 2004 14:52:30 +0400 Subject: Troubles with CSV file References: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> Message-ID: <028f01c43bfd$0e0c2c60$6b0aa8c0@vladimirpc> Thanks a much to everybody in discussion! You show me the light :-) >> ""read this, man"", 1 >Invalid CSV... >> """read this, man""", 1 >Valid CSV... Now I see that my CSV file is kind of invalid. Unfortunately it is not from mine application so I must live with it (just for curiosity - this is the *Powermarks 3.5* bookmark manager's output). I replace all "" to """ as suggested and all works fine now. This is not the ideal solution (sometimes csv file have a data like , 123, "", 345, ... which supposed to be a blank string (not shure). But it is irrelevant for me now and *replacing* approach is pretty satisfactory. Thanks again for your help. BTW http://www.voidspace.org.uk/atlantibots/pythonutils.html is unreachable ( "The page cannot be displayed" error ) Vladimir Ignatov From calvin at ironfroggy.com Sun May 30 07:21:00 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Sun, 30 May 2004 11:21:00 +0000 Subject: Looking for a TCP/IP networking library/module/whatever ... References: <6c64de9a.0405290755.6a366d77@posting.google.com> Message-ID: <2001079.bmv9TlgLlH@ironfroggy.com> Storm wrote: > ... that I would like to use in a client/server application that would > : > > 1) detect reliably when connection is lost and try automatically to > reconnect to the server and the link is declared dead (i.e. the > client/server is notified) if only a reconnect was not possible for > 3-4 minutes > > 2) perhaps have the whole link encrypter, but I see this most as a > bonus > > Anyone knows if something like this exists ? Look into Twisted? (http://www.twistedmatrix.com/) -- From fumanchu at amor.org Tue May 4 02:36:48 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 3 May 2004 23:36:48 -0700 Subject: fixedpoint cmp conundrum Message-ID: Tim Peters wrote: > 4. Define an __eq__ method, which returns False if its arguments > are non-comparable. Looking at the SourceForge page, I think this is addressed by Bug #887290: https://sourceforge.net/tracker/index.php?func=detail&aid=887290&group_i d=63070&atid=502756 I don't have 'diff' on this machine, and am *totally* swamped, but here's the new code I ended up with: def __eq__(self, other): if isinstance(other, FixedPoint): xn, yn, p = _norm(self, other, FixedPoint=type(self)) return not(cmp(xn, yn)) else: return False def __ne__(self, other): if isinstance(other, FixedPoint): xn, yn, p = _norm(self, other, FixedPoint=type(self)) return cmp(xn, yn) else: return True ...am I right in thinking that the presence of __eq__ and __ne__ doesn't *harm* the class under older versions of Python? Robert Brewer MIS Amor Ministries fumanchu at amor.org From dotsero at qwest.net Wed May 26 01:12:20 2004 From: dotsero at qwest.net (Michael Livsey) Date: Tue, 25 May 2004 23:12:20 -0600 Subject: ANN: EvNim uses neuroevolution to evolve an ANN that plays the game of Nim Message-ID: The people at ANNEvolve have been working hard again and have released EvNim 1.08. This new release fixes a bug in earlier versions. The effect was to initialize only a small part of each chromosome in the initial population, leaving most of the chromosome with zeroes. Version 1.08 will evolve faster, especially at the beginning. EvNim uses neuroevolution to evolve an ANN that plays the game of Nim. In this version of Nim two players begin the game with 15 "beans". As the game play continues players take turns removing beans. On each turn a player may remove 1, 2 or 3 beans. Each player must remove at least one bean and may not take more than 3. The player removing the last bean loses. EvNim will evolve a perfect player of the game. This is accomplished purely by a tournament among the population of ANNs, hence the perfect player ANN is created with no game analysis by the programmer. A hand-written perfect player is used to evaluate the results, but this information is not used in any way to guide the evolution or to influence the construction of the ANNs. Evnim is written in standard C with no extra libraries required for compilation. It is extensively documented. Much more information, and all source code, is included in the downloadable files at: http://sourceforge.net/projects/annevolve Comments and questions about EvNim may be posted on the ANNEvolve mailing list by sending email to annevolve-devel at lists.sourceforge.net. You may post without subscribing, but anyone may subscribe to this mailing list. The list archives may be viewed at: http://sourceforge.net/mailarchive/forum.php?forum_id=32765. The ANNEvolve team is experimenting with the Evolution of Artificial Neural Networks (ANNs). They are combining the two fields of Evolutionary Computation and Artificial Neural Networks. Find out more about other ANN evolution programs at the Annevolve project at: http://annevolve.sourceforge.net [ comp.ai is moderated. To submit, just post and be patient, or if ] [ that fails mail your article to , and ] [ ask your news administrator to fix the problems with your system. ] From Chris.Hornberger at blackrock.com Thu May 13 17:54:42 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Thu, 13 May 2004 17:54:42 -0400 Subject: Python - open forever ? Message-ID: >Doesn't IBM support python now? I'm sure a number of smaller >companies do. Correct. This poor guy (the original poster) is simply falling victim, as many of us do, to the whims and paranoia of middle management. I personally don't go out of my way to pacify them. Either they accept a decision or they do not. He should lay out some of the facts pointed out in this thread, then back away. An empassioned argument will only cause issues. Lay out the facts, then back away. It's the safest route. $.02 -------------------------- Chris Hornberger chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. From tzot at sil-tec.gr Mon May 24 17:14:10 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 25 May 2004 00:14:10 +0300 Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> Message-ID: On Mon, 24 May 2004 16:25:28 GMT, rumours say that Arthur might have written: >On Mon, 24 May 2004 07:35:05 GMT, Arthur >wrote: >> >>We agree as to the dynamics at work. > >With some part of that dynamics, it seems to me, being that many of us >take our own understanding of the difference between tuples and lists >(some of which might be deeper than others, mine on the lighter side) >and then ascribe and reconcile that understanding with Guido's words. >Which is part of the tautaology factor. > >It works fine, until we try to communicate with each other, around >those words. Well, lists, tuples, homogenity etc in other words (mine): Take a sequence of items. If there is a point in comparing an item of the sequence to another, use a list. If not, use a tuple. You can stop reading here. Digression: if you want to mark a specific point in time, use a tuple of (hour, minute, second). Do you care if hour > minute? If m is such a tuple, does m.sort() have any meaning? More digression: Tuple: a poor man's record. Take a function with arguments name, age. Consider this name, age as a tuple, since calling the function with the age first and then the name quite probably will produce garbage (please don't reply using an example of named arguments). The order is important; t[0] is the name, t[1] is the age. List: generic sequence. Take a function taking a sequence of fruits. You may want to know how many yellow fruits you have, or maybe you want to add their weights and find the average. Use a list; it doesn't matter if you call the function with an argument of [banana, orange, apple] or [orange, apple, banana]. It's equivalent. l[0] is a fruit, l[1] is another fruit, and so on. I'm just trying to make you see it as simple as I see it. Did I succeed? If not, then I beg your pardon in advance. If yes, I'm glad. Of course, you can always use a list instead of a tuple in all cases, with the minor exception of using a tuple when you want to index a mapping. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From max at alcyone.com Fri May 14 19:50:17 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 May 2004 16:50:17 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 References: Message-ID: <40A55B39.D2BD1A6D@alcyone.com> "Laughlin, Joseph V" wrote: > Personally, six months from now, I would have no clue as to all the > different locations a particular program installed files to. What's wrong with find $PREFIX -name '*python*' ? > It would > be worse if the program had modified various configuration files, etc. This is pretty rare for Unix utilites, and is not the case for Python at any rate. > And if you had other programs that depended on the program you were > uninstalling, that would also lead to breakage. If you're uninstalling Python, I would hope you'd remember that this means that Python programs wouldn't work afterwards. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Nobody's interested in sweetness and light. -- Hedda Hopper From kylotan at hotmail.com Fri May 28 14:46:28 2004 From: kylotan at hotmail.com (Kylotan) Date: 28 May 2004 11:46:28 -0700 Subject: mod_python confusion Message-ID: <153fa67.0405281046.331b1b19@posting.google.com> I thought mod_python would be the answer to my CGI performance issue, but I can't seem to make much sense out of it. All the examples are too trivial to be of much use. Given that I have an application consisting of several CGI scripts, what is the simplest way to go about converting it to run on mod_python, not using the CGI-handler which is allegedly slow and buggy? Everything seems to suggest a major rewrite because I not only need to shift from printing everything to calling req.write or whatever, but I may also need to sort out some sort of dispatching mechanism mapping URLs to functions if I use mod_python directly. PSP doesn't work on my system as 3.1.2 gives me errors and the Win32 installer for 3.1.3 fails at the last step (finding the Apache directory in the registry or something). -- Ben Sizer From sarah.tanembaum at yahoo.com Wed May 5 11:25:20 2004 From: sarah.tanembaum at yahoo.com (Sarah Tanembaum) Date: Wed, 5 May 2004 11:25:20 -0400 Subject: ACT 6 conversion, data manipulation, & mailmerge Message-ID: Does anyone out there ever find any info on how to manipulate data from ACT!6 (or any versin) using the scripting language? May be I can learn the scripting language as well using the data I have. I know that Ruby has the WinOLE connector, but how do I use that function to access the ACT! Data? I'm not aware with other language of WIN32 connector. Thanks From python at rcn.com Sun May 2 21:52:27 2004 From: python at rcn.com (Raymond Hettinger) Date: 2 May 2004 18:52:27 -0700 Subject: Efficient string concatenation methods References: Message-ID: <5d83790c.0405021752.2b82345e@posting.google.com> ocrow at skymind.com (Oliver Crow) wrote in message news:... > As a realtive python newb, but an old hack in general, I've been > interested in the impact of having string objects (and other > primitives) be immutable. It seems to me that string concatenation is > a rather common operation, and in Python having immutable strings > results in a performance gotcha for anyone not aware of the impact of > doing lots of concatenation in the obvious way. > > I found several sources with advice for how to do concatenation in a > pythonic way (e.g. ref#1), but I hadn't seen any measurements or > comparisons. So, I put together a little test case and ran it through > for six different methods. Here's the results, and my conclusions: > > http://www.skymind.com/~ocrow/python_string/ > > I'd be happy to hear if anyone else has done similar tests and if > there are any other good candidate methods that I missed. Nice work. Beautifully presented. A few thoughts: * The relative speed of list.append() and list comprehensions versus other approaches will improve dramatically in Py2.4. IOW, the rankings are version specific. Also, append works faster if you precompute the attribute lookup before the loop: build = str_list.append. * The underlying issue has little to do with the immutability of strings. The underlying C code is fearless and would mutate the heck out of it if that is what it took without being visible through the API. The real issue is how much space to allocate for the final string. When iterating, as you do, there is little forewarning about how many more entries to expect or the length of each. If too little space is allocated, then room for a larger string needs to be created and the previous result recopied (giving the O(n**2) behavior you're trying to get rid of). * For arrays, the advantage of mutability does not play out through the fromstring() method (which suffers the previously mentioned allocation issues). The way to capitalize is to make a long array all at once and then make slice assignments into it to add the strings. This is essentially what str.join() does under the hood (it loops over the input once and adds up the string lengths, allocates all necessary space, and re-loops making slice assignments) -- this is how it gets its O(n) behavior. For arrays, I suspect the overhead of tracking the slice pointer would overwhelm the benefits for small values of n. An interesting comparison is to time "ans=[]; build=ans.append; for i in xrange(n): build(i)" versus "ans=[None]*n: for i in xrange(n): ans[i]=i". Raymond Hettinger From loic at fejoz.net Tue May 18 03:03:23 2004 From: loic at fejoz.net (Yermat) Date: Tue, 18 May 2004 09:03:23 +0200 Subject: Python compilers? In-Reply-To: References: Message-ID: Svein Ove Aas wrote: > Is anyone working on a python-to-native compiler? > I'd be interested in taking a look. > > Come to think of it, is anyone working on a sexpr-enabled version of > Python, or anything similar? I really miss my macros whenever I try to > use it... > look at starkiller http://www.python.org/pycon/dc2004/papers/1/ The first step is to create a Type Inference system so there is star killer. Michael Salib said he is working on a C++ translation for python... -- Yermat From cs993442 at cs.yorku.ca Thu May 6 10:10:03 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Thu, 06 May 2004 10:10:03 -0400 Subject: Zero-fill shift In-Reply-To: <7xekpyg11i.fsf@ruckus.brouhaha.com> References: <7xekpyg11i.fsf@ruckus.brouhaha.com> Message-ID: <409A473B.70508@cs.yorku.ca> > That's Wheeler and Needham's Tiny Encryption Algorithm (TEA). You can > just AND the intermediate results with 0xffffffff as needed, but > unless you're trying to interoperate with some other program that > uses that algorithm, you're better off using a different algorithm. > There's plenty to choose from that are already implemented in Python > or as Python extensions. Yes, that is what I'm trying to do (basically I have Java on one end and Python on the other). The Java is running on a Palm device, so using SSL isn't really prudent. This seems like probably the simplest way to do it, so this little problem is really bugging me. ^^; I tried Scott's suggestion, but it's giving me totally different results as well. -_- --Daniel From loic at fejoz.net Fri May 28 07:50:57 2004 From: loic at fejoz.net (Yermat) Date: Fri, 28 May 2004 13:50:57 +0200 Subject: py2exe encoding In-Reply-To: References: Message-ID: Matthias Huening wrote: > Hello, > > I have got a Tkinter application which works just fine (Python 2.3.4, > WinXP). > I made a standalone version of it by using py2exe (0.5.0). Everything > seems okay, but when running this application I am confronted with the > following error: "no codec search functions registered: can't find > encoding". > > Any suggestions? > > Matthias It was in the FAQ and now in the wiki: http://starship.python.net/crew/theller/moin.cgi/EncodingsAgain -- Yermat From bkelley at wi.mit.edu Tue May 11 14:15:05 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 11 May 2004 14:15:05 -0400 Subject: How to update window after wxGrid is updated? In-Reply-To: References: Message-ID: <40a11859$0$560$b45e6eb0@senator-bedfellow.mit.edu> Tim Williams wrote: > Hi. > > I'm starting to learn wxPython and for an exercise I'm writing a > simple CSV file viewer. I just read in the CSV file and create a > wx.Grid with the data. I'm using Python 2.3.2 with wxPython 2.4.2.4. > > Everything runs fine under linux, but when I try the same code on a > Win XP machine, I have a window, but the frame the grid is in isn't > seen until I do a minimize/maximize on the window. Besides that, it > seems to run fine. I tried to do a self.Refresh(True, > self.grid.GetRect()), but that didn't help. Annoying isn't it? There are probably many solutions to this problem, but the one that I use is: > self.grid.AutoSizeColumns(True) > #self.Refresh(True, self.grid.GetRect()) self.twiddle() def twiddle(self): x,y = self.GetSize() self.SetSize((x, y+1)) self.SetSize((x,y)) This forces a repaint of the window and will also add scroll bars if necessary. You are welcome to join us on the wxpython user list as well for more in-depth answers. You have an unrelated bug in your code as well: for i in len(row): should be for i in range(len(row)): Brian From mwh at python.net Wed May 19 05:58:36 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 19 May 2004 09:58:36 GMT Subject: Popen3-style os.execl? References: Message-ID: Chris Green writes: > Hey folks, > > I'm whipping up a quick CGI to wrap a command line app and I was a bit > suprised to not find a execl-like Popen3 style object. I don't want > to bother with the shell interpreting metacharaters by constructing a > command line. > > Basically, I want something that acts just like Popen3 but allows me > to specify cmd as a path + args. Does something like this exist in > the standard library? If not, it sounds like a good candidate... Um. Can't you pass a list to the Popen3 constructor? Cheers, mwh -- same software, different verbosity settings (this one goes to eleven) -- the effbot on the martellibot From anthony at interlink.com.au Thu May 27 06:58:10 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 27 May 2004 20:58:10 +1000 Subject: RELEASED Python 2.3.4 (final) Message-ID: <40B5C9C2.30403@interlink.com.au> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.4 (final). Python 2.3.4 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. For more information on Python 2.3.4, including download links for various platforms, release notes, and known issues, please see: ~ http://www.python.org/2.3.4 Highlights of this new release include: ~ - Bug fixes. According to the release notes, more than 20 bugs ~ have been fixed, including a couple of bugs that could cause ~ Python to crash. These were discovered by Zope3. 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) - -- Anthony Baxter -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFAtcm4Dt3F8mpFyBYRAmgmAJ41U7s98dnQjOOD5XAqqPBJEXvRZwCcCm6x HQQ0vky/iPxSagROZk9Uk8M= =W9rA -----END PGP SIGNATURE----- From rogerb at rogerbinns.com Thu May 20 17:39:39 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Thu, 20 May 2004 14:39:39 -0700 Subject: How to Build Python 2.3.3 C/C++ Extensions in Windows Using Mingw32 References: Message-ID: C. Barnes wrote: > 5. Patch distutils. Locate > \python\lib\distutils\msvccompiler.py, open > it, and find the following lines (around line 211): > > if len (self.__paths) == 0: > raise DistutilsPlatformError, \ > ("Python was built with version %s > of Visual Studio, " > "and extensions need to be built > with the same " > "version of the compiler, but it > isn't installed." % self.__version) > > Delete these. You don't need that. Do this instead: python setup.py build --compiler=mingw32 bdist_wininst Roger From mwh at python.net Tue May 4 07:14:09 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 4 May 2004 11:14:09 GMT Subject: PEP 328 update References: <40967109$1@nntp0.pdx.net> Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article <40967109$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > >Aahz wrote: > >> > >> PEP 328 (``import`` changes) has been updated and is available at > >> http://www.python.org/peps/pep-0328.html > >> > >> Comments on the revised version are welcome. One area where feedback is > >> particularly desired is on the frequency of relative imports inside > >> packages in current code, both in absolute terms and as a percentage of > >> all imports. > > > >I am unclear as to why "import ..moduleA as A" is not allowed. The only > >rationale given for disallowing relative imports like "import .foo" is > >that .foo is unacceptable as a name. I'd propose a mandatory AS-clause > >if the MODULE begins with a period. > > > >This would allow me to do something like "import . as mypackage" -- a > >case which is perhaps unnecessary. I just found the "must use the > >from-style imports" surprising (I agree the change is not vital). > > I'm no expert, but I'd bet that Python's grammar can't support this. > Someone will be by to correct me if I'm wrong. ;-) I think you can do this via the usual 'accept too much in the grammar and throw things out in the compiler' dance. Cheers, mwh -- ARTHUR: But which is probably incapable of drinking the coffee. -- The Hitch-Hikers Guide to the Galaxy, Episode 6 From hungjunglu at yahoo.com Mon May 3 12:53:23 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 May 2004 09:53:23 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> <69cbbef2.0405030127.65aaa9b4@posting.google.com> Message-ID: <8ef9bea6.0405030853.333de14c@posting.google.com> has.temp2 at virgin.net (has) wrote in message news:<69cbbef2.0405030127.65aaa9b4 at posting.google.com>... > hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0405020828.5eafbd5c at posting.google.com>... > > > When one has not even tried, and starts to make criticisms like > > "unification means elimination, I will have to use my shoes to store > > my soup", it brings nothing but regrets. > > ROTFLMAO! I shall frame and mount this line at once! Before things get out of hand and be misunderstood again, I need to make a clarification. I don't make fun at analogies. In fact, anyone that comes up with analogies deserves commendation. Analogies are factorization of different experiences, no different from code factorization that we do in programming. I was pointing out that unification does not mean elimination. In the case example, pockets, shoes, food containers are all still there, even after unification. You still put your soup in your food container. If people want to know about prototype-based, Self is probably a good place to start. http://research.sun.com/self/language.html regards, Hung Jung From ramen at lackingtalent.com Sun May 2 22:31:53 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 03 May 2004 02:31:53 -0000 Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> <1095h4vc89hmcf@corp.supernews.com> Message-ID: In article , Greg Ewing wrote: > Dave Benjamin wrote: >> Hey, I never knew that "this" could be used inside of an anonymous object >> in JavaScript. Thanks for pointing that out! >> >> In Python, you'd have to give the object a name, since there's no "self" to >> refer to. > > No, you wouldn't, because the Python equivalent would > be something like > > def F(): > c = [105] > > class C: > a = 5 > > def incr(self): > self.a += 1 > c[0] += 1 > return [self.a, c[0]] > > return C() I don't know if I'd call it equivalent. Similar in effect, naybe, but the idea was to create an anonymous, classless object. > It's a bit more awkward in Python due to the inability to > directly rebind a name in an outer scope. This is an issue, but not a serious one. In my original example, I used a pretty simple workaround (an anonymous object). > BTW, IMO this is a seriously warped technique that I > would never use, even in Javascript. I can't see any > benefit in it that's anywhere near worth the obfuscation. One benefit, which applies equally to both languages, is that this technique gets you closer to enforced private attributes than the standard ways of making objects. I'm sure you could hack frames or something, but "c" is pretty much inaccessible to the casual programmer in your example above. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From vmilitaru at sympatico.ca Mon May 17 12:56:51 2004 From: vmilitaru at sympatico.ca (Vio) Date: Mon, 17 May 2004 12:56:51 -0400 Subject: Embedded python: "import" problem Message-ID: <4O8qc.18057$325.530372@news20.bellglobal.com> Hi, I've been trying to embed (statically) wxPy alongside an embedded py interpreter on a linux/gtk box. At one point, for some reason misc.o linking reported "multiple definitions of wxGetFreeMemory()". Since wxGetFreeMemory() seemed effectively unused in gtk, I just commented it out in misc_wrap.cpp (didn't want to patch SWIG to regenerate the wrapper code, so hacked the generated cpp source), and replaced "result=(long)wxGetFreeMemory();" with "result=0;". Crossed some fingers... All compiled and links without errors. (but don't try this at home folks: an almost 20MB executable) Anyhow, executing from the embedded interpreter the following: -------------------- import _core import _misc import _windows import _controls import _calendar import _gdi import _grid import _html import _wizard print dir() -------------- outputs: ['__builtins__', '__doc__', '__file__', '__name__', '_calendar', '_controls', '_core', '_gdi', '_grid', '_html', '_misc', '_windows', '_wizard'] but then continuing with: -------------- import core import misc import windows import controls import calendar import gdi import grid import html import wizard -------------- Modules - misc, calendar, grid, html, wizard - they all report ImportError: No module named ... Related: -------------- import core -------------- import core File "somepath/core.py", line 9444, in ? from misc import * ImportError: No module named misc Which is rather odd. Some unsuccessful hacks: 'core.py': around line 9444 replaced "from misc import *" to "from _misc import *". Only to get stopped by the next line (and last line) in "cope.py" with: ./src/helpers.cpp(680): assert "wxAssertFailure" failed: Unable to find stock object [in child thread] Commenting out last line of core.py and running: -------------- print "core.Frame>", core.Frame print "core.App>", core.App a = core.App() -------------- outputs: core.Frame> core.App> Segmentation fault but if I do: -------------- a = _core.new_PyApp() print a -------------- So I don't quite see the big picture here. The good news is that embedded py has access to wx classes, albeit in this not very pythonish raw form, bad news is that I don't quite understand why embedded py interpreter can import some embedded modules (like core and gdi), but fails to import some others (like misc or html). I'm not too sure what causes the segfault, but I suspect some dependencies on the failed imports perhaps? I included my little hack in misc_wrap.cpp, just in case it plays a role here which I missed. Any suggestions welcome, but basically I would appreciate if someone can point me what possibly could make some of these wx modules to get imported, and some to give me an Import Error. Cheers, Vio From della at toglimi.linux.it Thu May 27 11:34:40 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 27 May 2004 15:34:40 GMT Subject: [newbie] conditional imports In-Reply-To: References: Message-ID: vincent Salaun wrote: > - i've written a python xml parser using minidom > - i've written a Jython xml parser using java dom classes - because > minidom doesn't work with jython :( - I'd make a jython module to extend the java DOM API, making them work like minidom (or the subset of minidom that you really need). After that, you could contact the jython maintainers: I'd think they'd be happy to know there's a functional minidom module for Jython :-) Then, the conditional import would become to try: from xml.dom import minidom except ImportError: # We couldn't import xml.dom.minidom, so we are probably using #Jython from my.jython.package import minidom Then, you can go on happily using the minidom without caring whether it's the module you wrote or it's the CPython one. -- Ciao, Matteo From peter at engcorp.com Wed May 26 12:49:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 12:49:54 -0400 Subject: r'\' - python parser bug? In-Reply-To: <8089854e.0405260632.2f4367fc@posting.google.com> References: <8089854e.0405252339.18e0c59d@posting.google.com> <8089854e.0405260632.2f4367fc@posting.google.com> Message-ID: <9rOdnWZMhMssVyndRVn-tA@powergate.ca> Fuzzyman wrote: > Duncan Booth wrote in message news:... >>Raw strings aren't intended for writing DOS pathnames, they are actually >>targetted for regular expressions where this behaviour makes more sense. > > Yeah.. that's not an annoying feature.... I mean no-one would ever > want to use strings to hold Windows pathnames in...... So use forward slashes. They're prettier anyway, and no need for the r strings. -Peter From rupole at hotmail.com Thu May 20 20:38:47 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 20 May 2004 20:38:47 -0400 Subject: GetClipboardData(CF_BITMAP) unimplemented References: <90924643.0405200902.610baf23@posting.google.com> Message-ID: <40ad4bbd_1@127.0.0.1> It's just that nobody has written code yet to do anything with the returned bitmap handle. However, you can still do screen captures without it. The below code should also work with just about any window handle, not just the desktop Roger import win32gui, win32ui, win32con hwnd=win32gui.GetDesktopWindow() l,t,r,b=win32gui.GetWindowRect(hwnd) h=b-t w=r-l hDC = win32gui.GetWindowDC(hwnd) myDC=win32ui.CreateDCFromHandle(hDC) newDC=myDC.CreateCompatibleDC() myBitMap = win32ui.CreateBitmap() myBitMap.CreateCompatibleBitmap(myDC, w, h) newDC.SelectObject(myBitMap) newDC.BitBlt((0,0),(w, h) , myDC, (0,0), win32con.SRCCOPY) myBitMap.Paint(newDC) myBitMap.SaveBitmapFile(newDC,'c:\\tmp.bmp') "Kyle Harrigan" wrote in message news:90924643.0405200902.610baf23 at posting.google.com... > Win32all folks: > > I am attempting to use win32all to perform screen captures and save > the bitmap to a file. The call to GetClipboardData fails saying > GetClipboardData(CF_BITMAP) is unimplemented. Any ideas? > > My code looks something like this: > > win32api.keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0) > win32clipboard.OpenClipboard() > format = win32clipboard.EnumClipboardFormats() > data = win32clipboard.GetClipboardData(format) > win32clipboard.CloseClipboard() > writeFile = open('outfile.bmp','w') > writeFile.write(data) > writeFile.close() From peter at engcorp.com Tue May 25 13:12:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 May 2004 13:12:42 -0400 Subject: Displaying os commands In-Reply-To: References: Message-ID: <-qqdnb3X89UU4y7d4p2dnA@powergate.ca> Perochon Sebastien wrote: > Thanks for all your answers. > I just wanted to know if python got a variable to enable/disable the output. > It seems not. Unlike in the DOS batch file language, with Python the commands are not just automatically "echoed" to the console. Any output that you want you have to generate. It's trivial to do, however, as shown by the examples you've been given. The best option if you really want this is just to define your own "system" command: def system(cmd): print cmd # include the "prompt" if you wish... os.system(cmd) Then just use system('dir') instead of os.system('dir'). -Peter From max at alcyone.com Mon May 17 04:16:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 May 2004 01:16:03 -0700 Subject: What's active and worthwhile in the Python 3D world? References: Message-ID: <40A874C3.B3F0C7AD@alcyone.com> Kenneth McDonald wrote: > One of my current "fun" goals is to start playing with 3D > related things, purely because I find it of interest. Since > I also use and love Python in more serious endeavours, it > would seem to make sense to try to find 3D related things > that involve Python. > > In fact, there seem to be quite a few--so many that I'm > not really sure what is active and growing, and what is > dying off. So I was wondering if there are Pythonistas > out there with similar interests, and if so, what you > might recommend looking at? Sounds like you might want to start playing around with a fairly straightforward Python engine. If you're interested in starting out with something dirt simple, there's ZOE: http://www.alcyone.com/software/zoe/ ZOE is so simple that it almost doesn't deserve special mention was a Python OpenGL engine per se, but that can be helpful if what you just want to do is explore. If you're looking for something a little more fleshed out, then VPython is probably up your alley. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Chastity the most unnatural of the sexual perversions. -- Aldous Huxley From python-url at phaseit.net Mon May 3 17:28:07 2004 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 03 May 2004 21:28:07 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 3) Message-ID: <109deb75jo28v6c@corp.supernews.com> QOTW: "If a keyboard binding doesn't work as you expect it to, it's usually because focus is somewhere else. When in doubt, add a widget.focus_set() call to the appropriate location." -- Fredrik Lundh "I've found this newsgroup most useful for regular doses of 'Pythonic' Zen -- the progression from lumpy new-to-the-language code to smooth idiomatic code, which it seems is best learnt by osmosis and experience." -- James Kew Are conventional computers accurate to a millisecond? Precise within a microsecond? What do these terms *mean*? Grant Edwards, Knio, and others relate their experiences http://groups.google.com/groups?frame=left&th=f749b067884206db Mark McEahern backs Gustavo Niemeyer in his presentation of an engaging Closure recipe. http://groups.google.com/groups?frame=left&th=b415153adf49540b Oleg Paraschenko exhibits a "complete Python Tkinter sample application for a long operation". He uses threading to keep from freezing the GUI http://uucode.com/texts/pylongopgui/pyguiapp.html John Hunter gives the one-paragraph genesis of matplotlib, AND a concrete comparison of Matlab and Numeric white noise, while Colin J. Williams illustrates improved documentation for PyMatrix http://groups.google.com/groups?frame=left&th=bbe6d23ae72c636f Do you want to contribute to the second volume of Python Success Stories? http://groups.google.com/groups?th=bb67015324e512bb Measurement invariably is provocative. beliavsky measures a few Numeric vs. Fortran performance comparisons http://groups.google.com/groups?th=525bc03b9739dccf Scott David Daniels explains how his simple Data class helps him be more productive in interactive work http://groups.google.com/groups?frame=left&th=5c326de1818bac39 PyLinda makes distributed computing pretty (but slow--slower than technically required?) http://www-users.cs.york.ac.uk/~aw/pylinda Martin von Loewis' minutes from the most recent PSF meeting are public http://www.python.org/psf/records/members/minutes-2004-03-25.html ======================================================================== 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 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 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. *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 eriksp at attbi.nospam.com Fri May 21 19:07:51 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 21 May 2004 23:07:51 GMT Subject: Python Newbie References: <3c0a04e4.0405211434.6667f727@posting.google.com> Message-ID: Hey, I'm using the same book! : ) I'm a newbie too, but I think I can still help you. Let's take a look at your code: #Limiting password atempts to three password = raw_input("Enter your Password: ") count = 0 while password != "secret": print password = raw-input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count > 3: print "Please come back when you remember your Password." else: raw_input("Press enter to exit.") The first error I spot is in the loop - "raw-input" should be "raw_input". "elif count" should be == 3, not more than 3. Also, you do not need "print" before "password". If you want to view one of the messages before it closes out, you must take the last statement out of "else" and make it its own. Otherwise, it won't run that statement. The rest is just the structure of the program... according to the loop, the user must enter passwords until he/she types in the word "password", where the statement password != "secret" becomes false. Only then will the program move onto the "if" statement and tell the user whether they are granted access or not. To end the loop when the user guesses 3 times, you need to add another "if" statement inside the loop that breaks it if the count is equal to 3. Here is the new program: #Limiting password atempts to three password = raw_input("Enter your Password: ") count = 0 while password != "secret": if count == 3: break password = raw_input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count == 3: print "Please come back when you remember your Password." else: raw_input("Press enter to exit.") Remember to go step by step through the program when you have errors and see exactly what it does. From loic at yermat.net1.nerim.net Thu May 6 14:15:00 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Thu, 06 May 2004 20:15:00 +0200 Subject: Interfaces in python In-Reply-To: <409a7bf9@news.broadpark.no> References: <409a7bf9@news.broadpark.no> Message-ID: Thomas Weholt a ?crit : > Hi, > > I'm looking for a good clean explanation on how to implement interfaces in > python. My project uses Twisted so I could use their > interface-implementation, but I'm wondering if this is a portable solution > or if it needs Twisted. What I mean is can I use my interface-dependant code > if I decide to use something else than Twisted later? > > I've searched in google, and found stuff like > http://c2.com/cgi/wiki?InterfacesInPython and read the part about > interfaces, components and adapters in the Twisted-docs, but this is > allready what I'm doing now. Stuff like : >[...] Look at archive. There was already lot's of discussion about interfaces... http://groups.google.fr/groups?q=interfaces+group:comp.lang.python In fact, in python, you don't need interfaces ! But you can simulate if you really want them... -- Yermat From grahamd at dscpl.com.au Thu May 6 18:43:18 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 6 May 2004 15:43:18 -0700 Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> Message-ID: Brian Quinlan wrote in message news:... > Right now I'm working in an environment where tabs were mandated as the > indentation style for Python. I've managed to persuade everyone to > switch to 4 space indentation. > > The problem is that we now have a migration problem. Most of our > develoeprs are using VIM which, AFAIK, is not intelligent enough to > detect the current indentation style of a file. Modifying all of our > source files at once to use spaces and then getting everyone to change > their .vimrc is a posibility but not desirable because everyone would > have to check in their work (whatever it's state) at the time of > migration. Does anyone have any suggestions? Ideally, there would be > some way to tell VIM to use the file's exsiting indentation style. That > way I could slowly switch to spaces over time. I have the following to lines in my .exrc file: map ^Ktu 1G!Gunexpand -a^M map ^Kte 1G!Gexpand^M The ^K and ^M are the equivalent control characters. I then type ^Ke and it will pipe the whole contents of the file being edited through "expand" which will turn all tabs into appropriate number of spaces. Typing ^Ku does the opposite. You could run the "expand" program outside of vi as well as part of a shell script and do all your files at the same time. From usenet_spam at janc.invalid Sat May 15 00:07:34 2004 From: usenet_spam at janc.invalid (JanC) Date: Sat, 15 May 2004 04:07:34 GMT Subject: Smalles Possible Browser to display python cgi program References: Message-ID: matthiasjanes at gmx.net (matthiasjanes) schreef: > I would like to know what would be the smalles possible WebBrowser for > displaying Python CGI application. > > I developed a few small application with an WebInterface. > > The appplication runs just locally. > > I use CGIHTTPServer.py Module as a small webserver and Mozilla > Firebird as Browser. > > Does anyone know of a very small browser which I can directly > integrate. > > Just the very minimum for this purbose, no bookmarks, no tools, no > javascript, no flash ...... > > just displaying frames, html, forms, python cgi files and images. For Windows there is OffByOne: Only 450 KiB if you don't need SSL support. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tuure at laurinolli.net Wed May 26 20:35:37 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Thu, 27 May 2004 03:35:37 +0300 Subject: Question from a beginner In-Reply-To: References: <44c2a239.0405261525.5b22cb88@posting.google.com> Message-ID: Larry Bates wrote: > Test1=vector(1,0,0) > Test2=vector(1,0,0) > > to get to "independent" instances of the vector object. The copy function from module copy can also be used to create copies of objects. > > All objects (that I'm aware of) in Python can be > changed. You can even overwrite Python's own > objects. People do it all the time when first > learning. Actually this comes in handy after you > grow accustomed to it. No, not all objects can be changed, but names can be rebound. For example strings and integers are immutable. > > str="abc" > a=str(1) > > and get an error because the str() function has been > redefined to a string containing "abc". The function hasn't been redefined, the name str has been changed to refer to a new object. Consider the following: mystr = str str = "foo" and mystr(1) str(1) From segphault at sbcglobal.net Wed May 12 06:49:41 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 12 May 2004 10:49:41 GMT Subject: process References: Message-ID: On Wed, 12 May 2004 12:33:16 +0200, Jos? wrote: > I have a farm with 4 web servers. > I want to write a client-server program to rotate logs. > Basically the server has only one file, if I run it, the server listens. > The client has 2 files, one client and another server. > If the log is greater than xxx bytes, then the client send a message to > the server, then the server send another message to all the webservers, > and they must to rotate logs. > I'm too new in Python and I don't know a lot of modules, so the problem > is: how can I know which processes are running?. > I writed all, but I want that the "client server" look at the processes. > In case it's rotating logs, it must pause all. In bash it could be: > > #ps ax|grep rotatelogs > > But how in Python? > > thanks in advance I'm not aware of any way to retrieve the process list from python, but you might try this: import commands x = commands.getstatusoutput('ps ax|grep rotatelogs')[1] From p at ulmcnett.com Fri May 14 01:26:56 2004 From: p at ulmcnett.com (Paul McNett) Date: Thu, 13 May 2004 22:26:56 -0700 Subject: I need newbie help In-Reply-To: <9CYoc.126297$Jy3.43222@fed1read03> References: <10a83t8qku40d44@corp.supernews.com> <9CYoc.126297$Jy3.43222@fed1read03> Message-ID: <200405132226.56993.p@ulmcnett.com> Sean Berry writes: > You have to read the whole page to understand why. > > The title is: Python style switches. > Python does not have a swith statement like many other > languages. A switch statement could look like this: > > switch (a) > case 1: do something > case 2: do something else > case 3: do something else > default: do something else > > It evaluates a and checks to see if there is a matching case. > If there is, it executes the code for that case. So if > a==1, it would "do something." What's the matter with using if...elif...else: if case1: # do something elif case2: # do something else elif case3: # do something else else: # do the default something else -- Paul From jbors at mail.ru Mon May 24 18:13:34 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Tue, 25 May 2004 02:13:34 +0400 Subject: Multimedia extensions Framework In-Reply-To: Message-ID: "Roger Binns" wrote: > For other stuff such as storage, you will just be a lot slower than a > kernel level driver. (As an example I get about a 3rd the speed from > Python than kernel drivers when dealing with a device that is just > bulk data). May be packing data into bigger chunks or making a bigger transactions will help ? I think it could be tuned... > The other reason for having kernel level drivers is so that the > devices appear "normally" and can be used by other programs > (eg an audio device appearing as a normal OS level audio device). Absolutely agree in general. But if you consider embedded world, it will be apps running under the common framework( 1 level higher than OS, ex. python vm, .net vm, java vm ), so it may be not that critical to have kernel drivers, whereas it would be more beneficial to have simpler drivers for a lots of different devices/gadgets... Thanks, Dmitry/ From segphault at sbcglobal.net Sat May 8 03:58:59 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 08 May 2004 07:58:59 GMT Subject: __import__ References: Message-ID: On Sat, 08 May 2004 00:31:58 -0700, Coder Coder wrote: > Hi, > Can someone help me with how to overload the __import__ function, > so that I can call the old __import__ function and if it cannot find > the library to be able to do something else. > > - Thanks. The documentation has a small example of import overload: http://docs.python.org/lib/examples-imp.html but a better example David Mertz (my personal hero!) does an excellent job of explaining it simply: """" __import__(s [,globals=globals() [,locals=locals() [,fromlist]]]) Import the module named 's', using namespace dictionaries 'globals' and 'locals'. The argument 'fromlist' may be omitted, but if specified as a nonempty list of strings--e.g., '[""]'--the fully qualified subpackage will be imported. For normal cases, the `import` statement is the way you import modules, but in the special circumstance that the value of 's' is not determined until runtime, use `__import__()`. >>> op = __import__('os.path',globals(),locals(),['']) >>> op.basename('/this/that/other') 'other' """ (I stole this from his web site: http://gnosis.cx/TPiP/appendix_a.txt) He discusses usage of __import__ in his excellent essay on metaclass programming: http://gnosis.cx/publish/programming/metaclass_1.txt You can also find an example in part of his 'Gnosis' library: http://gnosis.cx/download/gnosis/magic/__init__.py Have Fun! From nhodgson at bigpond.net.au Wed May 19 05:16:56 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 19 May 2004 09:16:56 GMT Subject: MFC application and Python References: <2410357897.20040519033752@smtp.myrealbox.com> Message-ID: Adal Chiriliuc: > wxPython is way too bloated (9 MB on disk, 20MB! in memory for basic > stuff) and people say buggy. PythonWin is nice and small, but lacks > some features, like GDI support. At least some of GDI is available. I wrote some of the printing code inside PythonWin and there are calls like dc.GetTextMetrics, dc.SetMapMode, and dc.TextOut. > So this gave me the idea of doing it the other way around: having a > skeleton application which handles Win32 messages and the application > threads and this will call into Python for the logic, which will call > back into C++ for the critical operations and GUI updates. Venster and ctypes may be of interest. Venster doesn't appear very active but was updated as recently as January. Neil From __peter__ at web.de Fri May 14 11:54:55 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 May 2004 17:54:55 +0200 Subject: Loop and the list References: <2gk3eeF3gha1U1@uni-berlin.de> Message-ID: Krzysztof Szynter wrote: > anton muhin wrote in news:2gk3eeF3gha1U1 at uni- > berlin.de: > >> >> max([1, 2, 3]) >> 3 > > It works. Sometimes. It just works. >>> max([1,2,3]) 3 Until you rebind it: >>> max = 123 >>> max([1,2,3]) Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> Peter From tzot at sil-tec.gr Tue May 25 15:34:23 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 25 May 2004 22:34:23 +0300 Subject: Solving the Einstein's Riddle in Python References: Message-ID: <1f77b0pidibf6pej3a05dtveddg40m8u4l@4ax.com> On Tue, 25 May 2004 09:05:53 +0300, rumours say that Juha Haataja might have written: >Your solution is really nice, >a general way of coding the problem in Python. Thanks for the kind words; I just pointed my solution out of a tendency to produce as generic code as I can (that is why my code is also so much slower than yours...). I saw your code, and I believe you have already a good grasp of 'pythonness'; I also enjoyed your algorithm's gradual elimination of combinations --its speed too. My code was also mostly written in my python learning period too (an improvement over my older awk version :). If you ever make something more general (I mean, solving different puzzles without code changes) than your solution and faster than mine, I'd be glad to know :) -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From b.niemann at betternet.de Thu May 27 11:23:50 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Thu, 27 May 2004 17:23:50 +0200 Subject: how to store binary file data to a database blob In-Reply-To: References: Message-ID: > I'd like to read the contents of a file into memory. The problem is > that this file is binary. I then want to store the whole thing in > memory to a database as a blob. > I have no problem reading from a file: I did this: > > import os > f = open('/bin/ls' , 'r+b') > data = f.read() > f.close() > > How do I place that in a blob? If I concatenate this to a sql string, > how will the database sql parser know where my data string ends, knowing > that my data string could contain lots of ' and " and other little > things in it. ??? > > storeString = "insert into mytable (filedata) values ( %s ) " % data > > Does that look right? I don't think it would execute correctly. This probably won't work... Try this (assuming you are working with a Python DB API compatible database class): cursor.execute("insert into mytable (filedata) values ( %s ) ", data) This will let the database class replace %s by your data, including all required escaping stuff - in contrast to a 1:1 string replacment when using the % operator. This works at least for arbitrary strings (and that's the way to handle strings, if you don't like SQL injections ;) But I never tried this with blobs - perhaps they need some special treatment (thinking e.g. of laaarge files)... From eurleif at ecritters.biz Tue May 25 23:45:50 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 26 May 2004 03:45:50 GMT Subject: Update with pickle In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Leif K-Brooks wrote: >> Add interfaces to your object's class for mutability rather than using >> a low-level hack. Something like this (untested): > > Thx for your answer, but according to what I read about __slots__, this > feature has never been intended to be used that way either, so it's also > a kinda low-level hack, no? It is still an interesting solution. Using __slots__ is just an optimization, it isn't directly related to the example. This would also work: class cls: def __init__(self, foo=None): self.foo = foo def set_foo(self, foo): self.foo = foo foo = cls(42) bar = foo print bar.foo # 42 foo.set_foo(43) print bar.foo # 43 From cliechti at gmx.net Mon May 3 19:45:32 2004 From: cliechti at gmx.net (Chris Liechti) Date: Mon, 3 May 2004 23:45:32 +0000 (UTC) Subject: Strategies for backwards compatibility when using pickle? References: Message-ID: "duncan" wrote in news:mailman.219.1083624107.25742.python-list at python.org: > I am working on an application that currently uses a simple pickle to > save a project to disk. > > Every time we make a significant change to our object model we tell our > beta users to delete all of their old projects. > > Does anyone have any advice on how to balance the conflicting interests > of the developers who want to keep evolving the object model and users > who need stable project persistance? i sometimes use .ini files and the config parser o store program settings, but thats no option if you need to store entire object hierarchies. the ini files are at least tolerant to new or removed values and easy to edit by hand, sometimes i pickle and hexlify objects to store them in the ini file too, but then i only do that with built in types to avoid such problems you mention above. > It has been suggested that there may be a way to override pickle to deal > with an evolving object model but it would be nice to hear from others > who have tried to handle this problem. yep, especialy __getstate__ and __setstate__ are interesting for you. by implementing __setstate__ you can filter and update the pickled dictionary before you assign it to the new instance. thats a good way to convert old data to new objects. http://python.org/doc/lib/pickle-inst.html chris -- Chris From ajsiegel at optonline.com Tue May 25 07:51:46 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 May 2004 11:51:46 GMT Subject: terminological obscurity References: <1085248385.210031@yasure><51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: <5lc6b0prleu4cd85up3bdlbdma1l0etgb4@4ax.com> On Tue, 25 May 2004 08:19:49 +0200, "Fredrik Lundh" wrote: >Arthur wrote: >> >> Well for one, before new style classes, it was easier to think of an >> "instance" as in some sense a pseudo data type. Instances of >> different classes - even with no hierarchical relationship - were more >> conceptually homogenous. > >nonsense. Python has always used duck typing (what's important is what >you can do with x, not what type(x) happens to be). this hasn't changed a >bit. > >(if you don't understand duck typing, you don't really understand Python) > > Nonsense. I understand Python - but at a practical user level. If understanding it at that level isn't under5staning it, than it is not what it claims to be. Art From skip at pobox.com Thu May 27 21:28:58 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 May 2004 20:28:58 -0500 Subject: a python script which will parse an email message In-Reply-To: <40B691CD.1050002@ntlworld.com> References: <40B691CD.1050002@ntlworld.com> Message-ID: <16566.38362.377082.903075@montanaro.dyndns.org> chuck> any python script which will parse an email messages into a file chuck> to poplulate a database. Im trying with UnixMailbox but I cant chuck> figure out howto abstract the all email data messages to a file . Take a look at the Spambayes project's mboxutils module: http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/spambayes/mboxutils.py especially the getmbox() function. You'd use it like so: import mboxutils for msg in mboxutils.getmbox("/var/spool/mail/chucka"): print msg['subject'] Skip From randall at tnr.cc Mon May 24 15:40:50 2004 From: randall at tnr.cc (Randall Smith) Date: Mon, 24 May 2004 14:40:50 -0500 Subject: jython 2 cpython bridge Message-ID: <8dssc.179150$f_5.163363@lakeread01> I would like to use a type 4 JDBC driver in my Python program. I believe I can use in with Jython. Do you know of some way to communicate between the Jython and Python processes so that the CPython program can use the Jython JDBC database connection? Randall From Sebastien.Perochon at mmarelli-se.com Tue May 25 09:58:09 2004 From: Sebastien.Perochon at mmarelli-se.com (Perochon Sebastien) Date: Tue, 25 May 2004 15:58:09 +0200 Subject: Displaying os commands Message-ID: <33F0779A2CA2D711BECF0002A545B67AA7D726@ex5chantd01.chatellerault.marelli.fr> Hi all, When I do (on Windows): os.system('dir') The command 'dir' is well executed but the command itself 'c:\dir' is not displayed. How to display the launched command ? Thanks, Sebastien From kdahlhaus at yahoo.com Tue May 11 11:17:51 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 11 May 2004 08:17:51 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: <283adf56.0405110717.d04d999@posting.google.com> There's a sample of an overloading mechanism implemented in the python fltk wrappers on sourceforge. From aahz at pythoncraft.com Wed May 5 10:38:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 5 May 2004 10:38:26 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: In article , Stephen Ferg wrote: >Stephen deleted someone's attribution: >> >> Is submitting a bug or patch to sourceforge really that much of a barrier? > >Yes, it is a significant barrier. It requires knowledge of both Latex >and a certain way of using diff. There are many, many Python users -- >especially Python-on-Windows -- who are not familiar with these >technologies and don't have the time to learn them for the sole >purpose of making a contribution to the documentation. Huh. Fred Drake has said for years that plain-text contributions are welcome. I've submitted an SF bug to make that clear in the docs. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From eriksp at attbi.nospam.com Wed May 26 17:17:31 2004 From: eriksp at attbi.nospam.com (EAS) Date: Wed, 26 May 2004 21:17:31 GMT Subject: Current drive and directory Message-ID: Does anyone know how to display the current directory using DOS and/or Python? I already tried os.pardir and os.curdir in Python, but all they return are a couple of periods... >>>import os >>>print os.curdir . >>>print os.pardir .. From russblau at hotmail.com Fri May 14 16:06:11 2004 From: russblau at hotmail.com (Russell Blau) Date: Fri, 14 May 2004 16:06:11 -0400 Subject: stop()/_quit() References: Message-ID: <2gkn5kF3r1lgU1@uni-berlin.de> "Thomas Philips" wrote in message news:b4a8ffb6.0405141158.29ffab63 at posting.google.com... > NameError: global name '_quit' is not defined > > I've tried stop() instead of _quit(), with similar results. break does > not do the job - it just breaks out of the innermost loop and the > outer loops keep running. What's the fix? Ummm, the error message might be a clue -- you could try *defining* _quit. Or, you could use the standard library function sys.exit(), making sure you import sys first. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From calvin at ironfroggy.com Mon May 31 06:29:47 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Mon, 31 May 2004 10:29:47 +0000 Subject: [].index References: Message-ID: <1254886.aOezpE0fc5@ironfroggy.com> Mike Edey wrote: > Good day. > Recently I'd run into wishing a list's index method would match > substrings. Being fairly new to this game I can't help but think that my > solution is a little, well, clumsy. In the following trivial example I'm > only interested in finding the first matching list item: > >>>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo = >>>> ['b','e','e'] >>>> [data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for >>>> ix in range(len(foo))] > > ['bbb', 'eee', 'eee'] > > > So I guess this question is - have I missed a cleaner method then this > nested list comprehension? This depends on what you need this for exactly. Will you always be matching a single character to the beginning of a string or will they sometimes be more than one character? if only one, then how about storing the strings as a dict with the characters as keys? From newsgroups at jhrothjr.com Sun May 9 16:31:06 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 9 May 2004 16:31:06 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: <109t59e3v0oob1d@news.supernews.com> "Olivier Scalbert" wrote in message news:409e86e9$0$22811$a0ced6e1 at news.skynet.be... > Hello , > > What is the python way of doing this : > perl -pi -e 's/string1/string2/' file > ? > Thanks > Olivier I'm not sure what the -pi and -e switches do, but the rest is fairly simple, although not as simple as the perl one-liner. Just load the file into a string variable, and either use the string .replace() method, or use a regx, depending on which is appropriate. Then write it back out. from the python prompt (not the command prompt) that's something like: (untested) var = open("file", "r").read().replace("string1", "string2") open("file", "w").write(var) I think this is about as obfusticated as you can get - you'll lose the file if you try for a one-liner. John Roth From mark at prothon.org Tue May 25 17:51:20 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 25 May 2004 14:51:20 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <40B394F2.8020807@jessikat.fsnet.co.uk> <1xNsc.17979$bF3.1356@fed1read01> <40B3BA35.8050907@jessikat.fsnet.co.uk> Message-ID: "Robin Becker" wrote in message news:40B3BA35.8050907 at jessikat.fsnet.co.uk... > Mark Hahn wrote: > > "Robin Becker" wrote > > > > > >>In fact the python time for fib(35) was about 31.1 seconds (ie less than > >>prothon for fib(25)) so something is spectacularly amiss with prothon. > > > > > > Yes, and that something is that Prothon is pre-alpha and full of debug code. > > Take a look at the interpreter loop in interp.c and the reason will be > > obvious immediately. We are not going to be addressing efficiency until > > after the language is designed in July. > > > > One step at a time... > > Wasn't criticising. I expected some degredation from an early version, > but this seems too much. From the memory usage I would guess that > perhaps the frames aren't being released. Oh, I didn't realize you were talking about memory. We do have serious memory and object leaks. Maybe the garbage collector isn't working right. That area is also waiting for July as we are considering it part of performance. From R.Brodie at rl.ac.uk Fri May 21 06:22:31 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 21 May 2004 11:22:31 +0100 Subject: pexpect and OpenVMS References: <40ac9eaa@duster.adelaide.on.net> Message-ID: "Adrian Casey" wrote in message news:40ac9eaa at duster.adelaide.on.net... > Any ideas on how to make pexpect work with VMS systems? I'm surprised you even got pexpect to run under VMS. The fiddly terminal stuff doesn't look easy to port. Have you got some build details? From Mark.Puchalski at honigman.com Tue May 25 08:54:56 2004 From: Mark.Puchalski at honigman.com (mp312) Date: Tue, 25 May 2004 12:54:56 -0000 Subject: Newbie question Message-ID: I have a script that I need to do the following: Taking a user id that is in the format 'userid at MACAddress', read the userid portion (varying length) and concatenate with @honigman.com. Suggestions? Thanks. From amireallyfat at yahoo.com.au Thu May 27 02:11:39 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Thu, 27 May 2004 16:11:39 +1000 Subject: why learn Message-ID: <40b58695_1@news.iprimus.com.au> hey i finished working through alot of python stuff and no a fair bit bout it now what can i do with it??? From htx1 at gmx.de Tue May 11 09:03:35 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Tue, 11 May 2004 15:03:35 +0200 Subject: Are assert checks unpythonic? (was: Passing objects to a function) In-Reply-To: References: Message-ID: bruno modulix wrote: > Holger T?rk a ?crit : >> bruno modulix wrote: >>> Holger T?rk a ?crit : >>>> This could be supported by an assert statement: >>>> >>>> def BlackJackValue(hand): >>>> """BlackJackValue(Hand_instance) -> int\n\nReturn an integer, which >>>> is the value of the Hand according to the rules of BlackJack.""" >>>> assert isinstance (hand, Hand) >>>> [...] >>>> The method will throw an AssertionError if hand is not >>>> an instance of Hand. Assertions can be turned off later for >>>> performance reasons; with -O I guess. >>> >>> Note that this is also highly unpythonic since you won't be able to pass >> >> Unpythonic? That's a matter of taste. So: maybe. > > We can discuss the point... But to summarize what I have in mind : > testing for a *specific* type is fighting against the very dynamic > nature of Python instead of taking advantage of it (IMHO etc...) The dynamic nature is a very powerful tool and it may be applied when needed. But one does not have to. >>> objects that implements the Hand interface but do not subclass Hand. >>> This may not be a problem in this specific case, but this probably >>> should not be recommanded in the general case unless there is a very >>> compelling reason to do so... >> >> The assert statement, as it is used in the example above, describes >> the assumptions the programmer had in mind when writing the function >> it is written in. > > Not being psychic, I can't say what the programmer actually had in mind > when writing this specific piece of code !-) But whatever, the fact is > that the code needs a 'Hand-like' object, not a 'Hand' object. The > important word here is 'like'. I understand. It's like the omnipresent file-like object, an object which is not actually a file, but an object which supports read() and write(). Or was it write() and close()? Or even read(), tell() and seek ()? Seems like it depends on the client, even within the standard library. But instead of an AssertionError, telling me that my file-like object isn't file-like enough, an AttributeError is raised deep inside the module. In some cases, even TypeErrors may occur. That's my problem with foo-like objects implementing varying interfaces that aren't checked. Why isn't there a superclass "FileLike" with the standard methods that all raise NotImplementedError, "method bar"? So when NotImplementedError is raised, it's absolutely clear what's missing. I can't tell that from an AttributeError without deeper investigation. In this case: Hand could specialize HandLike and the assert could be "assert isinstance (hand, HandLike)". But that looks like a lot of useless work. >> Programs are not written into stone. When the need arises, the assert >> statement can be modified, e.g. to check an interface >> (hasattr (hand, containsCard), or something else), or even removed. > > But this require source-code modification. What's wrong with it? A function doesn't become poisonous once it's finished. A second person using the code may be unwilling or unable to change it. OK. But when you offer your code to someone else, you should be especially careful with the effects of your program/library. >> Because documentation regularly turns out to be neglected and assert >> statements are easily written, >> it's recommended to use them unless >> there is a good reason to drop them. > > > it's as easy to write : > def BlackJackValue(hand): > """expects a Hand-like object""" > [...] > > Because assert (or any other type-specific check) prevents from using > the same code with object of other types supporting the same protocol, > it's recommended to *not* use'em that way unless there is a *compelling* > reason to do so. Most of this discussion is based on the difference of our perspectives of what objects are: I focus on what something *is*, and you focus on what something *does* and how its "doing" is accessed. So I clearly understand your point of view. Still I do not understand why there should not be any explicit check of this interface, or why this interface should not be made explicit by extracting it into a class? Of course this doesn't make much sense when one wants to write a function like str(), which works on a large variety of objects. But for a specific problem domain, any means of making the program more explicit should be welcome. Any implicit interface, like the one you advocate, has to be properly documented, or else it will be forgotten, even by the author. And documentation, as I pointed out, regularly tends to be neglected. >> In this special case, Thomas clearly wanted to express that the >> parameter hand should be an instance of Hand. > > Whatever he 'clearly' wanted to express, what he *needs* to express is > that the parameter 'hand' should be an instance of any object responding First of all: He has to decide on his own what he wants and needs. He wrote: "I'd like to write the parameter list of a method or function in a way that makes the class of each parameter crystal clear, [...]" This undoubtedly is a demand for a strong restriction of the parameter type, i.e. he wanted to be sure that hand is a Hand, as opposed to hand being handlike. This can be enforced with assert, though it can't be documented with it. I don't see any point in saying: You can do it with foo, but don't do it with foo, because it does not match the spirit of the language (of which foo is a part), and because of that, you don't want and need it anyway. Maybe he likes assert and it makes him confident when he reasons out his program. Maybe it doesn't. At least it works for me. Greetings, Holger > to the messages that will be send to it. And the good news is that there > is no need to explicitely check for this, as if the object fails to do > so, an AttributeError will be raised. > >> So why shouldn't it >> be documented and checked this way? From dmq at gain.com Sat May 22 14:23:05 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 22 May 2004 11:23:05 -0700 Subject: Method binding confusion References: Message-ID: On Mon, 03 May 2004 19:52:02 +0200, Peter Otten <__peter__ at web.de> wrote: >The machinery behind the observed behaviour is now somewhat clearer - I >think you can predict a function's behaviour as a method by checking >hasattr(func, "__get__"). But still the *reason* (or simply use-case) for >this dichotomy of functions (to me) remains unclear. Why are not all >functions created equal? All functions and methods *should* be unified. See the section "Unification of all function forms" in PrototypeSyntax.doc at http://www.ece.arizona.edu/~edatools/Python I'm astonished at how a problem like this can be tolerated in a language that claims to be simple. Here is my simplification of the example which started this thread: import math def mypow(x, y): return x**y class MathA: pow = math.pow class MathB: pow = mypow ma = MathA() mb = MathB() print ma.pow(2,4) #=> 16.0 print mb.pow(2,4) #=> # TypeError: mypow() takes exactly 2 arguments (3 given) This problem, and a lot of others that confuse beginners could be eliminated if all functions and methods had exactly the same sequence of arguments (no special first argument). -- Dave From fperez528 at yahoo.com Sat May 15 15:36:54 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 15 May 2004 13:36:54 -0600 Subject: Idea: PYTHONPATH_VER References: Message-ID: Peter Hansen wrote: > Fernando Perez wrote: > >> Peter Hansen wrote: >>>Having missed the discussion preceding, I'm probably off the mark, >>>but in my experience just about everything that can be solved with >>>PYTHONPATH can be handled with a .pth file as well, and I haven't >>>had any need to use PYTHONPATH for quite some time as a result. >> >> How do you handle the fact that .pth files are only read from certain places, >> and not others? This problem has me currently rather stuck with gross hacks: [snip] > I might have some better idea how to deal with it if I'd ever had > trouble with it. One thing to note: I do most development on Windows. > Perhaps, for some reason, the problems are lesser there. (Which would > be a little surprising, but given Linux' issues with installing > software, perhaps not entirely unlikely.) Thanks, Peter. I might start a separate thread asking about this, with a clearer description of my problem. I don't think it's a linux issue, but rather one of dealing with when python loads (or not) .pth files. As I said, it may well just be my misunderstanding of how the system really works. Regards, Fernando From mark at prothon.org Sun May 23 18:04:00 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 23 May 2004 15:04:00 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01><30260531.0405222153.5027c135@posting.google.com> Message-ID: Does any Python user have a story of regret of using an object's attribute when they should not have and encapsulation would have saved their butts? In my Python usage when I found that I shouldn't be directly accessing an attribute it was no different than finding any other bug and I refactored and moved on. It certainly would have been more work to worry about all the attributes to start with. Does anyone have any story of encapsulation being a hero in any situation or of regret at not having it? I've programmed since the 60's and I have no regrets in 30+ years in not having encapsulation when I didn't have it and no hero stories in my four years of using Java. I certainly don't miss it in my Prothon. From fumanchu at amor.org Mon May 3 12:06:46 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 3 May 2004 09:06:46 -0700 Subject: Method binding confusion Message-ID: Peter Otten wrote: > > import math > #import myModule > > def mypow(x, y): > return "%s ** %s" % (x, y) > > class Klass(object): > def doOperation(self, x, y): > return self.operator(x, y) > > class KlassMath(Klass): > operator = math.pow > > class KlassMyModule(Klass): > operator = mypow #myModule.pow > > km = KlassMath() > kmy = KlassMyModule() > > print km.doOperation(2,4) > print kmy.doOperation(2,4) > > > >>> class A: > ... pass > ... > >>> def method(*args): > ... print args > ... > >>> A.m = method > >>> > >>> A().m(1,2) > (<__main__.A instance at 0x40296bac>, 1, 2) > > See? Although defined outside the class, method() is called with 3 > parameters. *I* could have sworn that _that_ would always happen. But: > > >>> import math > >>> A.m = math.pow > >>> A().m(1,2) > 1.0 > >>> > > Now I am as confused as you and the OP :-( Specifically, one needs to explain why: >>> kmy.KlassMath.operator >>> kmy.KlassMath().operator but: >>> kmy.KlassMyModule.operator >>> kmy.KlassMyModule().operator > ...which I haven't got the vocabulary or time for right now. ;( Robert Brewer MIS Amor Ministries fumanchu at amor.org From wolf_tracks at invalid.inv Tue May 4 00:48:41 2004 From: wolf_tracks at invalid.inv (W. Watson) Date: Tue, 04 May 2004 04:48:41 GMT Subject: Setting an Image File Values Message-ID: I have a 640x480 b/w bmp image file that can be converted to a dat file. I would like to convert the value of each pixel that is below say 120 units to exactly 40 units. I've never written a python program in my life. However, the manual for the image application I'm looking at show the following line to create a mask.dat file of size 640x480 bytes with every value set to 40: python -c "open('mask.dat','w').write(chr(40)*640*480)" I suspect a program to do what I need is not much more complicated. Can someone construct a program for me to do the job? It'll probably be the only python program I ever need. -- Wayne T. Watson (121.015 Deg. W, 39.262 Deg. N, 2,701 feet, Nevada City, CA) -- GMT-8 hr std. time, RJ Rcvr 39? 8' 0" N, 121? 1' 0" W Two laws Newton and Einstein didn't discover: 1. Time is money. 2. Matter will be damaged in direct proportion to its value. Web Page: sierra_mtnview -at- earthlink -dot- net Imaginarium Museum: From Chris.Hornberger at blackrock.com Thu May 13 11:36:13 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Thu, 13 May 2004 11:36:13 -0400 Subject: General Ledger/Accounting Libraries Message-ID: >It does lead to some awkward code. For example, to calculate a value >from a quantity and a price, I have to say > > value = int(round(price * value / 1000000.0)) > >This requires you to know what scale is used for each column, so >mistakes are easy to make. As you say, the Decimal package, when it is >released, will make life much easier. That's a nice work around. You could store the scales in the db and read them at app-startup and store them in a settings collection/class, thus eliminating hard-coding scale computations. You could also make that flexible by grabbing a prerelease decimal package and coding against both models, teaching your app how to load decimal if it's available or falling back to scale/math when necessary. Might mean a tad more db maintenance up front, but also ensures a safe and robust distributable software package. *shrugs* It's an idea. From juha.haataja at csc.no-spam.fi Mon May 24 07:12:38 2004 From: juha.haataja at csc.no-spam.fi (Juha Haataja) Date: Mon, 24 May 2004 14:12:38 +0300 Subject: Solving the Einstein's Riddle in Python Message-ID: I have been learning Python since April, and would like a few comments from the experts on list processing. I managed to implement a Python code for solving the so-called Einstein's Riddle, see e.g.: http://www.manbottle.com/trivia/Einstein_s_Riddle.htm I solved the problem in two ways, first the straightforward way by using lists and list comprehensions. Then I refactored to code using the Python object model by deriving new datatypes from the Python list object. The two versions are available here: http://www.csc.fi/oppaat/f95/python/talot.py http://www.csc.fi/oppaat/f95/python/talot_oo.py I apologize for not commenting the code. (I localized the data, so the nationalities are now mainly Nordic. The input data of the first version is in Finnish. Also, I don't like smoking, so I changed that part of the data to different types of music.) Here is the final output of the OO version: Choices: 1 1 2 3 4 5 yellow blue red green white norway denmark finland germany sweden water tea milk coffee beer blues opera rock pop metal cat horse bird fish dog Thus the German owns the fish in house 4. The OO version is somewhat slower (1.6 seconds vs. 1.2), but easier to understand. I'm wondering why the code is 50% slower. In principle, the only difference should be that in the OO versio I'm using an __init__ method, and in the original version I was creating lists using []. Please feel free to comment on the programming style. I'm just starting to get to know the language, and my background in Fortran 90/95 may be a handicap in learning Python. Thanks, - JuHa From miki.tebeka at zoran.com Tue May 11 02:47:09 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 May 2004 08:47:09 +0200 Subject: Shipping embedded Python project In-Reply-To: References: Message-ID: <40A076ED.3000107@zoran.com> Hello Thomas, > Or you use py2exe to build a zip-compatible archive, and insert it into > sys.path in your program. Do not specify any of the console and windows > options, and pass your 'main-module' with the --includes command line > option. py2exe will happily create a dist directory for you, without an > exe-file. Great! thanks. Miki From troy at gci.net Sun May 30 02:11:56 2004 From: troy at gci.net (Troy Melhase) Date: Sat, 29 May 2004 22:11:56 -0800 Subject: generalizing the CGI case was: Re: mod_python confusion In-Reply-To: <40B9231F.70609@harvee.org> References: <153fa67.0405281046.331b1b19@posting.google.com> <40B9231F.70609@harvee.org> Message-ID: <200405292211.57030.troy@gci.net> On Saturday 29 May 2004 03:56 pm, Eric S. Johansson wrote: > Since the integration isn't going to happen anytime soon, I am content > to run a persistent process (like fast CGI) with some glue logic handing > data over. The question is, is there a general framework for this. XML > RPC is a possibility but my experience has shown in to be a somewhat > sluggish protocol using the stock XML RPC server in Python. Have you tried the Fast Python XML RPC library? http://sourceforge.net/projects/py-xmlrpc/ Also, you may want to host it on a server other than one from the standard library, such as Medusa, Twisted, or Zope. -- Troy Melhase, troy at gci.net -- These are the days when the Christian is expected to praise every creed except his own. - G. K. Chesterton From tim.one at comcast.net Thu May 13 18:58:36 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 13 May 2004 18:58:36 -0400 Subject: struct doesn't handle NaN values? In-Reply-To: Message-ID: [Grant Edwards] > There's a table that clearly defines when it [struct] uses "native" vs. > "standard" byte-order and size-and-alignment. > > One assumes that the floating point _representation_ could > likewise be native or standard (IEEE), Yes, this is the case. > but it never specifies which FP representation is used when. The same as everything else: in native mode, whatever float and double representation the platform uses is what struct uses, just as in native mode struct uses whatever the platform uses for chars, shorts, ints and longs. In standard mode, the representation is forced to IEEE 754 float or double format. But it's still the case that all behavior wrt NaNs, Infs, and signed zeroes is an accident in standard mode. Indeed, it's precisely *because* standard mode tries to force the representation to a known format (and Python has no idea whether the platform it's running on uses 754 format natively or not) that these accidents occur. C89 predates 754 adoption, and so offers no portable facilities even for recognizing whether a thing is a NaN, Inf, or signed 0. "Standard" C tricks like if (x != x) { /* then x is a NaN */ } don't actually work across platforms (although many with limited x-platform experience believe they do). > Since "IEEE" is mentioned in the discussion of "standard size and > alignment", And only there. > I would guess that FP native vs. standard representation > matches the native vs. standard state of "size and alignment". I'm not sure what that sentence said, but bet it's right . From phil at riverbankcomputing.co.uk Mon May 24 13:22:58 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 24 May 2004 18:22:58 +0100 Subject: PyQt, main window can't have reference to application class In-Reply-To: <2hegkeFblripU1@uni-berlin.de> References: <2hegkeFblripU1@uni-berlin.de> Message-ID: <200405241822.58590.phil@riverbankcomputing.co.uk> On Monday 24 May 2004 3:54 pm, Sibylle Koczian wrote: > Still trying to learn PyQt from a book about several Python GUI > toolkits, I seem to learn first what doesn't work. The following small > script seems to work, but after closing the window I get the error > message "Fatal Python error: PyEval_RestoreThread: NULL tstate". You have created a circular reference which won't help. The problem doesn't occur if PyQt is built with SIP v4 - it uses the newer Python thread API. > Without the line "self.app = app" the error goes away. So I suppose the > main window can't have a reference to the application class. Right? > Using the global variable qApp instead of self.app doesn't work either: > qApp seems to be an instance of QApplication, not an instance of HelloApp. It's the same C++ instance, but they are different types. knopftext is an attribute of the HelloApp type. qApp is of type QApplication. > Should the GUI independent actions of the application rather be methods > of the main window? Or methods of some class not derived from QObject, > with a reference to an instance of this class in the main window > instance and not in the application instance? Comparing with Delphi I > suppose this might be the better way. I'd like to use the same class > with different GUI toolkits (Tkinter, wxPython), so all the GUI > independent stuff should be separate. > > #!/usr/bin/python > # -*- coding: latin-1 -*- > # hello2.py > > import sys > from qt import * > > class HelloWindow(QMainWindow): > > def __init__(self, app, *args): > QMainWindow.__init__(self, *args) > self.app = app #### this seems to be the problem #### > self.button = QPushButton(self.app.knopftext, self) > # self.button = QPushButton(qApp.knopftext, self) #### won't run at > all #### > self.setCentralWidget(self.button) > self.connect(self.button, SIGNAL('clicked()'), self, > SLOT('close()')) > > class HelloApp(QApplication): > > def __init__(self, *args): > QApplication.__init__(self, *args) > self.knopftext = 'HelloApp' > self.connect(self, SIGNAL('lastWindowClosed()'), > self, SLOT('quit()')) > self.MainWindow = HelloWindow(self) > self.setMainWidget(self.MainWindow) > self.MainWindow.show() > > def main(args): > app = HelloApp(args) > app.exec_loop() > > if __name__ == '__main__': > main(sys.argv) > > Thank you, > Koczian Phil From shalabh at cafepy.com Thu May 13 01:15:04 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 12 May 2004 22:15:04 -0700 Subject: Class instance problem? In-Reply-To: References: Message-ID: Zhao Huang wrote: > Hi, > > I'm new to python and I've come across a problem with my objects > corrupting each other. > > class aclass: > num = 0 > l = [[],[]] These create class attributes, not instance attributes. For example, after this you can try: print aclass.num print aclass.l > a = aclass() > b = aclass() > a.l.append(1) Since the instance a does not have an 'l' attribute, a.l refers to the class attribute aclass.l. You can verify this at this point by: print a.l is aclass.l # 'is' checks identity of objects Also you do a.l.append(1). The .append() (note the '.') tells python to append to the referred object. You are calling a method on the list object and you end up appending to aclass.l. > print "a.l",a.l > print "b.l",b.l Also try, print a.l is b.l. There is only one list object, it is on the class aclass but can be referenced through a.l and b.l. > My expectation is that a,b are separate objects, but appending to > a's l also appends to b's l. Why does this occur? On the other hand, > the command > > a.num = 1 Aha, here you use the '=' operator. Compare with operation on the list l earlier, where you used the '.' operator and a method name 'append'. The '=' creates an instance attribute 'num' on a. > doesn't change b.num's. Nope, there is no instance attribute 'num' on b as of now. print b.num merely prints aclass.num. Now that you know about '=', you can try a.L = [] b.L = [] a.L.append(1) print a.L, b.L And you'll see that you have two distinct lists. Actually three distinct ones if you count aclass.l. If you only need instance attributes, don't put them on the class. Use the following: class aclass: def __init__(self): self.L = [] self.num = 0 a = aclass() b = aclass() # play with a.L, b.L, a.num, b.num This is inconsistency is driving me crazy. > What am I doing wrong? Hope the above helped. > > Thanks for any help -- Shalabh From __peter__ at web.de Mon May 3 13:52:02 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2004 19:52:02 +0200 Subject: Method binding confusion References: Message-ID: Robert Brewer wrote: > Specifically, one needs to explain why: > >>>> kmy.KlassMath.operator > >>>> kmy.KlassMath().operator > > > but: > >>>> kmy.KlassMyModule.operator > >>>> kmy.KlassMyModule().operator > 0x0114DCD0>> > > ...which I haven't got the vocabulary or time for right now. ;( Following Andrew Bennetts' hint and rereading parts of http://users.rcn.com/python/download/Descriptor.htm the following is the most striking example that I could come up with to demonstrate how the existence/absence of a __get__() method controls a method's behaviour: >>> import types >>> class Method(object): ... def __get__(self, obj, objtype=None): ... return types.MethodType(self, obj, objtype) ... def __call__(*args): ... print "method%r" % (args,) ... >>> class A: pass ... >>> A.method = Method() >>> a = A() >>> a.method(1,2,3) method(<__main__.Method object at 0x40296d0c>, <__main__.A instance at 0x40296c0c>, 1, 2, 3) Now away with __get__(): >>> del Method.__get__ >>> a.method(1,2,3) method(<__main__.Method object at 0x40296d0c>, 1, 2, 3) >>> Bye the way, I tried this with a simple function first, but failed: >>> def f(): pass ... >>> del f.__get__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object attribute '__get__' is read-only >>> The machinery behind the observed behaviour is now somewhat clearer - I think you can predict a function's behaviour as a method by checking hasattr(func, "__get__"). But still the *reason* (or simply use-case) for this dichotomy of functions (to me) remains unclear. Why are not all functions created equal? Peter From Chris.Hornberger at blackrock.com Fri May 14 14:24:06 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Fri, 14 May 2004 14:24:06 -0400 Subject: I need newbie help Message-ID: > Since Python doesn't have a switch statement, you can make your own. > In Python you could do something like this though: > > selector={ > x<0 : 'return None', > 0<=x<1 : 'return 1', > 1<=x<2 : 'return 2', > 2<=x<3 : 'return 3', > 3<=x : 'return None' > }[a] > > if a == 1, it would "return 1". > I'd rather see, as long as there's a known domain of data, using a dictionary to return a known value. $.02 From mir4uu at yahoo.com Thu May 20 09:58:48 2004 From: mir4uu at yahoo.com (mir nazim) Date: 20 May 2004 06:58:48 -0700 Subject: newbie: sample code for wxpython/twisted References: <425cc8d1.0405190904.4b92a20b@posting.google.com> Message-ID: <425cc8d1.0405200558.5379884c@posting.google.com> mir4uu at yahoo.com (mir nazim) wrote in message news:<425cc8d1.0405190904.4b92a20b at posting.google.com>... > hi, hello, > > i am new to python but not new to programming. i am a php > developer(with some c/c++ under by belt). to let u know the level of > programming experience i have (so that u can help me better, no > arrogance intended), i have developed a web based adaptive testing > system, a sale/stock/inventory/ management system and am currently > working on a web based school management system, all in php. > > now i and my team want to shift to python. i will first shift to > python the my team members. > > i have been doing python(language only) for quite a good time. by now > i feel little confident with python and i want to try my hands on some > larger/real life things. i want to learn wxPython and twisted. > > but my problem is that i am unable to locate some project that uses > wxPython or twisted. i would like to know about some open source > projects which address the needs businesses wxPython/twisted. for > example an small accounting package,point of sale system, a hotel > management system, a groupware system etc. > > it is not necessary that wxPython and twisted must used in the same > project. can be two different projects. my point is that i want to > learn both. i am look for some good quality code to get started. i > have seen the wxPython demos but am not satisfied. > > if any one of u can point me to the projects that use wxPython or > twisted or both. best if it not a too big project that a beginner like > me will get overwhelmed. > > Thanks in advance for any help. > > --------------- > Mir Nazim. > Lead Developer. > XenSoft, Inc. > Kashmir(India). hi, i found schooltool http://schooltool.org uses both wxPython and twisted. hope it is helpful. can u tell me about other projects. From slawek at cs.lth.se Wed May 26 18:34:44 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Thu, 27 May 2004 00:34:44 +0200 Subject: Some Newbie Questions In-Reply-To: <40b47710@e-post.inode.at> References: <40b47710@e-post.inode.at> Message-ID: <20040527002206.3923.SLAWEK@cs.lth.se> On Wed, 26 May 2004 12:56:21 +0200 Leopold Schwinger wrote: #> (2) Is there any way to dynamically import modules, where the name #> of the module is not known during implementation but can be defined #> during scipt execution? Sure: Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> exec("import socket") >>> socket.socket() -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Write your questions down on the back of $20 dollar bill and send them to me. From s_gherman at yahoo.com Tue May 4 12:11:50 2004 From: s_gherman at yahoo.com (Sorin Gherman) Date: 4 May 2004 09:11:50 -0700 Subject: table widget in Tkinter ? Message-ID: Is there any table/list-control/list-view widget available in Tkinter? That is, something with several lines and columns (maybe similar to wxlistctrl in wxWindows)? Thanks in advance, /sorin From j_mckitrick at bigfoot.com Fri May 7 16:05:30 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 7 May 2004 13:05:30 -0700 Subject: How to change tkinter GUI look-and-feel? References: Message-ID: That's a good start, thanks! From __peter__ at web.de Sun May 2 04:46:24 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2004 10:46:24 +0200 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> <246a4e07.0405012334.5e5474db@posting.google.com> Message-ID: Frank Millman wrote: > I have recently introduced the concept of a 'table type', such as > 'Master' or 'Transaction', and have written my own subclasses with > standard methods to handle each type of table. The table type is > passed as an argument to the 'open' function. which now checks for a > user-defined subclass first, if not found checks the type to see if a > standard subclass exists, if not found instantiates the main class. > This works well. > > The concern is that a table may be of type Master, but a user may > create their own subclass and inherit from Table instead of Master by > mistake. I want to detect this error and raise an exception. How about providing a subclass for every table the user might want to subclass: class Table: def __init__(self, name=None): if name is None: try: name = self.name except AttributeError: name = self.__class__.__name__ self.name = name class Master(Table): pass class Transaction(Table): pass # provide a suggestively named class for every table in your application class Employees(Table): pass class Departments(Master): pass class Invoices(Transaction): name = "not-a-legal-identifier" for cls in [Employees, Departments, Invoices]: print cls().name Now the user can just subclass Employees without having to care whether it has to be derived from Transaction, Master, Table or whatever. If he needs to know, he can discover it on the command line: >>> issubclass(Employees, Transaction) False >>> issubclass(Invoices, Transaction) True >>> An additional benefit is that user code is shielded to some extent from modifications in your code, e. g., you could later change the base of Employees from Table to Master without requiring changes in client code. Peter From dmq at gain.com Sun May 23 23:25:51 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 23 May 2004 20:25:51 -0700 Subject: Unification of Methods and Functions References: <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> <16752bcc.0405230518.2023328a@posting.google.com> Message-ID: On 23 May 2004 06:18:54 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:... >> On 22 May 2004 11:50:18 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> >David MacQuigg wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... >> >> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> >David MacQuigg wrote: >> >> >> I like your example, but not as a *substitute* for Animals_2. It's >> >> just too complex for non-CIS students at this point in the course. I >> >> think I understand your concerns about Animals_2. I think the best >> >> way to deal with those concerns is not by complicating the example, or >> >> by taking out everything that could lead to problems, but rather by >> >> pointing out the problems, and showing subsequent examples that fix >> >> those problems, even at the expense of more complexity. >> >> >> >> If you have a simple all-in-one alternative to Animals_2, show me. >> >> >> > >> >Again, clearly I have not communicated myself well - I mean a >> >*completely* different example to the entire Animals approach. The >> >difficulty with writing a good Animals-type example comes from the >> >things which it is trying to do, which aren't especially well >> >expressed by a class-heirarchy. >> >> What I am trying to do in Animals_2 is provide the simplest, most >> learnable example of Python OOP, which has at least one of every basic >> structure the students will encounter in a real program. So I include >> bound, unbound, and static methods, but not metaclasses or >> descriptors. >> >> Creating a good example like this is turning out to be more of a >> challenge than I expected. I'm fairly happy with Animals_2, but I >> appreciate the "maintainability" problems you have pointed out, and >> have added footnotes accordingly. The examples in Learning Python are >> too spread out in little pieces, and of course, no attention to the >> issues you are concerned about. If you know of another place I can >> look for a good all-in-one teaching example, I am interested. >> > >Just for the sake of example, this is one of the programs which I >always write while learning a language, written in a way I'd use to >demonstrate OO; all it does is read in a wordlist, then print out >synonyms for user-inputed words. Handy for crosswords. ;-) I've posted these examples on our webpage at http://ece.arizona.edu/~edatools/Python/Examples Let me know if I should make any changes. These will be very helpful for students to see alternative styles in programming. -- Dave From nav+posts at bandersnatch.org Fri May 14 10:43:11 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 14 May 2004 10:43:11 -0400 Subject: I need newbie help References: <10a83t8qku40d44@corp.supernews.com> <9CYoc.126297$Jy3.43222@fed1read03> Message-ID: Paul McNett

writes: > What's the matter with using if...elif...else: In the example, I think the advantage is that the dictionary lookup is data driven. If you want to add a new location, you just extend the dictionary, which is cleaner than adding another clause to an if...elif block. Also, if you want to change the name of a location, you just change the relevant data -- not the code. 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 moughanj at tcd.ie Fri May 7 09:31:51 2004 From: moughanj at tcd.ie (James Moughan) Date: 7 May 2004 06:31:51 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> Message-ID: <16752bcc.0405070531.10dcc1fc@posting.google.com> David MacQuigg wrote in message news:... > On 6 May 2004 08:37:50 -0700, moughanj at tcd.ie (James Moughan) wrote: > > I don't want to argue implementation details, as I am no expert, but I > think you are saying something is wrong at the user level, and that > puzzles me. > > A global function, if I understand your terminology correctly, is one > defined at the module level, outside of any class. Such a function > cannot have instance variables. If you were to reference that > function from within a class, it would just act as a normal function > (a static method in Python terminology). I can't see the problem. > Let me give an example: def getLength(s): return s.length class Foo: length = 5 Foo.getLength = getLength foo = Foo() print length(foo), foo.length() A method in a class in Python is just like a global function; for a global function to operate on an object, it must take it as an argument. The prototype syntax would appear to break the above example. > The difference in the proposed syntax is that it doesn't need the > staticmethod wrapper to tell the interpreter -- don't expect a special > first argument. In the new syntax all functions/methods will have the > same calling sequence. If a method doesn't operate on the data from an object then as a rule it should be global. There are exceptions, but they generally don't occur in Python so much as a in 'true oo' language like Java. > I've looked at a few introductions to Python, and in my opinion > Learning Python, 2nd ed, by Mark Lutz and David Ascher is the best. > It strikes a good balance between the minimal presentation that > tersely covers the essentials for an experienced programmer vs the > long, windy introductions that put you to sleep with analogies to car > parts and other "objects". Lutz takes 95 pages to cover OOP. I think > I could do a little better, maybe 70 pages, but that may be just my > ego :>) > > When you say ten pages, you must be making some very different > assumptions about the students or their prior background, or the > desired level of proficiency. The least I can imagine is about 30 > pages, if we include exercises and examples. And that 30 assumes we > get rid of all the unneccesary complexity (static methods, lambdas, > etc.) that currently fills the pages of Learning Python. > I'm assuming they alreay know the general structures of programming in Python, and that you can then just show them how to package data and methods into a class with a clear example, by rewriting a program you've shown them before. After that it's mainly a question of explaining why you should do it, which is probably rather more important than how. I've never met anyone who had difficulty in understanding anything about the syntax of OO other than the class/object distinction. It's fundamentally very simple once you have a basis in all the other programming techniques. Unless you're talking about the entire programming course, 70 pages is waaay too much - your students just will not read them, regardless of how brilliant they are. > >There are static methods in Python? :) In my coding the major reason > >for static methods is for data encapsulation for singleton-style > >elements. Python has no data encapsulation worth anything, so static > >methods don't do much that's useful. > > We have the usual dose of terminology problems here. The term 'static > method' in Python may be different than in other languages. In Python > it just means a method that has no instance variables, no special > first argument, and an extra 'staticmethod' line, to tell the > interpreter not to expect a special first argument. > OK; no particular difference from Java/C++/etc. > Python does have "encapsulation" but does not have "hiding", by my > understanding of these words. The idea is that __private variables > are easily identified to avoid accidents, but there is no attempt to > stop deliberate access to such variables. This is a design philosophy > that I like. > *Nods* That's why I said 'worth anything'; the idea of encapsulation, in theory, is to prevent screw-ups, which is why hiding is key. Not that it's necessarily a good theory. :) I also like Python's philosophy here. > > > >I must note that Animals_2 is a total abuse of OOP techniques. You > >continuously define classes to do the same thing, repeat the same code > >in each, then give them slightly different names. > > This is a textbook introduction, not a real program. The purpose of > the example is to show a complete OOP hierarchy in a small example, > with a good selection of the method styles most needed in a real > program. The similarity between the show() methods in different > classes would not be so tempting to reduce to one global function if I > had made a larger example, with more radically different outputs from > each show function. I thought that just changing one string in each > function would be enough to say "This function is different." > OOP is a tool. It's abstraction makes it tempting to create arbitrary structures as examples, but doing that looses any sense of the reason why you would use that tool. That's why I see people with CS degrees who can throw around objects and heirarchies at will but who can't structure a simple program effectively. > You are not the only one who had this reaction. See my reply to Don > Cave above. I guess I need to thow in a little more "meat", so that > experienced programmers don't get distracted by the possibility of > making the whole program simpler by taking advantage of its > regularities. This is the same problem I've seen in many texts on > OOP. You really can't see the advantages of OOP in a short example if > you look at it with the attitude -- I can do that much more easily > without classes. It's when you get to really big complex hierarchies > that the advantages of OOP become clear. > Learning to program is about 5% how to do something, and 95% when and why you should do it. You seem to be focusing almost exclusively on how, which I suspect is why we're all so upset :) you get that way when you have to fix the code which eventually results. > >Also, your show method is IMO more than dubious. show does not > >logically belong to Feline. As a result you are using a class to > >display data about other classes to which it is not connected. This > >is not OOP. > > I thought this part was pretty clear. The show() method at each level > calls the show() method one level up, then adds its own stuff at the > end. Feline.show() calls Mammal.show(), which prints lots of stuff > characteristic of mammals, all in a format unique to the Mammal class. > Mammal.show() in turn calls Animal.show(). At each level we have some > unique display of characteristics. The purpose is to have a call at a > particular level show all characteristics of the animal from that > level up. > It is clear, just not a good idea. > >If I were teaching someone and they produced this structure then I'd > >go over the rationale with them and try to figure out where they went > >wrong in their planning of the program, and maybe go back and tutor > >them on the basic ideas of OOP. I would not change the language to > >make it easier to do in future. :) > > Both responses I have on this are basically experts saying -- you can > solve this particular problem more easily by restructuring it. I > should have been more clear. Imagine that each of these classes and > methods is fully expanded with lots of parameters to make each one > unique. Don't even think about re-structuring, unless you are trying > to tell me that the whole idea of having these structures in any > program is wrong. That would surprise me, since this "animals" > example is a common illustration of OOP. > OK: "The whole idea of having these structures in any program is wrong." Firstly, the program uses a class hierarchy as a data structure. That isn't what class heirarchies are designed for, and not how they should be used IMO. But it's what any bright student will pick up from the example. Secondly, it breaks the entire concept of OOP. Objects are designed to be individual entities with side-effects restricted to their scope, in order to modularize programs. In this example, you use side effects from one class to influence the output of another; a bovine will end up influencing the output of a cat, for example. And the effect in completely implicit. As a result, someone who is introducing a mouse class can break another part of your system without the faintest idea that they are affecting it. It's a fragile structure leading to the almost inevitable creation of the most intractable type of bug. The fact that Python makes it hard to do is *good*. > What I'm looking for is not clever re-structuring, but just a > straightforward translation, and some comments along the way -- oh > yes, that is a little awkward having to use a staticmethod here. Wow, > you mean staticmethods aren't fundamentally necessary, just a bandaid > to make up for Python's deficiencies? That was my reaction when I > first saw Prothon. > Static methods are more like a band-aid to make up for the deficiencies of OOP. Python isn't a pure OO language, and doesn't suffer the need for them badly. > Thanks again for your feedback. > > -- Dave From jdhunter at ace.bsd.uchicago.edu Sun May 16 10:42:33 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 16 May 2004 09:42:33 -0500 Subject: how to write a python program tht reads (x,y) In-Reply-To: ("Selbourne makhomo"'s message of "Sun, 16 May 2004 14:58:10 +0200") References: Message-ID: >>>>> "Selbourne" == Selbourne makhomo writes: Selbourne> Could you please help me with the following graphs: Selbourne> 1. python graph that reads in (x,y) data from a file Selbourne> 2. modify the program to draw a graph of the function Selbourne> using wxpython 3. python graph that performs a linear Selbourne> least squares regression, which fits a straight line Selbourne> through the points 3. plot the straight line in a Selbourne> different colour to the original graph connecting the Selbourne> points. Selbourne> I will appreciate your assistance in this regard. There are a number of ways to do it, eg, scipy contains everything you need to do it. Here is an example script using matplotlib. matplotlib works with wx (and other GUI toolkits). I'm assuming your data are in two ASCII columns for x and y. from matplotlib.matlab import * data = load('xydata.dat') x = data[:,0] y = data[:,1] #m and b are the best bit slope and intercept m,b = polyfit(x,y,1) # a line is a 1st order polynomial # blue dots and red solid line plot(x, y, 'b.', x, 3*x + b, 'r-') title('best fit line to noisy data') xlabel('x') ylabel('y') show() You can select wx as your default in the configuration file .matplotlibrc, or from the command line. Here is a screenshot of the result in a wx window http://nitace.bsd.uchicago.edu:8080/files/share/best_fit.png The function polyfit is defined in matplotlib.mlab (matplotlib.matlab imports all these functions too) and does general polygon fitting . A line is simplest case where the order of the polygon is 1. If you want to embed matplotlib in a wx application, rather than simply use it from the shell or in a script, see the examples/embedding_in_wx.py that comes with the matplotlib src distribution. http://matplotlib.sourceforge.net/ Good luck! John Hunter From jdhunter at ace.bsd.uchicago.edu Thu May 13 08:15:39 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 13 May 2004 07:15:39 -0500 Subject: inheritance and cxx Message-ID: I am using pycxx 5.2.2 to implement some extension code and have a problem relating to inheritance. I have a pure virtual base class and two concrete derived classes. In the code below, everthing works fine in that the derived classes can use the base method get, but if I try and add a method only available to Derived2, eg, get2, I get a compiler error on the call to add_varargs_method("get2",&Derived2::get2, "get2()\n"); in Derived::init_type. inheritance.cxx:73: error: no matching function for call to ` Py::PythonExtension::add_varargs_method(const char[5], Py::Object (Derived2::*)(const Py::Tuple&), const char[8])' /usr/local/include/python2.3/CXX/Extensions.hxx:574: error: candidates are: static void Py::PythonExtension::add_varargs_method(const char*, Py::Object (T::*)(const Py::Tuple&), const char*) [with T = Base] inheritance.cxx: In function `void initinheritance()': inheritance.cxx:124: warning: unused variable `inheritance_module*inheritance' error: command 'gcc' failed with exit status 1 How should I structure the code so that I can have inherited base methods but also allow derived classes to have their own methods? If I try defining Derived2 as class Derived1: public Py::PythonExtension, public Base so that it gets it's own add_varargs_method I get into trouble because both of the base classes share many functions so I get multiple inheritance errors. Complete example follows... #include #include #include #include "CXX/Extensions.hxx" class Base : public Py::PythonExtension { public: virtual Py::Object get(const Py::Tuple &args)=0; static void init_type(void); }; // a mutable float class Derived1: public Base { public: Derived1(double val) : _val(val) {} static void init_type(void); Py::Object get(const Py::Tuple & args) { return Py::Float(_val ); } private: double _val; }; // binary operations on lazy values class Derived2: public Base { public: Derived2(Base* b) : _b(b) {} static void init_type(void); Py::Object get(const Py::Tuple & args) { return _b->get(args); } Py::Object get2(const Py::Tuple & args) { return _b->get(args); } private: Base* _b; }; void Base::init_type() { behaviors().name("Base"); behaviors().doc("My base class"); add_varargs_method("get", &Base::get, "get()\n"); } void Derived1::init_type() { behaviors().name("Derived1"); behaviors().doc("Derived 1"); } void Derived2::init_type() { behaviors().name("Derived2"); behaviors().doc("Derived 2"); add_varargs_method("get2", &Derived2::get2, "get2()\n"); } // the extension module class inheritance_module : public Py::ExtensionModule { public: inheritance_module() : Py::ExtensionModule( "inheritance" ) { Base::init_type(); Derived1::init_type(); Derived2::init_type(); add_varargs_method("Derived1", &inheritance_module::new_derived1, "Derived1(x)"); add_varargs_method("Derived2", &inheritance_module::new_derived2, "Derived2(b)"); initialize( "The inheritance module" ); } virtual ~inheritance_module() {} private: Py::Object inheritance_module::new_derived1 (const Py::Tuple &args) { args.verify_length(1); double val = Py::Float(args[0]); return Py::Object( new Derived1(val) ); } Py::Object inheritance_module::new_derived2 (const Py::Tuple &args) { args.verify_length(1); if (!Base::check(args[0])) throw Py::TypeError("Derived2(b) expecting a base instance"); Base* b = static_cast(args[0].ptr()); return Py::Object( new Derived2(b) ); } }; extern "C" DL_EXPORT(void) initinheritance(void) { static inheritance_module* inheritance = new inheritance_module; }; From segphault at sbcglobal.net Mon May 31 15:58:10 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 31 May 2004 19:58:10 GMT Subject: getting mimetype of a file References: Message-ID: On Mon, 31 May 2004 19:54:53 +0000, Ryan Paul wrote: > is there any way to determine the mimetype of a file using ruby? > > TIA > > --SegPhault =P just realized I sent this to the wrong list. as long as I'm here... how is it done in python? From ajsiegel at optonline.com Wed May 26 08:28:49 2004 From: ajsiegel at optonline.com (Arthur) Date: Wed, 26 May 2004 12:28:49 GMT Subject: terminological obscurity References: <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <1085551118.250464@yasure> Message-ID: On Wed, 26 May 2004 05:58:40 -0000, "Donn Cave" wrote: > Just forget about Guido for a while, OK? My beef with the discussions on Python list surrounding the distinction between tuples and lists has never been with Guido. Though it isn't possbile to try to express that beef without his name coming up. >If you are constructing a conceptually homogeneous sequence, use a >list. Always have, always will. Art From __peter__ at web.de Sun May 2 07:24:09 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 May 2004 13:24:09 +0200 Subject: Looking at the next element in a for loop References: Message-ID: - wrote: > If I have a simple for loop like this: > > for a in b: > print a > > Is there a way I can get the next element in the loop? Something like > this: > > for a in b: > if a == 1: > print You could reverse the logic: >>> wasMatch = False >>> for a in [1,2,1,1,1,3,1,4]: ... if wasMatch: print a, ... wasMatch = a == 1 ... 2 1 1 3 4 >>> Or do something like this: >>> b = [1,2,1,1,1,3,1,4] >>> for a, nexta in zip(b, b[1:]): ... if a == 1: print nexta, ... 2 1 1 3 4 >>> If you like the latter, you can use the window() function on the itertools example page http://www.python.org/doc/current/lib/itertools-example.html for a better implementation: for a, nexta in window(b): if a == 1: print nexta, Peter From paul at prescod.net Thu May 13 11:42:00 2004 From: paul at prescod.net (Paul Prescod) Date: Thu, 13 May 2004 08:42:00 -0700 Subject: Python - open forever ? In-Reply-To: <593D8B10B2409E468D3E916CA156C84D0326C930@mail02.ad.telekom.lv> References: <593D8B10B2409E468D3E916CA156C84D0326C930@mail02.ad.telekom.lv> Message-ID: <40A39748.1000902@prescod.net> Romans Krjukovs wrote: >... > - There is a risk that Python can become closed and unsupported in the > future. > (Remember RedHat ?) There are two different issues here. One is long-term support for a particular software release. You can certainly buy support for even RedHat 1.0 (was there such a thing?) from consultants and contractors. You just cannot buy it (easily) from RedHat. But even they might not turn down your money if you offered them enough. The second is whether Python will become closed. The Python license makes this literally impossible. As soon as you download Python you have a perpetual license to it and the code forever. Guido could make a new version and try to charge money for it, but the rest of the Python world would just ignore him and continue to work on the open version that we all know and love. Even if only a tiny fraction of the Python world cared about keeping it open (which is unlikely) they could continue to make the open version available forever. > - Who can guarantee that Python will be usable and available to us if > it is > develeped and maintained by the hackers from all over the world > without > any obligations and guarantees ? Download it. Then you have it. It will never become less available than it is today. As far as usable on future operating systems and hardware: people used to the closed-source model completely invert the relationship between licensing and availability of future versions. For a proprietary language like Visual Basic to die (or be morphed into an incompatible language) it takes a single decision by a single decision maker at a single company. I've been at a company where they killed the development of a scripting language like Python after it already had a good user base. Those users were stranded. We were ordered not to work on it because it wasn't profitable enough for the business. ("we don't like to make little piles of money. We like to make buckets and buckets of money") For Python development to stop, _every_ Python developer would have to decide to stop doing it. Guido could not stop Tim Peters from working on future versions of Python nor vice versa. Python is immune to dips in the economy, to corporate mergers and buyouts, to individual or corporate bankruptcies, to shifting opinion polls. It survived the years from 1992 to 1996 when Guido did almost all of development by himself and knew most of the users personally. The mainstream had never heard of it. Now its future is secure for at least the next 13 years. > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) There is very little risk, but it would be nice of you to join the PSF. What risk there is probably stems from the possibility that Python accidentally violates a patent. Python is no more or less prone to this than a proprietary product but in today's litigious world, it is nevertheless a risk. You can help mititgate it by sponsoring the PSF. > Python is very fast in development, stable and fast code, easy to learn, > but never the less big and business critical project can't be started > without > mentioned risk analyses. > It would be nice to know what Python society members think about this. Open source is a means for minimizing risk and reducing your dependence on companies that invariably need to make decisions in their own best interest rather than yours. Paul Prescod From eric at zomething.com Wed May 19 03:10:50 2004 From: eric at zomething.com (Eric @ Zomething) Date: Tue, 18 May 2004 23:10:50 -0800 Subject: So what's a "pythong"? (was Re: Python/C++ Developers required for consulting position in Brooklyn, NY) Message-ID: <20040518231050.858653009.eric@zomething.com> David Lees wrote: > Perhaps "Pythongs" are the current fashion statement FINALLY, a marketing make-over. Pythong! Snakes and lingerie in a single word. This is going to sell big. Heck, my pulse is racing even now. I gotta go "Product" think: For the future, I think one would want to anticipate much larger datasets than most normally deal with, and faster networking speeds (x10, x100, x1000?), which, in conjunction with processing larger datasets, will tend make processing speed more often the bottleneck than it is now). We'll need all the good things about Python, but maybe more speed as well. >>> 'She's at Warp 10, Jim! She's giving us all she's got!' == True From ajsiegel at optonline.com Sun May 30 07:44:01 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 30 May 2004 11:44:01 GMT Subject: terminological obscurity References: <1085248385.210031@yasure><51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: <55ijb01a95i9ccfn2hut9q8dv1gvogut4c@4ax.com> On Tue, 25 May 2004 08:19:49 +0200, "Fredrik Lundh" wrote: >Arthur wrote: >> >> Well for one, before new style classes, it was easier to think of an >> "instance" as in some sense a pseudo data type. Instances of >> different classes - even with no hierarchical relationship - were more >> conceptually homogenous. > >nonsense. Python has always used duck typing (what's important is what >you can do with x, not what type(x) happens to be). this hasn't changed a >bit. Putting together what you and Martin are saying, am I correct then that what type(x) returns in Python is something other than x's type. that's strange. Art From akhilesh at it.iitb.ac.in Sun May 16 09:31:55 2004 From: akhilesh at it.iitb.ac.in (Akhilesh S. Shirbhate) Date: 16 May 2004 06:31:55 -0700 Subject: CORBA Python Query Message-ID: <789bf36d.0405160531.2b6a991e@posting.google.com> Sorry for reposting, but please help me... I desperately need help. I wrote a small CORBA program and am using ORBit-python. The IDL file was as below: --------------------------- module MESSAGING { typedef sequence msgLines; struct msg { string fr; string to; msgLines body; }; interface mail { void submit (in msg message); }; }; --------------------------------- The server program is as below: --------------------------------- #!/usr/bin/python import CORBA class mail: msg = 0 def submit(self, msg): print "Message Recieved from:", msg.fr print "Message for:", msg.to for line in msg.body: print line self.msgs = self.msgs + 1; print "Message Served: ", self.msgs CORBA.load_idl("msg.idl") CORBA.load_idl("/usr/share/idl/name-service.idl") orb = CORBA.ORB_init((), CORBA.ORB_ID) poa = orb.resolve_initial_references("RootPOA") servant = POA.MESSAGING.mail(mail()) poa.activate_object(servant) ref = poa.servant_to_reference(servant) open("./msg-server.ior","w").write(orb.object_to_string(ref)) print "Wrote IOR to file", orb.object_to_string(ref) poa.the_POAManager.activate() orb.run() --------------------------------- After running the program, it gives the following errors: --------------------------------- Traceback (innermost last): File "./msg-server.py", line 14, in ? CORBA.load_idl("msg.idl") AttributeError: load_idl --------------------------------- If I change the CORBA.load_idl to CORBA._load_idl then the error comes at some other place... Namely below: --------------------------------- Traceback (innermost last): File "./msg-server.py", line 20, in ? servant = POA.MESSAGING.mail(mail()) NameError: POA --------------------------------- The CORBA module is dynamically loaded from the following file: /usr/lib/python1.5/site-packages/CORBAmodule.so I have installed orbit-python-0.3.0-1 on my machine. Please help me out.. I need help desperately to run the server :(( Thanx in advance :) From stevenbee at removethis.part.att.net Tue May 4 17:33:04 2004 From: stevenbee at removethis.part.att.net (Steven Brent) Date: Tue, 04 May 2004 17:33:04 -0400 Subject: iter jitters In-Reply-To: References: Message-ID: OK, thanks ... that explains why my other idea of returning a new list to iterate over didn't work either. Talk about chasing one's tail... Btw, I just realized that a custom __getitem__ method I defined earlier in the module(and unhelpfully didnt post), handles the iteration in 2 lines! def __getitem__(self, index): return self.data[index] This is the kind of thing I was after, because I didn't want any iteration going on in the __iter__ definition itself. Trying to reinvent the wheel for exercise. But generators are cool, and I promise to use them lots :-) This seems to be a recurring pattern for me; I get deep into confusion by skipping over the obvious. Thanks for the clarity and knowledge. --Steven the newbie =========================== Diez B. Roggisch wrote: > Steven Brent wrote: > > >>In the snippet below, I'm trying to overload the __iter__ list method: >> >> def __iter__(self): >> print "using custom iter" >> counter = 0 >> end = len(self.data) - 1 >> while counter <= end: >> print self.data[counter] >> counter += 1 >> >>It pretty much works, except that the output is ugly when the while loop >>falls off the end of the list: >> > > >> File "mylist.py", line 38, in ? >> for item in L3:print item, >> TypeError: iter() returned non-iterator of type 'NoneType' >> >>Oh, yeah, plus it's adding a newline at the end of each item even though >>I've got the comma there. I'm gonna keep plugging away to see if I can >>figure this out, but stuff like this makes me frustrated... Thanks a >>million. > > > I think you've got something wrong here - __iter__ is supposed to return an > object that supports the iteration protocol - mainly a next() method that > throws an exception when no more elements are available. > > Today, this kind of thingy is usually done using generators: > > class foo: > def __init__(self): > self.data = range(10) > > def __iter__(self): > def _my_iter(): > for e in self.data: > yield e > return _my_iter() > > > for i in foo(): > print i > > > From mir4uu at yahoo.com Mon May 31 12:55:21 2004 From: mir4uu at yahoo.com (mir nazim) Date: 31 May 2004 09:55:21 -0700 Subject: wxPython tab order Message-ID: <425cc8d1.0405310855.7d4cb33c@posting.google.com> hi, is there a way to change the default tab traversal order of wx controls? and wxcalendar causes segementation dfault. why is it so. thanks, From jcarlson at uci.edu Wed May 5 19:12:43 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 05 May 2004 16:12:43 -0700 Subject: Numeric speed In-Reply-To: <4092ace5_1@news.binaries.net> References: <4092ace5_1@news.binaries.net> Message-ID: You seem to be new at Python, so I'll give you a some information that you should know before talking about benchmarking Python: 1. Python is slow. 2. Python evaluates the arguments of a function call before calling the function. That is, when evaluating the following sum(xx**1) xx**1 is evaluated before sum is called. Those who program and/or know mathematics, call this precidence. Since Python does not include an optimizer, xx**1 is always called, even though it doesn't do anything. 3. Your benchmark looks to really be testing the performance of the random number generating array function and the sum functions. I believe that both are implemented in C. Your "benchmark" therefore, is benchmarking C vs Fortran. I thought such things were out of vogue 10 years ago. Speaking of which, when will people stop comparing Fortran (whose optimizing compilers have had 30+ years to evolve) against Python (whose compilers don't optimize in the classic sense). 4. Posting "benchmarks" without posting the entirety of the code used to produce the results is fundamentally useless. Did you use the unix 'time' command? Did you use the Python 'time' module? Etcetera. - Josiah P.S. Python being slower that Fortran or (insert your favorite language here) wouldn't surprise me. While Python has been getting faster over the years, the design considerations are for usability first, speed later. From no at spam.invalid Thu May 20 14:24:27 2004 From: no at spam.invalid (Russell E. Owen) Date: Thu, 20 May 2004 11:24:27 -0700 Subject: Tkinter: update_idletasks References: Message-ID: In article , Jeffrey Barish wrote: >I'm confused about how to use the update_idletasks method. In my >program, I have a handler for a button in which execution will linger. >During that time, I would like for the GUI to continue to show signs of >life. I have a Pmw MessageBar in which I display a status message. I >figured out that if I run update_idletasks on that MessageBar, then the >MessageBar will update the display as I update the message. However, >if I cover the GUI with some other window and then expose it again, the >GUI does not refresh until the handler finishes (except for the >MessageBar). Do I have to run the update_idletasks method for every >widget in the GUI? for all the frames? for just the root frame? Or is >it impossible to get the GUI to refresh in this situation? To make your GUI responsive, call update_idletasks occasionally from the task that is taking a long time. Like most GUI systems, Tkinter is basically a single threaded system. It'll run the current task until finished, then process the next event. update_idletasks gives it a chance to handle other events. There are other ways to handle this sort of thing. Typically a long-running task should be run as a separate background thread (or even a separate process). The difficulty is that background threads cannot safely interact with GUI elements, so how does the thread communicate? The most straightforward technique is to transfer data from the background thread to the main thread via a Queue object (as usual), then poll the background thread's Queue (by repeatedly calling after to do a nonblocking read on the Queue object). However, a clever trick posted fairly recently is to have the background thread generate an event. Apparently that is safe. Then have a handler listen for that event. The handler will run in the main thread, and so can safely update the GUI. -- Russell From rory_geoghegan at yahoo.com Mon May 10 13:41:30 2004 From: rory_geoghegan at yahoo.com (Rory Geoghegan) Date: 10 May 2004 10:41:30 -0700 Subject: Integer division, surprising results References: Message-ID: <7aa8fd19.0405100941.43553112@posting.google.com> > I've looked at faqs and documentation, and nothing jumped out at me. Can > anyone explain the reasoning for this? According to my math book integer division is defined as such: a/b = q, where a = b*q + r and r is the remainder. A remainder (ei a modulo) is always positive, effectively flooring all the division operations. From fbouffar at gel.ulaval.ca Wed May 26 15:01:08 2004 From: fbouffar at gel.ulaval.ca (Francois Bouffard) Date: 26 May 2004 12:01:08 -0700 Subject: Loggers and reloads Message-ID: <68fe96e8.0405261101.dd3cd14@posting.google.com> (Disclaimer: I'm new to both Python and OOP in general, and I may have skipped a few lines in the docs) I'm using the logging module inside one of my module. I instanciate a logger which uses a StreamHandler to output to sys.stdout. It works really well; however, I mainly use my module in the Python interpreter in an interactive way, and I often have to reload said module. The problem is that each time I reload my module, a new logger object seems to be created, and the old one is not deleted. Both the new and the old object are still working, so that each log message is repeated; in general, if I did N reloads of my module, each message is repeated N+1 times. The del statement seems to only delete references, so that it can't be used to get rid of the old logger objects. Maybe the logging.shutdown() function is supposed to be of some help here, but I don't see how to use it. Any hint as to what I'm doing wrong or what I should do is welcome. Here's some sample module code: module logtest.py --------------- import sys, logging LOGLEVEL = logging.INFO loghandler = logging.StreamHandler(sys.stdout) logformat = logging.Formatter('%(name)s :: %(message)s') loghandler.setFormatter(logformat) logger = logging.getLogger('LoggerExample') logger.addHandler(loghandler) logger.setLevel(LOGLEVEL) def info_message(): logger.info('This is an info-level message') --------------- >>> import logtest >>> logtest.info_message() LoggerExample :: This is an info-level message >>> reload(logtest) >>> logtest.info_message() LoggerExample :: This is an info-level message LoggerExample :: This is an info-level message From pwmiller1 at adelphia.net Mon May 24 11:20:59 2004 From: pwmiller1 at adelphia.net (Paul Miller) Date: 24 May 2004 08:20:59 -0700 Subject: Tkinter MDI-style widget? Message-ID: <2e363c08.0405240720.6831f33@posting.google.com> I posted a couple of days ago looking for pointers on how to create a wiget that has a settable title and can't be moved outside the parent widget. What I'm really looking for is a Windows-style MDI widget. Does this exist/is it possible to make in Tkinter? The only thing I know of that behaves sort of the way I want is the Tkinter canvas item. Now I know you can create new canvas items through the tcl C interface, but would even that make it possible to do what I want? (Not that I really want to go that route, anyway.) From martin at v.loewis.de Fri May 28 03:01:46 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 May 2004 09:01:46 +0200 Subject: terminological obscurity In-Reply-To: <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> References: <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> Message-ID: <40b6e3d6$0$12458$9b622d9e@news.freenet.de> Arthur wrote: > Donn. who I think we agree, brought some light to this discussion did > state clearly, I think, that the use of the "homogenous data" (in > describing for example None and a module) is bad and misleading > terminolgy. Perhaps, because it supports too well a supposition that > we are only talking in tautologies. What can be said be homogenous > about such data, outside of the membership in a list? It is obvious that a single piece of data, in itself, cannot be homogenous. You have to pick a set of objects to determine whether they are homogenous. However, they are NOT homogenous by the mere fact that they are in set, and they are NOT homogenous by the fact that they share all the same type. Instead, they share the same semantical properties (whatever those are). So: No, "homogenous data" is *NOT* a tautology. It refers to inherent properties of the elements of the list, not to the fact that they are members of the list. It is possible to create a heterogenous list; the Python style suggests that you should not do that. If "lists are for homogenous data" was a tautology, the term "heterogenous lists" would be a contradiction. However, it is not: it is a meaningful term indeed. > Yet you insist, with a fresh start on all this, on using the > terminology "homogenous data". > > I don't understand Martin any better thatn I understand Guido. I don't see where I use the term in any new way in which it hasn't been used before. I *also* mentioned that Guido has talked about typing, and explained how a list of differently-typed objects may still get a single static type. However, static typing of lists and homogenous lists (i.e. lists of homogenous data) are different (although related) issues. Regards, Martin From me at privacy.net Tue May 25 07:02:09 2004 From: me at privacy.net (Heather Coppersmith) Date: 25 May 2004 07:02:09 -0400 Subject: Prothon vs. Python integers References: Message-ID: On 24 May 2004 23:49:42 -0700, danb_83 at yahoo.com (Dan Bishop) wrote: > Heather Coppersmith wrote in message news:... >> Accountants ("bean counters," in the derogatory vernacular) >> will be displeased if Prothon silently loses pennies (or other >> small- valued currencies) after a certain amount > Or credit card numbers. They're 16 digits long, and Microsoft > Excel has this inconvenient feature of displaying them with 15 > significant digits. Credit card numbers aren't integers, though; they just look like integers (modulo the internal spaces) when you print them out (not unlike U.S. postal codes, which consist of five or nine digits). Excel overzealously converts all such entries to mathematical objects. What does it mean, for example, to multiply your credit card number by three? Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From alan.gauld at btinternet.com Mon May 17 17:24:37 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 May 2004 22:24:37 +0100 Subject: beginner's question References: <1df3cfd12f5ac728e6aefcfd7ca32cb0@news.teranews.com> Message-ID: On Mon, 17 May 2004 12:51:55 GMT, Daniel 'Dang' Griffith wrote: > >what's wrong with helping to new beginners? > >Don't be snob! > > He's not being a snob. Please understand than on the internet, many > students will try to get the public to answer their homework for them, > without doing the work on their own. And FWIW the same policies are applied on the Python tutor mailing list which is specifically for beginners, but we still expect to see some evidence of effort from the poster. OTOH If you are a beginner you may find the tutor list worth subscribing to, just post the right kind of questions and you'll get lots of help. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From me at privacy.net Thu May 27 03:46:39 2004 From: me at privacy.net (Duncan Booth) Date: 27 May 2004 07:46:39 GMT Subject: Current drive and directory References: <40b50a15$1_1@127.0.0.1> <56oab0lrlg9dit9g19qdrargpominsqkj0@4ax.com> Message-ID: Dennis Lee Bieber wrote in news:56oab0lrlg9dit9g19qdrargpominsqkj0 at 4ax.com: >> And also, when I actually run the program, I have trouble using >> notepad on files: >> >> MS-DOS Prompt >> 'Q' to Quit >> >> C:\Documents and Settings\Erik\Desktop>cd \windows\system32 > > This os.system() performed a CD, and then exited -- all history > is lost. > >> >> C:\Documents and Settings\Erik\Desktop>notepad calc.py >> > This os.system() starts fresh, with the same settings as the > parent program. > Yes, that is what os.system does. It runs a single command, so it is roughly equivalent in this case to entering: cmd /c cd \windows\system32 cmd /c notepad calc.py at a windows command prompt. i.e. A separate shell is started, and terminated for each command. To get what you want, you must execute the commands in the same shell. Some ways to do this: For a short sequence of commands, just use the command separator as you would normally when entering multiple commands on one line at a command prompt. e.g. os.system(r"cd \windows\system32 && notepad calc.py") For a longer sequence, you can write a temporary batch file then use os.system to execute it. If you need more complex interaction you might want to use the popen2 module to pipe commands in and read the output, but you will almost certainly need to use multiple threads if you try this otherwise your program will deadlock. Or, for this specific case, just use absolute pathnames for everything so you don't have to change current directory before running a command. From chuck.amadi at ntlworld.com Fri May 28 02:43:56 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Fri, 28 May 2004 07:43:56 +0100 Subject: a python script which will parse an email message Message-ID: <40B6DFAC.7020002@ntlworld.com> Thankyou I will banging the keyboards soon as I get into work. From sjf at autograf.pl Wed May 19 07:53:51 2004 From: sjf at autograf.pl (..:: sjf ::..) Date: Wed, 19 May 2004 13:53:51 +0200 Subject: Problems with running EXE build with McMillan Installer Message-ID: Hi all, When I freeze Python script into _ONE_ EXE file with McMillan Installer (ver. 5b5) and then run it says: "MemoryError". Next I freeze it with --debug option and then run again. It says: "MemoryError" "RC: -1 from scriptname" Why I gave these messages and cannot run the script? -- .:: sjf ::.. "Linux is like Wigwam. No gates, no windows... Apache inside ;-)" From paul at boddie.net Mon May 10 10:45:05 2004 From: paul at boddie.net (Paul Boddie) Date: 10 May 2004 07:45:05 -0700 Subject: PEP 328 update References: Message-ID: <23891c90.0405100645.6757654f@posting.google.com> Bernhard Herzog wrote in message news:... > > Still, in my eyes especially the early versions of the pep are an example of > the carelessness with wich some core python developers toss backwards > compatibility out of the window. I'm not against breaking compatibility > when it is a clear gain for the language but it never should be done > lightly and should always result in substantial improvements in the > language that would not be possible otherwise. I don't think that's the > case for this pep, though. I can see the point of resolving ambiguities with imports, especially with common module names, but then I understand your frustrations with the backward compatibility breakage and continuous feature infusion. People go on about how Jython is important to general Python adoption before leaving it in the dust under a thick layer of increasingly difficult-to-justify functionality. People also state how important it is for Python to adapt to new platforms, become faster, have a smaller footprint, scale across multiple processors, and yet all of these goals become steadily harder to reach as more marginal stuff gets added to the mix. I'm sure that various comp.lang.python contributors have scoffed, Slashdot-style, at languages designed by committees, unaware that the newsgroup and the various mailing lists are increasingly doing a good job of emulating such committees quite effectively. Paul From cookedm+news at physics.mcmaster.ca Wed May 12 11:42:24 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 12 May 2004 11:42:24 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> <8fff3ffd3e29a30d3600ff041cf21056@news.teranews.com> Message-ID: At some point, Daniel 'Dang' Griffith wrote: > On 11 May 2004 12:05:52 GMT, Oliver Fromme > wrote: > >>Daniel 'Dang' Griffith wrote: >> > [on sed] One reason >> > to install it is that it's smaller than perl or python; another is >> > that it probably performs the task faster, since it isn't a general >> > purpose state machine; >> >>FWIW, sed _is_ a state machine, although not really "general >>purpose". It is a programming language with variables, loops >>and conditionals, and I believe it is turing-complete. Most >>of the time it is abused to perform simple search-and-replace >>tasks, though. ;-) > > I never used sed for anything but "stream editing", aka search and > replace. Well, if it's turing complete, my apologies to the sed > author(s). :-) > --dang There's a whole bunch of 'extreme' sed scripts at http://sed.sourceforge.net/grabbag/scripts/ I like the dc.sed script there; it's an implementation of the UNIX program 'dc', which is an arbitrary precision RPN calculator: http://sed.sourceforge.net/grabbag/scripts/dc_overview.htm Only for the truly brave. A Turing machine, too: http://sed.sourceforge.net/grabbag/scripts/turing.sed And I notice they have a Python sed debugger: http://sed.sourceforge.net/grabbag/scripts/sd.py.txt -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From Scott.Daniels at Acm.Org Mon May 3 11:55:03 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 03 May 2004 08:55:03 -0700 Subject: PEP 328 update In-Reply-To: References: Message-ID: <40967109$1@nntp0.pdx.net> Aahz wrote: > PEP 328 (``import`` changes) has been updated and is available at > http://www.python.org/peps/pep-0328.html > > Comments on the revised version are welcome. One area where feedback is > particularly desired is on the frequency of relative imports inside > packages in current code, both in absolute terms and as a percentage of > all imports. I am unclear as to why "import ..moduleA as A" is not allowed. The only rationale given for disallowing relative imports like "import .foo" is that .foo is unacceptable as a name. I'd propose a mandatory AS-clause if the MODULE begins with a period. This would allow me to do something like "import . as mypackage" -- a case which is perhaps unnecessary. I just found the "must use the from-style imports" surprising (I agree the change is not vital). -- -Scott David Daniels Scott.Daniels at Acm.Org From nomail at nospam.no Thu May 6 16:48:46 2004 From: nomail at nospam.no (Dominic) Date: Thu, 06 May 2004 22:48:46 +0200 Subject: bdist_wininst strangeness Message-ID: I have written a distutil setup.py and a post installation script for windows, which places a shortcut on the desktop. Everything works perfectly, a minor nuisance is the fact that temporary files are left on the source drive e.g. d:\s3vvlaa9 etc. Usually they are empty, if I print from the post-installation script they also contain this text. So how can I get rid of those temporary files? Thanks, Dominic From nature_boyMYPANTS at mindspring.com Fri May 28 01:26:17 2004 From: nature_boyMYPANTS at mindspring.com (B P) Date: Fri, 28 May 2004 05:26:17 GMT Subject: pdf2txt Message-ID: Is there a way via Python or even Perl to capture records from a pdf and output a delimited text file? My work has a situation with a trunk load of data forms that were scanned as pdfs. The data needs to be taken from the forms and moved into a database, so I figure that comma-delimited format will work fine. The amount of man-hours it would take to manually do this is very cost-prohibitive for what we have to work with. I know that a txt2pdf exists, was checking to see if the opposite would as well. BP From segphault at sbcglobal.net Wed May 12 16:40:32 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 12 May 2004 20:40:32 GMT Subject: things I wish python could do Message-ID: I've spent a lot of time using python, and personally, I feel like it is vastly superior when compared to languages like java, and c++, but there are still a few things that detract from its elegance and flexibility. I thought I might mention a few of them. I'd like to hear what people think of my complaints, and I also like to hear the complaints of others. 1. many keywords (eg:try/except) are strictly imperative, and cannot be used in a functional context. this really should be possible: map(print,mylist) 2. there is no easy way to extend existing classes externally. its possible, but it aint pretty... class Shape: def __init__(self,numSides, perimeter): pass Currently you can do this: Shape.__dict__.update({ 'triangle':ClassMethod( lambda self,sideLength: Shape(3,sideLength*3)) 'square':ClassMethod( lambda self,sideLength: Shape(4,sideLength*4)) }) I want a way to extend a class as easily as I can define it. 3. you cant extend the builtins (string,list,etc), you have to inherit them. Guido says he wont let us because it would create compatability issues, and possibly break the interpreter. Maybe if we had namespace functionality, that wouldnt be an issue? 4. assignments cant be made inside of anonymous functions. I think most python programmers will agree, that python emphasizes simplicity, readability, and uniformity. Ultimately, I dont think that any of those things are important enough to justify the reduction of flexibility, syntactic mutability, and versatility. I was surprised to find that Ruby solves all of my python complaints, while achieving grace and simplicity easily comparable to that of python, and providing a few innovative extras (including real private, public, and protected methods). Despite the fact that I disagree with quite a bit of the philosophy behind prothon, I have enjoyed watching it, because it inspires good dialogue about language development. (as long as those with closed minds keep their mouths closed as well) Are there are any strong reasons why a language shouldn't support the things I list? Is anybody aware of features promised for future python versions that solve or nullify my problems? Are any of my perceived problems really just products of ignorance? From 2002 at weholt.org Sun May 2 04:48:16 2004 From: 2002 at weholt.org (Thomas Weholt) Date: Sun, 2 May 2004 10:48:16 +0200 Subject: Adding and modifying methods at run-time References: <4092c014$1@news.broadpark.no> Message-ID: <4094b6bf$1@news.broadpark.no> That worked great !!! Thanks alot. Thomas "Diez B. Roggisch" wrote in message news:c707s0$q4m$03$1 at news.t-online.com... > Thomas Weholt wrote: > > a = A() > > a.addNewMethod(1, a.obj1) > > # use new dynamically method > > a.method4obj1(1,2) # now the third param with a default is set to point to > > obj1 instead of None > > > > I'm crashing at the copy-method in addNewMethod. It crashes with the > > exception "TypeError: function() takes at least 2 arguments (0 given)". > > This is deep inside the copy-module. > > > > Any hints or clues? > > I have to admit that I'm not fully undestanding what your code above is > supposed to do - but form what I understand you try to introduce a new > method on an object where a certain named parameter is bound to a special > value. > > Now this problem can be split into two parts: > > 1 - create a method that has a paramter bound to a certain value > 2 - add that method to an object instance > > The first thing is known as currying, and there is a cookbook recipe that > does that very well: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 > > You will end up with a new method that can be invoked. Now to make this an > instance method, remove the space between the last two words before the > comma in this sentence and look up the result in the python docs :) > > Seriously, all you need is the function instancemethod from the module new. > Use it to create a new method on your instance. > > The following program illustrates the concepts, the curry-fun is taken from > the recipes comments: > > import new > > def curry(*args, **create_time_kwds): > func = args[0] > create_time_args = args[1:] > def curried_function(*call_time_args, **call_time_kwds): > args = create_time_args + call_time_args > kwds = create_time_kwds.copy() > kwds.update(call_time_kwds) > return func(*args, **kwds) > return curried_function > > > class foo: > def method(_, arg1, named_arg=None): > print (arg1, named_arg) > > f = foo() > > f.method(1) > > new_m = curry(foo.method, named_arg="something") > > new_m(f,2) > > f.new_m = new.instancemethod(new_m, f, foo) > > f.new_m(3) > > > > > -- > Regards, > > Diez B. Roggisch From max at alcyone.com Mon May 24 05:04:45 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 02:04:45 -0700 Subject: iterator expression - please explain References: Message-ID: <40B1BAAD.1F7013EC@alcyone.com> "Delaney, Timothy C (Timothy)" wrote: > Note that Helmut is using 2.4 - that's a valid generator expression in > the function call. Indeed. I'd heard about that a while ago but forgot about it. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Chastity the most unnatural of the sexual perversions. -- Aldous Huxley From jdhunter at ace.bsd.uchicago.edu Fri May 28 12:17:48 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 May 2004 11:17:48 -0500 Subject: Non-programmer needs help with PyGTK-2.0.0 In-Reply-To: (Mark Mitchell's message of "Fri, 28 May 2004 16:16:36 GMT") References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> Message-ID: >>>>> "Mark" == Mark Mitchell writes: Mark> No, I compiled from source. Try installing with 'python setup.py install' rather than configure/make install. From mwh at python.net Tue May 4 11:40:33 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 4 May 2004 15:40:33 GMT Subject: curses and python (linux, debian) References: Message-ID: Guido writes: > Hello > > I'm new to python and i'm trying to write a script that shows a menu. > > Now, I have some troubles with curses.setsyx() > > I do: > > import curses > > curses.setsyx(2, 20) > curses.putp("TEST TITLE") > curses.setsyx(25, 35) > curses.putp("TEST CENTER") > curses.setsyx(12, 35) > curses.putp("TEST CENTER") > > but it just prints all the string after each other at the first > lines.. > > can anybody help me please? Don't you call initscr() first? Cheers, mwh -- ZAPHOD: OK, so ten out of ten for style, but minus several million for good thinking, eh? -- The Hitch-Hikers Guide to the Galaxy, Episode 2 From skip at pobox.com Thu May 13 16:20:25 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 May 2004 15:20:25 -0500 Subject: PEP: import version In-Reply-To: References: Message-ID: <16547.55433.26988.477848@montanaro.dyndns.org> Chris> Basic Goals: Chris> * Multiple versions of wxPython being installed at the same time Presumably in different directories, so setting PYTHONPATH, LD_LIBRARY_PATH, etc will distiguish them for applications. Chris> * Two or more programs, each using a different version could run Chris> at once. This doesn't require a change to the language. This requires a proper setting of PYTHONPATH and/or LD_LIBRARY_PATH, etc. Chris> * Easy for developers - for testing with multiple versions etc That's fine, and precludes the use of something like a hardcoded import wxPython version '2.4' as someone else suggested. In fact, this just cries out for either a WXPYTHON_VERSION environment variable which the wxPython framework could use or for setting PYTHONPATH. Chris> * Easy for users - their apps detect the right version to run Chris> with Getting the right version of dependent packages is an installation issue. This should be detectable from either configure script, Makefile or distutils setup.py script. Chris> * Cross-Platform solution Distribute your apps with .bat file front ends on Windows, shell scripts on Unix. Chris> More detail: Chris> * The ability for the programmer to specify the version used in Chris> the code, ideally only on (or before) the first import of Chris> wxPython I fail to understand why that's a problem that needs to be addressed in the Python program. This is information which is know before the program is run. It belongs in an environment variable or front-end shell/bat script. Chris> * The ability to specify the version wanted with an environment Chris> variable, so that multiple versions could be easily tested This is the correct way to do this. Chris> * The ability to specify multiple versions that all work, in a Chris> ordered list of some sort. Your installation program should detect all installed versions and pick the latest version which intersects with the set of multiple working versions. Chris> * The ability to specify a "minimal" version, and higher versions Chris> could be used. Again, this goes in your setup.py script (or configure, or Makefile, or whatever). It's an install-time decision. Chris> * The ability for "from wx.lib import Something" to work as well, Chris> respecting the version Assuming your installation software worked correctly this should be a no-brainer. ;-) Skip From a at a.invalid Thu May 27 14:10:50 2004 From: a at a.invalid (Timo Virkkala) Date: Thu, 27 May 2004 18:10:50 GMT Subject: why learn In-Reply-To: <40b58695_1@news.iprimus.com.au> References: <40b58695_1@news.iprimus.com.au> Message-ID: mr_vocab wrote: > hey i finished working through alot of python stuff and no a fair bit bout > it > now what can i do with it??? If you're interested in game programming, try making a simple (or complex) game: http://www.pygame.org/ -- WT From peter at engcorp.com Tue May 25 22:17:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 May 2004 22:17:32 -0400 Subject: Cleaner idiom for text processing? In-Reply-To: References: Message-ID: <9bGdnbIYGcOhYy7dRVn-uw@powergate.ca> Michael Ellis wrote: > I have some data files with lines in space-delimited > format. There are multiple name-value pairs per line. > > Is there a cleaner idiom than the following for reading each line into > an associative array for the purpose of accessing values by name? > > for line in infile: > tokens = line.split() > dict = {} > for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1] > do_something_with_values(dict['foo'],dict['bar']) for line in infile: tokens = line.split() d = dict(zip(tokens[::2], tokens[1::2])) do_something_with_values(...) By the way, don't use "dict" as a variable name. It's already a builtin factory function to create dictionaries. -Peter From newsgroups at jhrothjr.com Thu May 13 21:43:18 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 13 May 2004 21:43:18 -0400 Subject: struct doesn't handle NaN values? References: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> Message-ID: <10a8925qmkt5led@news.supernews.com> "Grant Edwards" wrote in message news:40a41bcc$0$8705$a18e6209 at newsreader.visi.com... > In article , Tim Peters wrote: > > > Are there architectures that support multiple floating point > representations that can only be determined at run-time? IBM mainframes. However, I don't believe Python supports them, and in any case, one of them is vanilla IEEE 754. John Roth > -- > Grant Edwards grante Yow! I have a TINY BOWL in > at my HEAD > visi.com From segphault at sbcglobal.net Sat May 8 21:35:29 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sun, 09 May 2004 01:35:29 GMT Subject: What I don't like about wxPython References: Message-ID: On Sat, 08 May 2004 12:40:52 -0700, j_mckitrick wrote: > Just thought I'd play devil's advocate... > > I tried wxPython briefly, and it had some nice features. > > It has a huge list of dependencies. > > I don't like the fonts (but I'd love to know how to get fixed fonts, > or at least anything that looks better on a small laptop screen. > > TkInter seems much easier to use... less effort to do things. > > jonathon TkInter does seem a lot easier to deal with, but it doesnt provide nearly as many widgets as wxPython, and in my experience, it doesnt handle drawing as well. wxPython has a relatively comprehensive control set. My major gripe with wxPython is the speed (lack thereof, actaully). On my pIII 800, using linux, most large wxPython applications are too slow to be usable, whereas comparable pyGTK applications run very smoothly. Seeing as the linux version of wxwindows is gtk based, i'm still not quite sure why there is such a massive speed difference. Ultimately, none of these ui api's are as 'pythonic' as I want them to be, and wxPython in particular seems like a carbon copy of the C api, which makes it lose points in my book. On my system, at least, Wx is too slow for large programs so I would really only use it to make little gui wrappers for convenience scripts, and as I dont usually need a comprehensive widget collection for that, I typically find Tk to be better suited, as there seems to be less overhead. I do use Wx for programmatic drawing when PIL doesnt do quite enough. Wx doesnt have a 'huge list of dependancies' but it is in and of itself an unnecessary bulk. Tk comes with python and has a slightly more pythonic api, so I just use it. in any event, thats my incoherent thought for today. From __peter__ at web.de Tue May 25 03:01:05 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 May 2004 09:01:05 +0200 Subject: Tkinter - One Canvas to Rule Them All? References: Message-ID: Dave Harris wrote: > I derived two Frame classes and created a Canvas in each. I was extremely > surprised when frame1.canvas.delete('all') erased the image in > frame2.canvas! Maybe you are accidentally deleting the last reference to the image (the canvas itself doesn't keep one). Care to show some code? > I deduce from this behavior that there is a single database behind the > scenes for the Canvas implementation. I can't confirm that. Peter From nospam-trice at comcast-nospam.net Wed May 5 00:18:33 2004 From: nospam-trice at comcast-nospam.net (Tim) Date: Wed, 5 May 2004 00:18:33 -0400 Subject: printing float as formatted dollars References: Message-ID: "Peter Hansen" wrote in message news:lsmdnXfkzI1VwwjdRVn-vw at powergate.ca... > Tim wrote: > > > Is there a simple way to output float values as formatted dollar amounts? > > i.e. 127379.42 as $127,379.42 > > The following recent thread would probably give you several ways that > fit the "simple" requirement, provided you are really interested in > writing something that has no internationalization support and ignores > the local conventions. (If you want i18n, use the locale module.) > > http://groups.google.ca/groups?&threadm=e567c03a.0404280035.79d0d973%40posting.google.com > > -Peter Peter, Thanks for the referral to the recent post. I'm only a few months into Python and, to be perfectly honest, I've been shying away from the chapters in my books regarding the re module. This was helpful. Thanks, Tim From peter at engcorp.com Fri May 7 23:46:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 May 2004 23:46:00 -0400 Subject: Python Resources In-Reply-To: <2g2arlF3rvuhU1@uni-berlin.de> References: <109l91isml27qe4@corp.supernews.com> <2g2arlF3rvuhU1@uni-berlin.de> Message-ID: <1eidnbiRwJdlygHdRVn-vg@powergate.ca> Dave Kuhlman wrote: > Peter Hansen wrote: > > [snip] > >>>if you have Python Links in your favourites Post them as well >>> >>>I have been searching google as well To clarify, for the record, I said neither of the above, but merely included them in my reply. Luckily, this time, it doesn't seem to matter much... -Peter From sandysj at juno.com Fri May 7 13:13:58 2004 From: sandysj at juno.com (Jeff Sandys) Date: Fri, 7 May 2004 17:13:58 GMT Subject: VPython and 3D Visualization References: Message-ID: <409BC3D6.ECFE45DF@juno.com> You should join the Python edu-sig and post your findings. http://www.python.org/sigs/edu-sig/ Thanks, Jeff Sandys > "Joel C. Alcarez" wrote: > > I have been using VPython ( http://www.vpython.org) in developing > cross platform 3D visualization tools for Physics Lectures. ... From eurleif at ecritters.biz Tue May 25 15:09:58 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 25 May 2004 19:09:58 GMT Subject: Update with pickle In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > I want to update the content of an object with a dumped object of the > same type so that all reference to existing object are still valid. Add interfaces to your object's class for mutability rather than using a low-level hack. Something like this (untested): class cls(object): __slots__ = ('foo') def __init__(self, foo=None): self.foo = foo def set_foo(self, foo): self.foo = foo foo = cls(42) bar = foo print bar.foo # 42 foo.set_foo(43) print bar.foo # 43 From mwh at python.net Mon May 17 13:57:55 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 17 May 2004 17:57:55 GMT Subject: Warning when testing 2.3.4c1 References: Message-ID: bhoel at web.de (Berthold H?llmann) writes: > Hello, > > Testing 2.3.4c1 I get: > > ... > test_format > /home/devel/compile/Python-2.3.4c1/Lib/test/test_format.py:19: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up > result = formatstr % args > ... > > Is this intended, or should it be solved? Argl. I thought that had been fixed... at any rate, it's not very important. Cheers, mwh -- Have you considered downgrading your arrogance to a reasonable level? -- Erik Naggum, comp.lang.lisp, to yet another C++-using troll From aahz at pythoncraft.com Fri May 7 01:22:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 7 May 2004 01:22:59 -0400 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: In article <997a06e0.0405061128.6768676d at posting.google.com>, wrote: > >What's the standard way to implement polymorphic behavior in a python >method, given that method arguments can't declare their types as >they're being passed in, and method definitions don't have signatures? > >For instance, if I wanted to write a method that auto-detected whether >it was being passed a string or a tuple/list, how would I do so >without using type() to identify the parameter's type? Using type() is >deprecated in the documentation I've read. Generally speaking, in Python you simply create two different callables. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From marco.terzuoli at libero.it Tue May 18 15:03:50 2004 From: marco.terzuoli at libero.it (Marco Terzuoli) Date: Tue, 18 May 2004 19:03:50 GMT Subject: Tree control with TKinter Message-ID: Hi, I would like to implement a tree control inside a Python application. It should be similar to GTK's TreeStore widget, but I need it for TKinter. Any ideas? thanks Marco From catcher at linuxmail.org Sat May 22 17:52:38 2004 From: catcher at linuxmail.org (Robert) Date: Sat, 22 May 2004 17:52:38 -0400 Subject: SciTE editor question References: Message-ID: "Brent W. Hughes" wrote in message news:sxPrc.97519$xw3.5665588 at attbi_s04... > I want to increase the number of files I can have open in the SciTE editor. > The SciTEDoc.html document says to change the number of buffers in a file > called SciTE.properties, but it doesn't say specifically how to specify > this. So I tried putting this in the properties file: > > buffers=5 > > It didn't work. Maybe I need to qualify it in some way, like sys.buffers=5. > Does anyone know about this? > > Brent > > P.S. If I'm in the wrong newsgroup for this question, please tell me which > NG to use. > What I have in my SciTEGlobal.properties file: tabbar.visible=1 tabbar.hide.one=1 tabbar.multiline=1 buffers=30 From peter.maas at mplusr.de Tue May 4 09:37:46 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 04 May 2004 15:37:46 +0200 Subject: Experience with vb2py? In-Reply-To: <_Azlc.44378$r37.39639@newssvr29.news.prodigy.com> References: <_Azlc.44378$r37.39639@newssvr29.news.prodigy.com> Message-ID: asdf sdf wrote: > vb2py sounds terric but i don't want to be the first guineau pig who > gambles his project on it. > > i have a large VB project lying around that may have to be upgraded. i > would love to see it go to python. It's reasonable to ask for opinions but if you want to use it for a large project you should experiment with it anyway. Create a little hello world dialog and try to convert it. Populate it with more complicated controls, add database and network connections and try to convert it again. My bet is that vb2py won't do *all* of the work for you. I once tried to convert a medium sized project (25 kloc) from vb6 to vb.net and the migration assistant supplied by MS aborted after a 3 hours run. Python and VB are much more different so I assume that vb2py saves the low level typing work like converting loops, ifs and defs which is very valuable but the high level conversions that require to understand the code will probably be up to you. Please don't forget to report your results in c.l.py because i don't want to be the first guinea pig who gambles his project on it. :) Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From newsgroups at jhrothjr.com Wed May 5 13:31:43 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 May 2004 13:31:43 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: <109i99sefeba59f@news.supernews.com> "Marcel Molina Jr." wrote in message news:mailman.274.1083773846.25742.python-list at python.org... > On Tue, May 04, 2004 at 04:54:30PM -0700, Stephen Ferg wrote: > > I've been wondering how we can improve the quality of the Python > > documentation. > what really makes sense for me with php's documentation is how very > intuitive (and therefore easy and fast) it is to get to what one is > looking for. this is particularly true of its online documentation of > its built in functions. this ease of access is leveraged through their > website's way of dealing with 404 requests. > > if you go to php.net/ you are automatically redirected > to the page that documents that function. > > this is often more efficient than the three step process of going to > the page, doing a search, clicking on the appropriate search result. it > is often faster than have a bookmark to a page that lists all functions > and then scrolling or even Ctrl-Fing your way to the appropriate one. [snip] > online documentation shouldn't be one's only recourse though, and > this is a place where python has a major leg up on php. one aspect to > python's documentation that i really appreciate is having the help() > function interface to pydoc now in the interpreter. whether it be ruby's > 'ri', perl's 'perldoc' or python's 'pydoc', command line interfaces to > documentation are very helpful, both as a learning tool and a reference, > especially when they can be accessed from within an editor such as with > vi's Shift-K macro. php has no such interface. I kind of like this notion. There are a lot of times I'm going for a module that I know is there, but I'm not sure of either the name or the location in the TOC. (And the trick of cleverly hiding the module index at the back of the Library Reference instead of leaving it as a separate document got me confused for a while, but that may be a WinHelp issue.) > pydoc from the interpreter through 'help()' often gets me to where i want > to go in one step, so no complaints there. it would be nice, though, > if there was the same kind of web site functionality at python.org > as there is at php.net (though i am not familiar with all the ways to > access documentation for either and there may be many means of getting > documentation that address my need that i am just not aware of). I vaguely remember that there were ways of rigging WinHelp so that it would do something similar, at least if you asked nicely. The difficulty is probably getting the doc process to produce the right incantations. John Roth > > thanks, > marcel > -- > Marcel Molina Jr. > From http Tue May 11 18:38:26 2004 From: http (Paul Rubin) Date: 11 May 2004 15:38:26 -0700 Subject: scraping display to obtain all on-screen text using OCR References: <27e4d2e8.0405111130.7081968e@posting.google.com> Message-ID: <7xy8nyoahp.fsf@ruckus.brouhaha.com> jaepstein_63 at yahoo.com (Jonathan Epstein) writes: > I would like to perform a more classical type of "screen scraping" > than what most people now associate with this term. I only want to > find all the text on the current screen, and obtain associated screen > coordinates. This probably must be done using OCR. > This need only run on Windows. Usually you do that by intercepting the Windows text painting events, rather than anything as horrendous as OCR'ing. From nicksjacobson at yahoo.com Tue May 4 09:05:04 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 4 May 2004 06:05:04 -0700 Subject: pychecker proposal References: Message-ID: "Roger Binns" wrote in message news:... > Nick Jacobson wrote: > > I think that PyChecker should be part of the "batteries included" > > library that comes with Python. It can be a very useful tool for > > catching errors and bad style. > > > > If it were in the standard library, newbies would be aware of it > > sooner. > > I would prefer a "lint" mode to the Python interpretter that runs > in a full warnings mode, using both static analysis that pychecker > does as well as any dynamic analysis that could be done. I > don't even care if it runs at half the speed of normal Python. > > Roger Yes! I completely agree. Perl has its "use strict" and "use warnings". Admittedly, Perl *needs* them more, but I think Python could use something like this too. Not everyone would have to use it, but IMO having the option to catch certain bugs (or style mistakes) before run-time would be beneficial. From jonrose at farious.com Thu May 20 00:36:45 2004 From: jonrose at farious.com (Jonathan M. Rose) Date: Thu, 20 May 2004 00:36:45 -0400 Subject: News Posting Script with Emailing Ability Message-ID: <40ac36d4$1_1@nntp2.nac.net> I am looking for a script that I can sit on an HTML server (Linux, Apache, PHP/Perl/Python/Etc.) that will allow me to do the following things: 1) Post news articles that consists of (i) a title and (ii) a body. 2) Show the last X posts (or, better yet, just the last X titles) on a home page. 3) Show all posts on a "news" page. 4) When a news article is posted, email the news article (with the title being the email subject and the news body being the email body) to a single address (which will be a Mailman email list address). 5) Preferably not require the use of a db server. 6) Preferably allow changing or deleting news posts if errors were made in the wording or otherwise. 7) I do not need nor want the ability for users to "reply" to the news articles. Does anyone know of anything like this? If not, how about simple news posting tools that I could remake to include the emailing functionality? A tool similar to what I want is located at http://newswriter2005.sourceforge.net/. This one, however, doesn't allow email of news articles. Also - what is the proper newsgroup for asking about server-side html scripts? alt.html.server-side would be perfect, but it seems to be dead (at least on the news server I use). Thank you for your time in advance. -Jon -- Jonathan M. Rose President, Farious Net Solutions Phone: (866)NET-SOLN; Web: http://www.farious.com Computer sales and service, Linux deployment and maintenance, low voltage wiring and Java/database Programming for the northern New Jersey/New York City area. Call us today! From rjt-usenet at thegrindstone.me.uk Thu May 6 12:18:26 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Thu, 06 May 2004 17:18:26 +0100 Subject: rectangle layout algorithm? References: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <409a6553$0$31698$fa0fcedb@lovejoy.zen.co.uk> Terry Reedy wrote: > > > Among other things, the algorithm you want depends on the following: > Are the rectangles all the same size or different sizes? They are photographs, so they are generally all the same size. > Do you want to pack as tightly as possible or spread out over a > background? I want to fit as many on a specified sheet of paper as possible. I would like to be able to specify the paper size at run time e.g. A4, A3 etc. > Are the images ordered or may they be placed randomly? They can be placed randomly. They can also be rotated in order cover more of the page as they will be cut into separate pictures once printed. > What is your criterion for a good versus poor layout? Maximum use of paper is the criteria. Photo paper is expensive :-) Regards Richard From greg at cosc.canterbury.ac.nz Sun May 2 21:42:54 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 03 May 2004 13:42:54 +1200 Subject: Simple prototyping in Python In-Reply-To: References: <69cbbef2.0404300855.20dd436b@posting.google.com> <1095h4vc89hmcf@corp.supernews.com> Message-ID: Dave Benjamin wrote: > Hey, I never knew that "this" could be used inside of an anonymous object > in JavaScript. Thanks for pointing that out! > > In Python, you'd have to give the object a name, since there's no "self" to > refer to. No, you wouldn't, because the Python equivalent would be something like def F(): c = [105] class C: a = 5 def incr(self): self.a += 1 c[0] += 1 return [self.a, c[0]] return C() It's a bit more awkward in Python due to the inability to directly rebind a name in an outer scope. BTW, IMO this is a seriously warped technique that I would never use, even in Javascript. I can't see any benefit in it that's anywhere near worth the obfuscation. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tim.one at comcast.net Mon May 17 15:28:02 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 17 May 2004 15:28:02 -0400 Subject: This program makes Python segfault - no other does In-Reply-To: Message-ID: [Juho Saarikko] > The function unQuoteBytea allocates memory with PyMem_Malloc, and frees it > with PyMem_Free. The segfault happens at freeing the memory (as the > backtrace shows). It seems to me that if Python's memory management > routines fail to free an object they've allocated, it must be a bug in > Python. That or some other bug corrupts memory structures, Bingo. > in which case it's almost impossible to track down. At this point > I'm considering either switching to a different database plugin, or > to Java. > > I tried the new Python version (3.3.4c1) and got the exact same behaviour. > Aarrgghh. > > Here, I'll attach the unQuoteBytea function, it's a short one. Maybe you > can find some problem in it I couldn't: Yes. > PyObject *unQuoteBytea(char *sin) > { > int i, j, slen, byte; > char *sout; > PyObject *result; > > slen = strlen(sin); > sout = (char *)PyMem_Malloc(slen); You're in trouble already here. strlen(sin) does not count the trailing NUL byte, so you haven't allocated enough memory for sout to hold a NUL-terminated copy of sin. There may or may not be other C bugs here, but for starters change the last line to > sout = (char *)PyMem_Malloc(slen + 1); BTW, running under a debug-build Python would have told you that the program wrote beyond the bounds of the memory allocated for sout. From akaiser at vocote.de Thu May 13 13:52:00 2004 From: akaiser at vocote.de (Andreas Kaiser) Date: Thu, 13 May 2004 19:52:00 +0200 Subject: ANN: Dabo 3-tier desktop framework for data-aware apps ERROR In-Reply-To: <200405120653.00578.p@ulmcnett.com> References: <200405120653.00578.p@ulmcnett.com> Message-ID: Hi, If I try to run a demo, I get following errors: >c:\python\pythonw "SimpleFormWithControls.py" Traceback (most recent call last): File "SimpleFormWithControls.py", line 82, in ? form = MyForm(None) File "SimpleFormWithControls.py", line 26, in __init__ self.instantiateControls() File "SimpleFormWithControls.py", line 41, in instantiateControls for obj in ((dTextBox(panel), "txtCounty", "County"), File "c:\python\lib\site-packages\dabo\ui\uiwx\classes\dTextBox.py", line 15, in __init__ self.PostCreate(pre) File "c:\python\lib\site-packages\dabo\ui\uiwx\classes\dPemMixin.py", line 21, in __getattr__ raise AttributeError, "%s object has no attribute %s" % ( AttributeError: ? object has no attribute PostCreate 19:43:55: Debug: e:\Projects\wx2.4\src\msw\app.cpp(439): 'UnregisterClass(canvas)' failed with error 0x00000584 (this class has open windows.). >Exit code: 1 What's wrong? Python 2.3.3 WinXP Home SP1 wxWindows 2.4.2.4u Andreas From list-python at ccraig.org Fri May 21 08:31:04 2004 From: list-python at ccraig.org (Christopher A. Craig) Date: 21 May 2004 08:31:04 -0400 Subject: MailMan integrated with JSP/Servlet integration References: <1ed550fd.0405150539.3adffc13@posting.google.com> <1ed550fd.0405160226.5a088220@posting.google.com> <1ed550fd.0405181350.6c5c880b@posting.google.com> Message-ID: michela_rossi66 at hotmail.com (michela rossi) writes: > Sounds good - except cookies not allowed. I don't see how you're going to use mailman at all then. The stock version of mailman is very cookie dependent and I don't know of any patch that changes that. -- Christopher A. Craig Though He slay me, I will hope in Him. -- Job 13:15 From jfabiani at yolo.com Sat May 1 19:52:05 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat, 01 May 2004 23:52:05 GMT Subject: web start References: Message-ID: Nuff Said wrote: > On Fri, 30 Apr 2004 18:49:57 +0000, John Fabiani wrote: > >> In the Java world they have a way to start and update programs using web >> start. Is there something like web start for Python? > > If you feel comfortable in the Java world (?), then you might > consider to use Jython. (Google for *Jython "web start"* and > you will find some information this approach.) > > HTH, Nuff. Not really. But I like python. I'm just looking for a way to deploy my apps (including updates) without the user going thru all the normal garbage. -- John Fabiani From heikowu at ceosg.de Sat May 1 17:41:17 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 1 May 2004 23:41:17 +0200 Subject: Save up to 70% on programs, Python. In-Reply-To: <011001c42f53$4f541cd6$0870e83f@no-wucking-furries-mate.com> References: <011001c42f53$4f541cd6$0870e83f@no-wucking-furries-mate.com> Message-ID: <200405012341.18687.heikowu@ceosg.de> Am Samstag, 1. Mai 2004 10:07 schrieb Enrichment A. Cozy: > Well well well! > Everything you see I owe to spaghetti. > > [snip] > > Happiness does not lie in happiness, but in the achievement of it. > Better to ask twice than to lose your way once. > No wife can endure a gambling husband unless he is a steady winner. Wow, now this really makes me want to buy software from them, esp. the last sentence... Would be interesting to see whether these sentences are different in the same ad posted to another mailbox... Heiko. From buzzard at urubu.freeserve.co.uk Wed May 19 12:25:51 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 19 May 2004 17:25:51 +0100 Subject: PERT for python References: Message-ID: "Juan Antonio Dom?nguez P?rez" wrote in message news:c8fqsl$141$1 at news.ya.com... > Duncan Smith wrote: > > > "Juan Antonio Dom?nguez P?rez" wrote in message > > news:c8fhi7$qp1$1 at news.ya.com... > > > >>Can anoyone let me know if there is a standar PERT algorithm > >>implementation in python? > >> > >>Thanks in advance. > >> > >>-------------------------- > >> > >>Juan Antonio Dom?nguez P?rez > >>http://www.dominpe.com > > > > > > > > Not as far as I know, but I will be coding one up shortly. I'll write one > > (probably today / tomorrow) if you promise to give me some feedback :-). > > > > Of course. I need the algorithm to make an offline process, so isolate > the PERT code from your application. I only need to date the tasks, and > resolve the conflicts by a set of simple rules. > > Well, I'll wait for your code. And, of course, thanks in advance :D > > > Duncan > > OK. What I have in mind is fairly simple, and shouldn't take long; a precedence diagram class and a node/activity class (is this where you tell me PERT stands for something other than what I think it does :-)?). I suppose it could develop into something a bit more interesting (Monte Carlo, not restricted to Beta distributions). I guess by "conflicts" you're referring to what I would call precedences? BTW my e-mail address is genuine, but I'll reply via my 'non-throwaway' address if you e-mail me. Duncan From peter at engcorp.com Mon May 3 08:43:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 08:43:35 -0400 Subject: Path ... where is my application's home dir? In-Reply-To: References: Message-ID: JanC wrote: > "Roger Binns" schreef: >>You can compare with Google where you can see their worldwide figures >>for March: http://www.google.com/press/zeitgeist.html >>They have 22% for Windows 98, which seems to take proportionally >>from the figures in my stats. > > At least, they are pretty close to my guess... :-) > >>Of course we don't know what percentage of people configure their >>browsers to lie. > > And: > - what percentage of people have a PC and no internet access... > - what percentage have a PC & internet at work but aren't allowed to use it > for visiting your site (or other non-work-related sites). > - etc. And, finally, what percentage of any of these subsets are likely customers for Jorge, Yermat, you or me? ;-) (It likely includes very few of those with a PC but no internet access and, I would propose, it also includes only a small subset of those still stuck with Win98.) -Peter From peter at engcorp.com Thu May 20 10:27:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 10:27:04 -0400 Subject: query regarding python script In-Reply-To: References: Message-ID: Shubhra Gupta wrote: >>I have the following statement in one my python script :- >> >>assert not opt_initialize or os.path.exists(initdir), "initialize implies init directory" >> >>Could u tell please what it is intended to do? Nobody but the author could say what it was *intended* to do. What it is actually doing, however, is terminating the program if the opt_initialize flag is False or, in the case where it's True, if there is a directory or file (!) with the path in 'initdir'. If it does terminate the script, it will also show the string that follows. The lines shown will also not execute at all if the script is run with the -O or -OO options. Looks like it was not entirely well thought out... -Peter From davecook at nowhere.net Thu May 20 09:49:21 2004 From: davecook at nowhere.net (David M. Cook) Date: Thu, 20 May 2004 13:49:21 GMT Subject: GTK or TKinter (or what else?) References: Message-ID: In article , Marco Terzuoli wrote: > I use python under linux and would like to create some GUI applications. I > have seen that Python can be used together woth some different graphic > libraries and would like to have a suggestion about which one to use. > I feel like GTK is better documented bud would not like to create programs > which are not fully portable. Moreover, I know you can use wxWindows as > well... I have tried it in my C program and didn't like the way events were > handled. Are there any differences in Python? While not absolutely ideal for win32 because of look-and-feel issues, Gtk does run well under win32. There's even a win32 theme, so it just comes down to feel in a few places. Maybe someone else can speak to the Mac situation. Dave Cook From shalabh at cafepy.com Sun May 30 11:38:57 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 30 May 2004 08:38:57 -0700 Subject: 2d lists In-Reply-To: <337e6cd5.0405291411.4376debc@posting.google.com> References: <337e6cd5.0405291411.4376debc@posting.google.com> Message-ID: SunX wrote: > What is the best way to assign a 2d lists? Something like; > > for i in range(10): > for j in range(10): > aList[i][j] = i*j > > Thank you in advance. If you want a list of lists, you could do: for i in range(10): L = aList[i] = [] for j in range(10): L[j] = i*j A completely different option is to use a dict for 2d data: d = {} for i in range(10): for j in range(10): d[(i,j)] = i*j Notice the index is a tuple. -- Shalabh From peter at engcorp.com Tue May 4 07:26:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 May 2004 07:26:25 -0400 Subject: Kill a thread in Python In-Reply-To: References: Message-ID: C. Barnes wrote: > This code module allows you to kill threads. The > class KThread is a drop-in replacement for > threading.Thread. It adds the kill() method, which > should stop most threads in their tracks. > def __run(self): > """Hacked run function, which installs the > trace.""" > sys.settrace(self.globaltrace) > self.__run_backup() > self.run = self.__run_backup Although I'm usually against premature optimization, in this case I have to point out the potentially *very* significant impact of using the system tracing capability... Also, this sort of "kill" is easily implemented on a special case basis in real code, where you generally just want to check at a high level whether the thread has been requested to die. Doing it at each bytecode seems like overkill, unless you tend to write lots of potentially endless loops at lower levels. Having a thread stuck in external code is by far the most common use case for this, I think, which this won't handle. It's a nice example of a use of sys.settrace, however... -Peter From ville at spammers.com Tue May 25 09:53:29 2004 From: ville at spammers.com (Ville Vainio) Date: 25 May 2004 16:53:29 +0300 Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> <9ace45f.0405250518.2803e7b0@posting.google.com> Message-ID: >>>>> "Andrei" == Andrei Smirnov writes: >> Andrei Smirnov wrote: >> >> > i do really suffer. i have to use Perl and i know that i have >> > no chance to convince my new boss (very smart guy) to switch >> > to Python because of braces. >> >> Clearly your new boss is *not* very smart, or is insane. Andrei> there are many smart people who are not familiar with any Andrei> aspect of this discussion (and other way around). so, Andrei> don't make judgement based on preferences. He's probably not stupid, just prejudiced. Many people in tech are. You just need persistence in convincing, and you may need to demonstrate how productive/readable Python is. Never give up - even the most stubborn will see that Python absolutely kills Perl, given enough exposure. Just write something and show him the code. Make it brief and elegant. The indentation issue will fall by the wayside. Andrei> well, there is such thing as initial impression. and Andrei> python initial impression for (smart or stupid) guy who Andrei> was using C for years is like swap brake and gas pedal in Andrei> the car. why should anybody do this? the real fact is that Andrei> C-look is everywhere and it is affecting decision-making Andrei> process in this way. It might very well be affecting the decision making process, but so should you. It's not necessary to sit silently while other people make the decisions - programmers should complain loudly when the decisions made are stupid, especially if they concern them. Andrei> not very hard to convince your friend to do it. but things Andrei> are very different in any industry and when you Andrei> interacting with your boss. The boss is a person like anyone else, with a pair of ears and at least half a brain. -- Ville Vainio http://tinyurl.com/2prnb From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun May 9 12:22:03 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 9 May 2004 18:22:03 +0200 Subject: Python for Nokia Series 60 References: Message-ID: Re-Hi ! I have found : http://xenian.net/~enki/ and http://feetup.org/blog/dev/python/symbianPython.html @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From davidf at sjsoft.com Tue May 18 10:13:40 2004 From: davidf at sjsoft.com (David Fraser) Date: Tue, 18 May 2004 16:13:40 +0200 Subject: pyVideoIO source release In-Reply-To: <2gugfoF6p9rhU1@uni-berlin.de> References: <2gugfoF6p9rhU1@uni-berlin.de> Message-ID: Riccardo wrote: > Hello, after a long time I'm releasing my extension to read AVI files, > QuickTime and connect to WebCameras under win32. > I do not have much time to create a decent website by now, therefore I > released the sources and a binary for python 2.3 just to be prompted to > do more. > If somebody will find this useful I'll add any contribution I receive. > > the URL is: > > www.geocities.com/rtrocca/python > > Well, sorry for the lack of more information, > I'll add docs and other stuff in the future. > > > Riccardo > Cool! Looking forward to the docs... David From htx1 at gmx.de Fri May 14 10:10:00 2004 From: htx1 at gmx.de (=?ISO-8859-2?Q?Holger_T=FCrk?=) Date: Fri, 14 May 2004 16:10:00 +0200 Subject: Loop and the list In-Reply-To: References: Message-ID: Krzysztof Szynter wrote: > def maxvalue(TY): #gets an index of the max value in the TY list > max = 0 > for i in range(0,len(TY)): > if (max max = i > print TY[i],max > continue > return max max is an index, right? So your test should be if TY[max] < TY[i]: [....] In your code, you compare the index to a value. Greetings, Holger From jack at performancedrivers.com Thu May 13 13:17:31 2004 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 13 May 2004 13:17:31 -0400 Subject: make faster Richards benchmark In-Reply-To: <6748553f.0405130815.4a69cc84@posting.google.com> References: <6748553f.0405122211.5be5a150@posting.google.com> <6748553f.0405130815.4a69cc84@posting.google.com> Message-ID: <20040513171731.GG445@performancedrivers.com> On Thu, May 13, 2004 at 09:15:58AM -0700, Duncan Lissett wrote: > Duncan Booth wrote in message news:... > > Remove the pointless set/get methods and just access the members directly. > > If you are writing a benchmark they will cripple performance. > > > > Avoiding multiple accesses to the same instance variable, or assigning to > > instance variables until you are about to return from a method: use a local > > during the execution of the method. > > The pointless set/get methods are pointless in the other language > implementations as well - that's the point. (And I'll cripple that > Oberon-2 implementation real soon by enforcing privacy with modules > and set/get procedures.) I would leave python and some other languages out of the comparison. You can do near line-for-line translations for languages in the same class - say C++ and Java, or Assembly and C. Requiring the python/perl/ruby versions to look like a C++ program just measures how badly C++ maps to Python, and not much else. I've even seen some line-for-line translations in production use that use python list-of-strings where the orignal version used char arrarys. You can imagine what that does for performance *shudder*. Writing benchmarks is just hard, if you allow people to solve the problem in whatever way they like you end up measuring how good a coder the language A guy is compared to the language B submitter. -jackdied From nelson at monkey.org Wed May 19 12:55:40 2004 From: nelson at monkey.org (Nelson Minar) Date: Wed, 19 May 2004 16:55:40 GMT Subject: unique number generator References: <5da2b26991d290ff30a502d392812f4b@news.teranews.com> Message-ID: "Joe Wong" writes: > There is a constraint that the number can be at most 8 digits, ie: > 00000000 ~ 99999999 What an odd constraint. Is this your homework? Your best bet is to issue increasing serial numbers from a process that's properly mulithreaded and persistent. If you're really lazy, install MySQL and have it generate unique IDs for you. From tjreedy at udel.edu Thu May 6 09:59:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 May 2004 09:59:45 -0400 Subject: rectangle layout algorithm? References: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> Message-ID: "Richard Taylor" wrote in message news:409a0c8d$0$31702$fa0fcedb at lovejoy.zen.co.uk... > Hi > > I need an algorithm to layout a collection of rectangles (images) within a > bounding rectangle (sheet of paper). > ... > (Actually building the composite image is not a problem, I am going to use > PIL to do that. It is knowing where to place the images that I need to > solve.) Among other things, the algorithm you want depends on the following: Are the rectangles all the same size or different sizes? Do you want to pack as tightly as possible or spread out over a background? Are the images ordered or may they be placed randomly? What is your criterion for a good versus poor layout? Terry J. Reedy From brian at sweetapp.com Thu May 6 04:49:16 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 06 May 2004 10:49:16 +0200 Subject: VIM and tab to space migration In-Reply-To: References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <40992866$0$12738$636a15ce@news.free.fr> Message-ID: <4099FC0C.3090407@sweetapp.com> > I use these settings myself, but just now after posting, I realized that > it is far better to set the preferences on a per-buffer basis, so I > change my advice to the following: [snipped] > And this is *really* all there is to it. I don't know what this is supposed to do, but it doesn't seem to do what I want. Here is the test I performed: 1. create a new file using tab indentation 2. open it in VIM 3. hit the tab key VIM inserts 4 spaces for the tab so I now have a file containing mixed tabs and spaces. Ideally, I would like VIM to be smart enough (like every other programmer's editor in the universe) to detect the current tab settings in the file and use those. Cheers, Brian From mcbrides9 at comcast.net Mon May 3 21:58:50 2004 From: mcbrides9 at comcast.net (Jerry McBride) Date: Mon, 03 May 2004 21:58:50 -0400 Subject: Is there a Python library that packs binary data into one file? References: <85b54e91.0404261301.69d5c1e9@posting.google.com> Message-ID: Larry Bates wrote: > zipfile.py works pretty well and you get compression > as well. > If you're after better compression there's also bzip2... -- ****************************************************************************** Registered Linux User Number 185956 http://groups.google.com/groups?hl=en&safe=off&group=linux Join me in chat at #linux-users on irc.freenode.net Buy an Xbox for $149.00, run linux on it and Microsoft loses $150.00! 9:22pm up 14 days, 43 min, 5 users, load average: 3.05, 3.06, 2.99 From Mike at DeleteThis.Geary.com Mon May 24 22:05:23 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 24 May 2004 19:05:23 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> <22b7fd40.0405240325.7b2b6376@posting.google.com> <10b4bgsimk120ce@corp.supernews.com> <22b7fd40.0405241622.2bbe748c@posting.google.com> Message-ID: <10b5af3r0ke5473@corp.supernews.com> Ralph A. Gable wrote: > Thanks ever so much. That worked and helps tremendously. Great, glad to hear it, Ralph. Internet Explorer's object model is really easy to work with once you know how to get to it, and Python interfaces to it very nicely. I've been pleased with how well it works out in projects I've done with it. -Mike From apardon at forel.vub.ac.be Thu May 13 10:32:45 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 14:32:45 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: Op 2004-05-13, Andrew Bennetts schreef : > On Thu, May 13, 2004 at 11:26:28AM +0000, Antoon Pardon wrote: >> Op 2004-05-13, Andrew Bennetts schreef : >> > Augmented assignments are still assignments, and that makes perfect sense to >> > me -- each of those behave exactly like their obvious longer versions: >> > >> > s = 'abc' >> > s = s + 'd' >> > >> > i = 7 >> > i = i + 3 >> > >> > l = [1, 2, 3] >> > l = l + [4, 5, 6] >> > >> > (Yes, there are tricky examples that do behave differently -- but I try to >> > avoid tricky things, because they tend to be hard to read. I almost only >> > find I want to use augmented assignment on integers and occasionally >> > strings.) >> >> But these things are only hard to read (to you, I don't find it so) because >> you are using constants in the expression. > > I didn't say those examples are hard to read. Personally, I find both > forms equally readable. > > I did say that there are cases where: > > += x > > does not behave the same way as: > > = + x > > But you need relatively tricky lvalues for this to be the case. > >> a += b, is just as hard to read whether a and b are lists or integers. >> >> The problem is that because the behaviour with strings and lists is >> different I can't write a program in which the behaviour of += is >> consistent for all classes because there will always be core classes >> for which the behaviour will be different. > > It seems to be that your problem isn't really with "+=" as such, it's that > Python has immutable types at all, including in the commonly used builtins. > Immutability of strings, numbers and tuples has worked very well for Python > so far, so you'll have a struggle convincing many people that it should be > otherwise. Well I didn't have this problem when I first encounterd python. It had no "+=" operators then. But with the introduction of these and the inconsistencies it introduces I have began to think differently. You are probably right that people will be hard to convince to change this, so I wont try. I'll just use the language that suits me best for a particular task and often enough it will be python, with the warts I think it has. > > Personally, I like that when I do: > > x = 7 > func(x) > > That I know that x will still be 7 after func returns, regardless of what > happens inside func. It's just not possible for func to accidentally change > the value of x in my scope, because I know that numbers are immutable in > Python. Well personally I like it to be that way for any object, unless func has somehow announced that it can change the argument. I think a copy in parameter is a far better way to assure you of that, because it indeed works for any object, or maybe a seperate attribute that allows any object to be mutable or immutable depending on the needs of the moment. > It would take some *massive* benefits to convince me to change my mind. > >> It is a bit like having some classes use "+" for substraction. In it self >> that wouldn't be so bad, you just have to pay attention. But then >> you want to write a class that will work with whatever number type >> and it needs to do additions. Now suddenly things get difficult because >> a + b doesn't behave consistently among the different number types. > > Again, if the objects you're using don't "make sense", you're stuck with a > difficult life. If a library's API is hard to use, then chances are the > library won't get used much. Well that is my point, "+=" operators don't make sense for immutable types. >> You have the same kind of difficulty now if you want to write a >> class/function/module that works with any kind of sequence. >> >> Using the "+=" operator you can't guarantee any kind of consistency. >> If I had code like this: >> >> a = b >> b += c >> >> I would have no idea at all whether a was changed or not. So >> writing code that can work with any sequence becomes a possible >> problem spot if you use these kind of operators. > > Then take a copy of the sequence first, using list(seq) or tuple(seq), and > then you'll know exactly what you have. I consider that a work around. > Or even simpler -- use: "b = b + c" > instead. Then you know that a is unmodified. Right. In order to write reliable code in a function, class or module that can work with any sequence I better not write "b += c" but write "b = b + c" because only the latter guarantees a particual result. So how good are those "+=" operators if you can't use them in generic code. I don't find it convincing that it is convenient to be able to write "a += b" if you then learn that in generic code you better write "a = a + b" anyway. > If you don't know what kind of objects your functions are working with, how > can you expect them to behave correctly? I know what kind of objects: sequences. It is not my fault the operators on sequence are not consistent. > If your API assumes that a > particular method receives a tuple, then either make sure it does by calling > tuple(x), or document that it does in the docstring. > > Otherwise, a user of your library code might legitimately try to pass a > list, a dictionary, None, or perhaps their own custom type, unaware of your > hidden assumptions. But I want my code to work with any sequence type, the problem is that the core library doesn't provide a consistent behaviour for all its sequence types. That is not my fault. > In my experience, I've never had the issue of mutable vs. immutable sequence > types cause the sort of problems you're worried about. Perhaps I'm lucky, > or subconciously careful, or it has happened and I'm just plain forgetful :) > ... Regardless, I'm not going to start worrying about it now. Python is > working just fine for me despite this. Well that doesn't surprise me much, since the += operators are relatively new and it is the introduction of those that can cause such problems. Yes there are workaround such as taking a copy with tuple or list, Just as you can embed a variable in an object if you want to change something on an intermediate scope. I consider the needs of such workarounds as signs that the language would better be changed in these parts. It is not that big a deal that it will have a big influence on the language I'll use, but I still think of these kind of things as warts. -- Antoon Pardon From theller at python.net Wed May 26 13:35:20 2004 From: theller at python.net (Thomas Heller) Date: Wed, 26 May 2004 19:35:20 +0200 Subject: creating .exe file References: <3f0686ff.0405260841.6deba711@posting.google.com> <9rOdnWFMhMvqUCndRVn-tA@powergate.ca> Message-ID: <1xl76qhz.fsf@python.net> Peter Hansen writes: > Peter Maas wrote: > >> Q X wrote: >>> I am wondering what kind of tools are available to wrap python scripts >>> into just 1 .exe file (with no other files) in windows. I also want >>> the .exe file to be able to use command line arguments ie. >>> pythonprogram.exe -classpath d:/temp -file c:/hi.text >> http://sourceforge.net/projects/py2exe > > He explicitly asked for "just one .exe file (with no other files)", > but py2exe cannot do that. Gordon McMillan's installer can do this. If you manage to find a copy to download. Or Tools/freeze. Thomas From jhefferon at smcvt.edu Sat May 22 09:21:15 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 22 May 2004 06:21:15 -0700 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> <545cb8c2.0405201645.16ac3364@posting.google.com> Message-ID: <545cb8c2.0405220521.ac117a4@posting.google.com> Peter Otten <__peter__ at web.de> wrote: > Of course it would fail with non-ascii characters in the string that shall > be converted. Why not allow strings with all 256 chars? Again, as stated in > my above post, that would be ambiguous: > Thanks, Peter and others, you have been enlightening. I understand you to say that Python insists that I explicitly decide the decoding, and not just smoosh the strings. Thanks. I will write to the documentation person with the suggestion that the documentation of .join(seq) at http://docs.python.org/lib/string-methods.html#l2h-188 might be updated from: "Return a string which is the concatenation of the strings in the sequence seq." > >> Use either unicode or str, but don't mix them. That should keep you out > >> of trouble. > > Or make all conversions explicit with the str.decode()/unicode.encode() > methods. Now I only have to figure out whic codec's are available and appropriate. Thanks again, Jim From me at privacy.net Sat May 29 12:31:38 2004 From: me at privacy.net (Duncan Booth) Date: 29 May 2004 16:31:38 GMT Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> Message-ID: David MacQuigg wrote in news:o1veb09o0vgiaf9b7cs4umu79jf977s5qa at 4ax.com: > I haven't added any classmethod examples to my OOP chapter, because > until now I've thought of them as very specialized. I'm searching for > a good textbook example, but all I can find is trivially replacable > with an instance method or a static method. If you have an instance > already, the class can be resolved via self.__class__. If you don't > have an instance, the desired class can be passed as an argument to a > static method. I find that slightly surprising. You say that if you have a static method you can pass the class as a parameter, but since you already specify the class somewhere to access the static method surely you are duplicating information unneccessarily? You could equally say that static methods aren't needed because you can always use a class method and just ignore the class parameter if you don't need it. > > I sounds like you may have a good use case for classmethods. Could > you give us an example, and a brief explanation of what it does that > can't be done as easily with other method forms? Your help will be > greatly appreciated. Ok, I'll try and give you a couple of examples, feel free to tear them apart. The most obvious one is to write factory methods: -------- begin cut --------------- class Shape(object): def __init__(self): super(Shape, self).__init__() self.moveTo(0, 0) self.resize(10, 10) def __repr__(self): return "<%s instance at %s x=%s y=%s width=%s height=%s>" % ( self.__class__.__name__, id(self), self.x, self.y, self.width, self.height) def moveTo(self, x, y): self.x, self.y = x, y def resize(self, width, height): self.width, self.height = width, height # Factory methods def fromCenterAndSize(cls, cx, cy, width, height): self = cls() self.moveTo(cx, cy) self.resize(width, height) return self fromCenterAndSize = classmethod(fromCenterAndSize) def fromTLBR(cls, top, left, bottom, right): self = cls() self.moveTo((left+right)/2., (top+bottom)/2.) self.resize(right-left, top-bottom) return self fromTLBR = classmethod(fromTLBR) class Rectangle(Shape): pass class Ellipse(Shape): pass print Rectangle.fromCenterAndSize(10, 10, 3, 4) print Ellipse.fromTLBR(20, 0, 0, 30) squares = [ Rectangle.fromCenterAndSize(i, j, 1, 1) for i in range(2) for j in range(2) ] print squares -------- end cut ------------ Running this code gives something like: [, , , ] The important point is that the factory methods create objects of the correct type. The shape class has two factory methods here. Either one of them could actually be moved into the initialiser, but since they both take the same number and type of parameters any attempt to move them both into the initialiser would be confusing at best. the factory methods give me two clear ways to create a Shape, and it is obvious from the call which one I am using. Shape is clearly intended to be a base class, so I created a couple of derived classes. Each derived class inherits the factory methods, or can override them if it needs. Instance methods won't do here, as you want a single call to create and initialise the objects. Static methods won't do as unless you duplicated the class in the call you can't create an object of the appropriate type. My second example carries on from the first. Sometimes you want to count or even find all existing objects of a particular class. You can do this easily enough for a single class using weak references and a static method to retrieve the count or the objects, but if you want to do it for several classes, and want to avoid duplicating the code, class methods make the job fairly easy. --------- begin cut ------------- from weakref import WeakValueDictionary class TrackLifetimeMixin(object): def __init__(self): cls = self.__class__ if '_TrackLifetimeMixin__instances' not in cls.__dict__: cls.__instances = WeakValueDictionary() cls.__instancecount = 0 cls.__instances[id(self)] = self cls.__instancecount += 1 def __getInstances(cls): return cls.__dict__.get('_TrackLifetimeMixin__instances' , {}) __getInstances = classmethod(__getInstances) def getLiveInstances(cls): instances = cls.__getInstances().values() for k in cls.__subclasses__(): instances.extend(k.getLiveInstances()) return instances getLiveInstances = classmethod(getLiveInstances) def getLiveInstanceCount(cls): count = len(cls.__getInstances()) for k in cls.__subclasses__(): count += k.getLiveInstanceCount() return count getLiveInstanceCount = classmethod(getLiveInstanceCount) def getTotalInstanceCount(cls): count = cls.__dict__.get('_TrackLifetimeMixin__instancecount' , 0) for k in cls.__subclasses__(): count += k.getTotalInstanceCount() return count getTotalInstanceCount = classmethod(getTotalInstanceCount) class Shape(TrackLifetimeMixin, object): def __init__(self): super(Shape, self).__init__() self.moveTo(0, 0) self.resize(10, 10) def __repr__(self): return "<%s instance at %s x=%s y=%s width=%s height=%s>" % ( self.__class__.__name__, id(self), self.x, self.y, self.width, self.height) def moveTo(self, x, y): self.x, self.y = x, y def resize(self, width, height): self.width, self.height = width, height # Factory methods def fromCenterAndSize(cls, cx, cy, width, height): self = cls() self.moveTo(cx, cy) self.resize(width, height) return self fromCenterAndSize = classmethod(fromCenterAndSize) def fromTLBR(cls, top, left, bottom, right): self = cls() self.moveTo((left+right)/2., (top+bottom)/2.) self.resize(right-left, top-bottom) return self fromTLBR = classmethod(fromTLBR) class Rectangle(Shape): pass class Ellipse(Shape): pass print Rectangle.fromCenterAndSize(10, 10, 3, 4) print Ellipse.fromTLBR(20, 0, 0, 30) squares = [ Rectangle.fromCenterAndSize(i, j, 1, 1) for i in range(2) for j in range(2) ] print Shape.getLiveInstances() for cls in Shape, Rectangle, Ellipse: print cls.__name__, "instances:", cls.getLiveInstanceCount(), \ "now, ", cls.getTotalInstanceCount(), "total" --------- end cut ------------- The middle part of this file is unchanged. I've added a new mixin class at the top, but the class Shape is unchanged except that it now includes the mixin class in its bases. The last 4 lines are also new and print a few statistics about the classes Shape, Rectangle, Ellipse: [, , , ] Shape instances: 4 now, 6 total Rectangle instances: 4 now, 5 total Ellipse instances: 0 now, 1 total From jzgoda at gazeta.usun.pl Sun May 9 14:16:49 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 9 May 2004 18:16:49 +0000 (UTC) Subject: Python documentation in Qt Assistant? Message-ID: Has anyone tried to integrate Python documentation with Qt Assistant? I know I can view Python documentation with Eric3 help viewer, but I would like to use Assistant's full-text searching capability. -- Jarek Zgoda http://jpa.berlios.de/ From irmen at -nospam-remove-this-xs4all.nl Sat May 8 10:38:18 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 08 May 2004 16:38:18 +0200 Subject: Logging module, a few questions Message-ID: <409cf0da$0$21804$e4fe514c@news.xs4all.nl> Hello I'm using the logging module in Python 2.3.3, with a format string containing %(asctime). But it now dumps a full date +timestamp in the log, which is nice but sometimes I only want the timestamp (no date). Is there an easy way to change this? How can I make %(asctime) dump only the time? I'm using a configuration file to set up the logging. Which brings me to another thing. In java's log4j, it's easy to "silence" or "enable" specific parts of a logging hierarchy, by doing: log4j.category.nl.company = DEBUG log4j.category.nl.company.lib = WARN log4j.category.org.apache = WARN and so on. I see no easy way of doing the same for Python's logging module; it seems that I have to create a handler for each of the different parts of the hierarchy of which I want to set the loglevel. Am I missing something? Thanks! --Irmen de Jong From max at alcyone.com Mon May 24 01:53:56 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 May 2004 22:53:56 -0700 Subject: ANN: uid.py 1.0.2 -- Configurable unique ID generation References: <40AC1487.EA453C74@alcyone.com> Message-ID: <40B18DF4.46B39DD1@alcyone.com> Tim Roberts wrote: > Maybe I'm being ridiculous, but intuitively, this makes me > uncomfortable. > If one has a "unique ID" generator, isn't it likely that any change to > its > configuration is only going to serve to reduce the "uniqueness"? Only if the chances of a collision are increased. Since there are no known MD5 (much less SHA) hash collisions, that does not seem worth worrying about. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Extremes meet. -- John Hall Wheelock From lucabaralis at tiscalinet.it Fri May 28 03:20:45 2004 From: lucabaralis at tiscalinet.it (LB) Date: Fri, 28 May 2004 09:20:45 +0200 Subject: pdf2txt References: Message-ID: > I know that a txt2pdf exists, was checking to see if the opposite would > as well. I'm sure that from Acrobat you can save a .pdf as .rtf (that is text...). Then it will be easy to do anything on it. I remember also some utilities to "pdf2txt", try a search on google. LB From eric_brunel at despammed.com Mon May 24 04:22:32 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 24 May 2004 10:22:32 +0200 Subject: Help on multithreading and Tkinter; Linux vs Windows References: Message-ID: corrado wrote: > Hello > > I have an application running several thread to display some financial > data; > basically I have a thread displaying HTML tables by means of Tkhtml, > another implementing a scrolling ticker based on a Text widget with > embedded windows and a thread running the Tkinter mainloop plus > several other thread dealing with the scheduling of the contents and > the acquisition of data but not using graphic widgets. > I run the same code on Linux and Windows; I have no problems on Linux > while on Windows everything get stucked when I tried to scroll the > ticker, it looks like I'm blocked in mywidget.xview(SCROLL,1,UNITS); > at this time the graphic of the application freezes while all the rest > goes on running. Like many other GUI toolkits, it seems that Tkinter doesn't like to be called from several threads in the same application. The fact that it works on Linux is what is suprising to me: I already tried to do a similar thing on Linux and finally gave up, because I experienced many lock-ups like you do. The solution is always the same: use only one thread to manage the GUI, preferably the main one, and use a combination of Tkinter GUI events posted via event_generate and Queue's to pass information from secondary threads to the GUI. It messes up the code a bit, but it's the only way we've found to avoid the lock-up's you're experiencing. [snip] > Is there anyone who can help me? I've already tried the > Tkinter-discuss mailing list but I got no answer. > I supposed Tkinter worked the same way under Windows and Linux but it > does not look like it's so; is there any paper explaining the > differences between the behaviour on the two operating systems? For > instance on Windows I also had problem with iconify and with the > button highlight, which is Windows standard whatever setting you try. Try the tcl/tk documentation at http://www.tcl.tk/man ; it of course describes the tcl commands corresponding to the Tkinter classes and methods, but has much more details about the differences between the supported platforms than any Tkinter documentation I know. But you're touching quite a deep problem here: the mix of GUI and threads is a tough issue, and the problems you experience may depend not only on tk or Tkinter, but also on how Python manages threads and how the underlying system supports them. I fear your best source of info on this matter will be newsgroups like this one... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From heikowu at ceosg.de Tue May 4 17:06:31 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 4 May 2004 23:06:31 +0200 Subject: iter jitters In-Reply-To: References: Message-ID: <200405042306.31428.heikowu@ceosg.de> Even easier: """ class foo: def __init__(self): self.data = range(10) def __iter__(self): for e in self.data: yield e for i in foo(): print i __iter__ may itself be a generator (I mostly use it exactly in this way). HTH! Heiko. From max at alcyone.com Sun May 30 18:22:05 2004 From: max at alcyone.com (Erik Max Francis) Date: Sun, 30 May 2004 15:22:05 -0700 Subject: Question about exec() References: Message-ID: <40BA5E8D.2F9CFA33@alcyone.com> Adonis wrote: > Nevertheless, inside the html document I have > python enclosed in tags, and it executes fine, but if I have a > few of > those tags I would like that prior executions stay in memory of the > same > document, instead of having to load X module everytime I wish to > execute the > code in the same document. Maintain a separate globals dictionary and give it to exec: exec code in myGlobals -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Life is one long process of getting tired. -- Samuel Butler From pit.grinja at gmx.de Thu May 20 04:38:44 2004 From: pit.grinja at gmx.de (Piet) Date: 20 May 2004 01:38:44 -0700 Subject: wxPython: Looping over all children of a sizer Message-ID: <39cbe663.0405200038.3406d131@posting.google.com> Hello, I need some help with the design of a "dynamic" wxDialog. The dialog window is divided into several sizers, the first contains a wxComboBox. When choosing an entry from this wxComboBox, a second sizer (RowColSizer) will be populated with some controls, the number and type of which will depend on the selected ComboBox-Entry. That works fine for the first selection: The wxDialog is enlarged to give room for the new controls. But when I make another selection, I get an error saying that some positions in the sizer are populated twice. It is obvious that the sizer has to be cleared before I put in the new controls. I checked the documentation and found the Remove-Method for sizers. Unfortunately, this method seems only to be able to remove a sizer completely (which is not want I want, because the sizer will be repopulated in the next step, and I dont want to recreate it, because the sizer has to keep its position in the dialog relative to the other sizers) or to remove the item with the specified position (which is no alternative as well, because the number of childs or controls in the sizer will vary). Now my question: is there a clearall-Method for sizers that removes all the items in the sizer or is there a function to get the number of childs in the sizer so that I could write something like for i in range(sizer.GetNumberOfChildren()): sizer.Remove(i) That would help me a lot. Thanks in advance Piet From budr at local.host Sat May 15 22:00:29 2004 From: budr at local.host (Bud Rogers) Date: Sat, 15 May 2004 21:00:29 -0500 Subject: RELEASED Mailman 2.1.5 References: Message-ID: Barry Warsaw wrote: > Mailman 2.1.5 is a significant upgrade which should improve disk i/o > performance, administrative overhead for discarding held spams, and Barry, a quick question if I may. I think I read something about incorporating bayesian filtering into Mailman. Is that still in the works? Any idea of a time frame? > Finally, a personal note. I have left Zope Corporation to join Secure > Software, a company started by John Viega -- Mailman's original > author. Good luck in your new venture. From imbosol at aerojockey.invalid Tue May 11 23:01:11 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Wed, 12 May 2004 03:01:11 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: Kirk Job-Sluder wrote: > Write me a two-line script in python that reads a character delimited > file, and printf pretty-prints all of the records in a different order. How about one line (broken into three for clarity): for line in __import__('sys').stdin: print ''.join([ x.rjust(10) for x in map( line.strip().split(',').__getitem__,[4,3,2,1,0]) ]) Believe it or not, I actually do stuff like this on the command line once in awhile; to me, it's less effort to type this in than to remember (read: look up) the details of awk syntax. I don't think I'm typical in this regard, though. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From hans at zephyrfalcon.org Wed May 12 01:46:15 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 12 May 2004 01:46:15 -0400 Subject: How to update window after wxGrid is updated? In-Reply-To: References: Message-ID: <40A1BA27.9070706@zephyrfalcon.org> Tim Williams wrote: > Hi. > > I'm starting to learn wxPython and for an exercise I'm writing a > simple CSV file viewer. I just read in the CSV file and create a > wx.Grid with the data. I'm using Python 2.3.2 with wxPython 2.4.2.4. > > Everything runs fine under linux, but when I try the same code on a > Win XP machine, I have a window, but the frame the grid is in isn't > seen until I do a minimize/maximize on the window. Besides that, it > seems to run fine. I tried to do a self.Refresh(True, > self.grid.GetRect()), but that didn't help. I believe wx.Yield() should do the trick. From max at alcyone.com Mon May 24 04:02:03 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 01:02:03 -0700 Subject: iterator expression - please explain References: <2hdobkFbkjkoU1@uni-berlin.de> Message-ID: <40B1ABFB.B6F854BA@alcyone.com> Helmut Jarausch wrote: > myfun(x^2 for x in xrange(10)) ... > I expected the sequence 0,1,4,9,.... > What am I missing and what's going on here? ^ is the bitwise xor operator. You wanted **. (Although what you wrote above isn't legal anyway.) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ War is the province of chance. -- Karl von Clausewitz From donn at drizzle.com Wed May 26 02:24:34 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 26 May 2004 06:24:34 -0000 Subject: Embedding Python at the OS level - build problems References: Message-ID: <1085552673.374501@yasure> Quoth Phil Frost : ... | I really have a swarm of questions. Among them are: | | - is there a better way to cross compile python? | - is there anything I can do about the above error? I have never cross compiled anything, but I find it kind of troubling to hear that the compiler was finding include files in /usr/include. If they're missing in the target, it should just fail to find them. posixmodule is naturally one of the more difficult things to build on a new platform. If your problems are no worse than I_PUSH is missing, you are in fat city. socketmodule may also be difficult, and if you have your own platform specific threading API that will take some work. | But most importantly: | | - is the posix module really required? At the moment, I'm interested in | only getting a minimal Python working, so anything that can be | disabled, should be. What things can I do to eliminate all features, | modules, and whatever that isn't required to build libpython2.3.a? I don't think posixmodule is strictly required, but that brings up another can of worms. Python builds itself. You build it with posixmodule (cf. Modules/Setup) so it can run setup.py. This is, of course, to run on your build host. But of course you need a to end up with different binary to run on your target host. I shouldn't worry, I'm sure people do this all the time, it just sounds kind of hairy to me. I know I'm not much help, but you should be able to find some good technical discussion of minimal Python builds in the Google archives of comp.lang.python. It has definitely been done. Donn Cave, donn at drizzle.com From miki.tebeka at zoran.com Tue May 11 03:16:01 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 May 2004 09:16:01 +0200 Subject: Writing Formatted txt to a file (xtreme newbie q) In-Reply-To: <8a0bb987.0405101503.2656788a@posting.google.com> References: <8a0bb987.0405101503.2656788a@posting.google.com> Message-ID: <40A07DB1.3080908@zoran.com> Hello Uri, > The data is in the format of a list right now (maybe a dictionary at > some point) and there is one question and one answer per column. I > would like to set it up as "Question: Answer" in side-by-side > formatted columns, or perhaps "Question" over "Answer" in two rows, > answers on bottom. Try the "csv" module (http://www.python.org/doc/current/lib/module-csv.html) HTH. Miki From martin at v.loewis.de Mon May 31 04:21:02 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 31 May 2004 10:21:02 +0200 Subject: terminological obscurity In-Reply-To: <63okb0tv8f5fc2ahcfuohafk0og60ic0q0@4ax.com> References: <1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <55ijb01a95i9ccfn2hut9q8dv1gvogut4c@4ax.com> <1085933508.579296@yasure> <63okb0tv8f5fc2ahcfuohafk0og60ic0q0@4ax.com> Message-ID: <40baeaee$0$27038$9b622d9e@news.freenet.de> Arthur wrote: >>Python's typing isn't all about what type(x) returns. >> > > And they tell me Python's great for kids ;) Indeed. Kids have real problems grasping the notion of types (let alone of type hierarchies); I can tell from experience that first-year computer science students still have these problems. With duck typing, the need to even introduce the notion of types goes away: you invoke operation on objects, and if the operation makes sense for the object, it will proceed. At that point, it is irrelevant what other objects would also allow the operation to proceed. After a few months of Java, students are spoiled, and consider static types and type hierarchies a natural thing, and consider duck typing as evil. Regards, Martin From peter at engcorp.com Wed May 19 14:23:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 May 2004 14:23:01 -0400 Subject: pyVideoIO source release In-Reply-To: <2h0jkcF7rbfvU1@uni-berlin.de> References: <2gugfoF6p9rhU1@uni-berlin.de> <2h0jkcF7rbfvU1@uni-berlin.de> Message-ID: Riccardo wrote: > Peter Hansen wrote: >> Riccardo wrote: >>> www.geocities.com/rtrocca/python >> >> You should probably add a copy of the LGPL to the source package... > > Hello, I checked my source package and I've seen that a copy of the LGPL > tex is included in the VideoIO/src directory. > Is it ok to do so or something is missing? That's probably okay, though I didn't find it after a bit of poking through the zip. I believe it's a fairly common convention to include a copy (in a file called LICENSE?) in the top-level directory of the archive, but I don't suppose that's necessary if you've got it somewhere else. My apologies for missing it. -Peter From tim.one at comcast.net Wed May 26 22:58:12 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 26 May 2004 22:58:12 -0400 Subject: how to terminate a process on win32? In-Reply-To: <013301c44392$eaa2a3b0$7f00a8c0@scl01.siliconcreation.com> Message-ID: [Joe Wong] > But calling TerminateProcess will stop the application right away. I need > someway that the process being killed get notified and thus to carry out > some procedure before shut down. On Linux, I can use kill(pid, signum) to > achive this but on windows? There is no way guaranteed to work on Windows. This MS article explains the *intended* way, but many apps (and especially console apps) don't play this game: http://support.microsoft.com/default.aspx?scid=kb;EN-US;q178893 The short course is that native Win32 programs with a GUI "should" be running a message pump, and their top-level window should respond to a WM_CLOSE message by shutting down the app cleanly. If they're not coded that way, then no, you have in general no way to force them to shut down cleanly. Googling will turn up many approximations that more-or-less work for different kinds of apps. Bottom line is really that life is sheer hell unless the process you're trying to shut down *advertises* a way to force that from outside (like responding to WM_CLOSE, or the state of a global semaphore, or a particular string of bytes sent to an agreed-upon socket, etc). From jepler at unpythonic.net Tue May 18 08:46:29 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 18 May 2004 07:46:29 -0500 Subject: how to keep one instance??? In-Reply-To: <200405180732.i4I7WGb19062@bald.unpythonic.net> References: <200405180732.i4I7WGb19062@bald.unpythonic.net> Message-ID: <20040518124627.GH14843@unpythonic.net> I'm not sure how Windows applications typically do this, in low-level terms. The answer, in general terms, would be that you need to have a way for a new instance of your app to communicate with an existing one. When the user opens a file, the application starts by finding whether another copy of the application has the document open, and if so that window is just raised to the top and given focus. Otherwise, the document is actually opened. You can expand this a little bit, so that if the document was not yet open it's still opened in the first copy of the application (but in a different window). In Tk, the "send" command can be used to implement inter-application communication. Using the BLT package, "send" works on Windows as well as Unix. I've never used send for this purpose, though, and I'm not even sure whether an interface to it is provided by Tkinter. Other widget toolkits might provide other methods, and there may be a single method that you're supposed to use in a win32 application that I don't know about. Note that there are often race conditions here---if two copies of the application start nearly simultaneously, both may detect that no other copy of the app exists. If someone wants to tell me the way to get this right in the context of Unix/X11, please speak up! Jeff From pete at shinners.org Fri May 14 01:26:02 2004 From: pete at shinners.org (Pete Shinners) Date: Thu, 13 May 2004 22:26:02 -0700 Subject: Idea: PYTHONPATH_VER Message-ID: I've been working on systems that have multiple versions of python. People are also trying to manage the compilation of external extension modules. The problem is there is no easy way to control the separate modules for each python version. I keep thinking having a separate PYTHONPATH environment variable for each version of Python would really make life easier. I have heard Perl started doing this sometime ago and it is in use on these same machines. At startup Python 2.4 would prepend PYTHONPATH24 to the regular path. Easy to do, likely just slip into the "site.py". Would there be any problems trying to get something like this added for 2.4? From SeeBelow at SeeBelow.Nut Mon May 31 15:13:02 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Mon, 31 May 2004 19:13:02 GMT Subject: Best way to put out a small package for public scrutiny and use? References: Message-ID: <40BB83DF.6A96D30@shaw.ca> Kenneth McDonald wrote: > > I've created a small (and I believe, very useful) package to ease the > creation and use of regular expressions. I'd like to make it available, > (though the first release will be aimed mostly at finalizing > functionality, not at being a polished project.) I don't want to use > SourceForge, as I don't use CVS, and I'm not yet ready (if ever) > to open up my home Subversion server to public access. If this > was just a single file, I'd simply post it in this newsgroup to > start with, but as it incorporates a couple of files, I need to post > the directory somehow. Any thoughts as to the best way to make > this package available? You can release files on SourceForge without using CVS. We do it all the time. You can just collect all the files into a .zip and then upload it. The public can then download the zip file. I will help you with SF usage if you need help. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From wilkSPAM at OUTflibuste.net Wed May 26 12:14:14 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 26 May 2004 18:14:14 +0200 Subject: ANN : ConfigObj 3.0.0 - Simple config file parsing References: <8089854e.0405260620.230f8319@posting.google.com> Message-ID: <87vfijyxm1.fsf@blakie.riol> michael at foord.net (Fuzzyman) writes: > There have been a couple of config file 'systems' announced recently, > that focus on building more powerful and complex configuration files. > ConfigObj is a module to enable you to much more *simply* access > config files. What do you thing about yaml for config file ? it's very pythonic with indentation : import yaml print yaml.load(""" rub1: - one - two rub2: - three - four """).next() {'rub1': ['one', 'two'], 'rub2': ['three', 'four']} it can also work on the other side : print yaml.dump({'rub1': ['one', 'two'], 'rub2': ['three', 'four']}) --- rub1: - one - two rub2: - three - four -- Wilk - http://flibuste.net From kkto at csis.hku.hk Fri May 28 22:09:20 2004 From: kkto at csis.hku.hk (Isaac To) Date: Sat, 29 May 2004 10:09:20 +0800 Subject: "Private" Member Variables References: Message-ID: <7illjc6l2n.fsf@enark.csis.hku.hk> >>>>> "Scott" == Scott Brady Drummonds writes: Scott> The problems that arise from directly relying on the member Scott> variable in C++ (compile-time type dependency, as I said above) Scott> don't exist in Python. So why provide an accessor at all? Why Scott> not just allow direct reading and writing of the member variable? Scott> Is there something here I'm missing? Scott> What are your thoughts? How much privacy should I build into my Scott> code? Should I be using variables beginning with "__" and Scott> accessors? Or is that simply not necessary (or normal) in Python Scott> code? The "__" convention is not about hiding, which, as others has noted, need not exist anyway. See an example first: >>> class C: ... def value(self): ... return self.__value ... def setvalue(self, val): ... self.__value = val ... >>> c = C() >>> c.setvalue(5) >>> c.value() 5 >>> c.__value Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute '__value' >>> dir(c) ['_C__value', '__doc__', '__module__', 'setvalue', 'value'] >>> c._C__value 5 >>> c._C__value = 10 >>> c.value() 10 Now it should be clear that the outside can still access the __value within c, although it has to be named a bit differently: _C__value. So the "__" doesn't prevent others from accessing the field. "__" is important for classes that simultaneously are (1) changing, and (2) inherited by someone else. It solves a namespace issue. Suppose you are write a class C, give it to your friend, who derive another class D from it. In the process of deriving, your friend needs to add a collection of fields into C. Of course, he reads the documentation of C and, like the above, the dir() of it to see what field names to avoid. He thus derives a correct class D from C. But you know nothing about it. In particular, you don't know what fields are used by your friend. You continue modify your class to improve it, and in doing so you need to create additional private fields. Being private, you don't document them. Then you give the class to your friend, who read the documentation, see nothing intrusive, and use it as a plug-in replacement of D. Unluckily, your friend won't know that the fields of your new C actually clash with the fields of D, and when the class is in use it gives strange behaviour, giving them a hard time debugging. A simple technique would resolve the issue: use a naming scheme that says "this is field f of class C". So you would name the field like "C_f" instead of "f". But when the class name and the field name are long, this is not an attractive solution. The "__" trick give you best of both worlds: you avoid name clashing, and at the same time you don't need to write long names. And as a further benefit it is fully standardized, so you don't need to worry that the third programmer would use a different naming convention. Regards, Isaac. From andreas at easywebsite.se Tue May 18 08:58:16 2004 From: andreas at easywebsite.se (SubZane) Date: 18 May 2004 05:58:16 -0700 Subject: Regexp to enclose text with P-tag Message-ID: I'm looking for help writing a regexp to enclose text with a

tag. The rule is that other HTML tags in the text like and other block elements should NOT be enclosed by

. example: lorem ipsum dolor should become:

lorem ipsum

dolor

Can anyone help me with this? :) From r.gable at mchsi.com Mon May 24 07:25:15 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 24 May 2004 04:25:15 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> Message-ID: <22b7fd40.0405240325.7b2b6376@posting.google.com> "Kevin T. Ryan" wrote in message news:<40b1697d$0$3131$61fed72c at news.rcn.com>... > Ralph A. Gable wrote: > > > I'm a newbie at this but I need to control MSIE6 using Python. I have > > read the O'Reilly win32 python books and got some hints. But I need to > > Navigate to a site (which I know how to do) and then I need to get at > > the source code for that site inside Python (as when one used the > > View|Source drop down window). Can anyone point me to some URLs that > > would help out? Or just tell me how to do it? I would be very > > grateful. > > I'm not sure why you need to go through IE, but maybe this will get you into > the right direction: > > >>> import urllib > >>> f = urllib.urlopen('http://www.python.org') > >>> f.readline() > ' >>> f.readline() > ' "http://www.w3.org/TR/html4/loose.dtd" >\n' > >>> > > You could do: > for line in f: > process(line) > > just like you can with a file. Check the urllib, urllib2, and other related > modules (maybe httplib). Hope that helps. Sorry. I forgot to mention that I have tried that. The data I want is being stripped out when I access the URL via urllib. I CAN see the data when I go into IE and do view source but when I use urllib the site intentionally blanks out the information I want. For that reason, I would like to get it using IE6 if I can. If there are other ways to fake out the site, I would be interested in that also. I thought that perhaps the site was detecting the fact that I was not querying it using a browser. I tried putting that into into the HTTP messages but may not have done it right. At any rate couldn't get that to work. It may be that the site is using cookies to be sure someone is not getting the data. I haven't pursued that. Again that is another reason I wanted to use IE6 (since I know it works). The data is on a site to which I subscribe to a service. But the particular information is available to anyone if he/she types in the url (as long as you are using a browser). From mark at freelance-developer.com Wed May 5 12:01:45 2004 From: mark at freelance-developer.com (Mark J. Nenadov) Date: Wed, 05 May 2004 12:01:45 -0400 Subject: Web programming ... References: Message-ID: On Wed, 05 May 2004 11:49:46 -0400, Sarah Tanembaum wrote: > Is python good for creating Web application? I do like the OOness of Python, > as a newbie, I'm trying to find out if Python has all its necessary > modules/utilities for Web programming just as extensive as, say, PHP or > Ruby(some say that Ruby is not ready for this sort of application and is not > yet mature as Perl, Python, and PHP - is it true?). Sasha, Yes. Python is good for creating web applications. Have you ever heard of Zope? I strongly suggest that you have a look at it. -- Mark J. Nenadov From bkc at Murkworks.com Wed May 12 09:15:58 2004 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 12 May 2004 09:15:58 -0400 Subject: sending out XML from python. References: <03foc.111778$Jy3.44600@fed1read03> <3o2dnQnr_4xJDDzdRVn_iw@powergate.ca> Message-ID: Also consider elementtree http://effbot.org/zone/element-index.htm -- Novell DeveloperNet Sysop #5 _ "Peter Hansen" wrote in message news:3o2dnQnr_4xJDDzdRVn_iw at powergate.ca... > Sean Berry wrote: > > > I am going to be doing some programming with a Flash programmer in my > > company. Most of the online docs about integrating Flash with another > > language use PHP. I am not a fan of PHP. > > > > What I would really like to do is use Python to create data in the form of > > XML to send back to Flash, since Flash MX has the ability to easily parse > > XML to get variables and values. > > > > I have done some reading on XML in Python, but only stuff I have seen has > > been geared toward reading in XML data, not spitting it out. > > > > Is there a module for doing this? I know that I can make something that > > would work, but wondered if it is already done. > > It's often the case that the simplest thing is just to build > up the strings from scratch. Constructing an awkward > in-memory representation (ala DOM) just to serialize it > immediately can be a trying experience. > > How complicated will your XML be? > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From benn at cenix-bioscience.com Tue May 25 07:21:05 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 25 May 2004 13:21:05 +0200 Subject: Unification of Methods and Functions In-Reply-To: References: <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> <2hft17Fc8642U1@uni-berlin.de> Message-ID: <40B32C21.8070406@cenix-bioscience.com> David MacQuigg wrote: >On Tue, 25 May 2004 15:31:49 +1200, Greg Ewing > wrote: > > > >>David MacQuigg wrote: >> >> >>>My perspective may be different, because I have not yet absorbed the >>>Python traditions, and I don't have any instictive avoidance of static >>>methods. >>> >>> >>> >>> >>But Python has modules for use as general-purpose >>namespaces. Classes are thus relieved of the burden >>of performing this double duty, leaving them free to >>concentrate on what they do best, which is defining >>the behaviour of a collection of objects. >> >> The point is that a static method defined in a class _is_ a part of the object model. There are many, many object models where you would have a static method that _belongs_ to the class. For a dummy example : -- A dodo class which has a method to return a new dodo when it is born. A dodo class with a static method to return the first ever dodo (the uber-dodo!), this is a static method - making the constructor return the same dodo each time is counter intuitive. ALSO A dodo class static method of Dodo.makeExtinct(), this applies to the Dodo class (species) and not to the individual dodo (animal). -- In addition, when returning a singleton, that should live in with the class as the fact that a class in only available as a singleton is a factor of the design of the class and should not be linked to another namespace. I am a ex-Java/.NET programmer so I admit I'm biased but the problem is not language specific, it's design specific. I do understand that in Python this is only syntatic sugar but using a module namespace to acheive these needs removes what is a link in the design. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 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 vbasicboy at aol.com Sat May 22 04:13:02 2004 From: vbasicboy at aol.com (Grant D. Watson) Date: 22 May 2004 08:13:02 GMT Subject: Running code on module import References: <20040522035701.13396.00001028@mb-m06.aol.com> Message-ID: <20040522041302.13396.00001029@mb-m06.aol.com> >This works so long as runmain is the first module imported by any module that >uses it. No sooner said than I find that this doesn't work in my rewrite, only in my first "version" (prototype is more like). Anyway, I suspect that this is because in the first one I used a recursive import. (Is this dangerous? It seems like it ought to be.) In the second one I tried to find the main() function in the module object when the module hadn't finished initializing yet. Am I attempting the impossible, here? Will recursive imports burn me? Grant D. Watson grant_watson at yahoo.pleasedontspamme.com (Please use this address, not my AOL one.) From ajsiegel at optonline.com Tue May 25 19:59:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 May 2004 23:59:05 GMT Subject: terminological obscurity References: <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: On Tue, 25 May 2004 09:03:29 -0700, Donn Cave wrote: Donn - First let me thank you for engaging me. I have learned some, and it has allowed me to express myself some. >> But with everything subclassable, 2 different classes, each derived >> from object, are conceptually distinguished more similarly to the way >> in which a str and int are distinguished. > >Really makes no difference at all - not just insignificant, >really _no_ difference. A truly heterogeneous sequence may >be full of references to the _same_ object (e.g., (1, 1, 1)), >and a truly homogeneous sequence may have objects as different >as None and a module. It's not about properties of the objects, >considered in isolation. You fundamentally miss my point. What you are saying is clear enough. You are also saying that this is what Guido meant, when he said something different. And leaving as anomolous why Guido didn't say what he meant himself. I am connecting 2 points by a straight line, rather by way of an occult labyrinth. I am suggesting the possbility that Guido's expressed himself ambigously, because the matter wasn't as crsiply defined in his own mind as it is in yours. The part I consider to be pure, but plausible speculation, is why that might have been true. That at an earlier point in Python's development, the distinction between homogenous data and a homogenous sequence was not crucial to draw, and that Guido therrfore hadn't drawn it. >> He sort of stacks the cards by making his tuples of hetereogenous >> type, and his list easily described as a list of T. And thereby >> sidesteps all the ambiguities inherent in the ten word edict. Except >> that at the Object level, we are at lists of Objects and tuples of >> Objects. It detracts little from the point of the above quote, but >> this quote then becomes substantially weaker as support for his 10 >> worder. > >Guess he may have overestimated his audience. True. Not everyone can map from what he said to what he meant in the way you can :) > >If you're interested in the history of this matter, it may >help to know that Guido did not invent the tuple. It has >been around in computer programming languages since Lisp. >You can actually find precisely parallel descriptions of >the concept in that context, down to the unnecessary use >of different data types to emphasize the heterogeneity. > >Lisp and its relatives have both a tuple and a list type, >but the list is a `real list', not a 1-dimension array as >in Python but a recursive data structure. In Python, this >data structure can be represented using a tuple: > > t = (0, None) > t = (1, t) > t = (2, t) > ... > def print_list(tail): > value, tail = tail > if tail: > print_list(tail) > print value > >Guido's "mistake" is that unification of all these sequence >types leaves the distinctions less obvious. Maybe your grasp of this history could help explain things, on the slight possiblity that there is some merit my suggestion that you are clearer of these issues than Gudio had been in March of 2003, Art > > Donn Cave, donn at u.washington.edu From jepler at unpythonic.net Mon May 17 16:20:49 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 17 May 2004 15:20:49 -0500 Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: <20040517202049.GG14843@unpythonic.net> The result of modifying locals() is undefined. Jeff From jarausch at igpm.rwth-aachen.de Mon May 24 04:30:15 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 24 May 2004 10:30:15 +0200 Subject: iterator expression - please explain In-Reply-To: <40B1ABFB.B6F854BA@alcyone.com> References: <2hdobkFbkjkoU1@uni-berlin.de> <40B1ABFB.B6F854BA@alcyone.com> Message-ID: <40B1B297.6040802@igpm.rwth-aachen.de> Erik Max Francis wrote: > Helmut Jarausch wrote: > > >>myfun(x^2 for x in xrange(10)) > > ... > >>I expected the sequence 0,1,4,9,.... >>What am I missing and what's going on here? > > > ^ is the bitwise xor operator. You wanted **. (Although what you wrote > above isn't legal anyway.) > Many thanks for pointing out that silly mistake. But why isn't it legal? By the way, the corrected version (with **) works just fine (with the CVS version of Python from the weekend or today) Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From dyzma at mat.uni.torun.pl Wed May 19 09:11:42 2004 From: dyzma at mat.uni.torun.pl (Lukasz Indyk) Date: Wed, 19 May 2004 15:11:42 +0200 Subject: zope & cvs Message-ID: i work in programming team that has 6 members. we develop our application in Zope, and we write code using ZMI (Zope Management Interface). we want to use cvs to control versions of our software. is it possible use cvs with Zope (without abandoming ZMI), or is there any other solution that give similar features like cvs and can be used with ZMI? From peter at engcorp.com Tue May 11 09:41:35 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 May 2004 09:41:35 -0400 Subject: OT: Idea for Python T-shirt In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > (Don't mind me, my frequent late night "I should be sleeping by now" > brainstorm) > > A python smiling, its body curled in the background, 1's and 0's visible > in its body visibly grouped in fours, and below the slogan: > > "With Python your nibbles explode with desire" > > I'll do one for myself :) If you plan to try selling them, note that in North America it's generally "nybble", by analogy with "byte". Nibble is the British English spelling. Also, I don't get it... -Peter From ben.nospam at ladeda.co.uk Sun May 9 15:48:49 2004 From: ben.nospam at ladeda.co.uk (BenO) Date: Sun, 9 May 2004 19:48:49 +0000 (UTC) Subject: Replacing "illegal characters" in html Message-ID: Hi I'm new to python and need to write a function to replace certain characters in a string (html). The characters I need to replace come from MS Word copy & paste and are: ' (Left quote) ' (Right quote) Double Left quotes Double Right quotes Can anyone help me or point me in the right direction on an efficient way of doing this? Thanks Ben From grante at visi.com Thu May 13 17:42:00 2004 From: grante at visi.com (Grant Edwards) Date: 13 May 2004 21:42:00 GMT Subject: struct doesn't handle NaN values? References: Message-ID: On 2004-05-13, Tim Peters wrote: >> the struct module docs say it's IEE 754, but I can't figure >> out how to get it to handle NaN values correctly (either >> packing or unpacking). > > All Python behavior in the presence of 754 special values > (infs, NaNs, signed zeroes) is a platform-dependent accident. I guess the doc that claim struct supports IEEE 754 need to have a few footnotes added. > There's a growing list of these in PEP 42 (under > "Non-accidental IEEE-754 support"), but nobody even bothers to > keep that up to date. > >> >>> x = float('nan') > > It's even an accident that this line didn't raise an exception > (it does, for example, under the Windows Python). That would be fine. Either the correct answer or an exception I can handle would be acceptable. >> >>> struct.unpack(" > The C routine that gets invoked here is _PyFloat_Unpack4(), in > floatobject.c. As the comment there says, > > /* XXX This sadly ignores Inf/NaN issues */ > > That is, the outcome of this is also an accident. Ah. That needs to be fixed. It should either return a correct value or raise an exception. Silently returning wrong answers is hardly the way of "least surprises". -- Grant Edwards grante Yow! I'm DESPONDENT... I at hope there's something visi.com DEEP-FRIED under this miniature DOMED STADIUM... From ville at spammers.com Wed May 5 04:26:59 2004 From: ville at spammers.com (Ville Vainio) Date: 05 May 2004 11:26:59 +0300 Subject: improving the Python docs -- a wiki? copy PHP's model? References: <109gh8ml6lo6o7b@news.supernews.com> Message-ID: >>>>> "Roger" == Roger Binns writes: Roger> It is trivial to add new comments. Sure one could do Roger> it via SourceForge instead, but that is a far greater Roger> hassle. Every single little step you put in the way Roger> makes it less likely people will contribute. If you Roger> are running cathedral style development, then that is Roger> fine. I'm not sure I would like to see the official Python documentation "improved" too much. At least the library reference is top notch as it stands, and some other areas (distutils/embedding) should be covered in seperate volumes of documentation, e.g. some wiki-maintained tutorials. Documentation just isn't a problem for core Python. The same can't be said for various UI toolkits or third party libs, but that's a separate problem. -- Ville Vainio http://tinyurl.com/2prnb From Mike at DeleteThis.Geary.com Tue May 4 23:25:25 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 4 May 2004 20:25:25 -0700 Subject: Simple prototyping in Python References: <69cbbef2.0404300855.20dd436b@posting.google.com> <1095h4vc89hmcf@corp.supernews.com> <109eg534ca5cj8b@corp.supernews.com> Message-ID: <109gnl5sc4qob22@corp.supernews.com> > > Greg Ewing wrote: > >>BTW, IMO [the closure] is a seriously warped technique > >>that I would never use, even in Javascript. I can't see any > >>benefit in it that's anywhere near worth the obfuscation. > Michael Geary wrote: > > I think part of the problem is the contrived examples that > > we all use to illustrate closures. Greg wrote: > Just in case it wasn't clear, I was talking about that > particular use of a closure, i.e. simulating an object > with a private instance variable. I'm well aware that > there are other, better uses for closures. > > The example you posted is a reasonable use of > closures (although the in-line-constructed object > passed as an argument to a function made my brain > hurt a bit while trying to parse it!) Ah, roger that. Naturally, it's also possible to write that code by creating the events object first and then just passing a reference to it into the function call--it sounds like that would make it easier to read. -Mike From claird at lairds.com Fri May 21 11:14:00 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 21 May 2004 15:14:00 -0000 Subject: pexpect and OpenVMS References: <40ac9eaa@duster.adelaide.on.net> Message-ID: <10as75o6o3gbddf@corp.supernews.com> In article , Richard Brodie wrote: > >"Adrian Casey" wrote in message >news:40ac9eaa at duster.adelaide.on.net... > >> Any ideas on how to make pexpect work with VMS systems? > >I'm surprised you even got pexpect to run under VMS. The >fiddly terminal stuff doesn't look easy to port. Have you got some >build details? > > That's what I thought the first time I read it. I think when you re-read the description you'll see that Mr. Casey unequivocally explains that he's *driving* an OpenVMS process from a conventionally-hosted pexpect. -- Cameron Laird Business: http://www.Phaseit.net From imbosol at aerojockey.invalid Sat May 8 21:10:44 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 09 May 2004 01:10:44 GMT Subject: What I don't like about wxPython References: Message-ID: Peter Hansen wrote: > j_mckitrick wrote: > >> Just thought I'd play devil's advocate... >> >> I tried wxPython briefly, and it had some nice features. >> >> It has a huge list of dependencies. > > 1. Python. > 2. Windows. The Unix version requires at least Python, gtk, and wxlib. Gtk is technically three libraries: gtk, gdk, and glib. gdk depends on libpng, probably also libjpeg. The latest version has all kinds of i18n dependencies. Not that that isn't par for the course in Unix. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From premshree_python at yahoo.co.in Sat May 29 13:07:36 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 29 May 2004 18:07:36 +0100 (BST) Subject: creating .exe file In-Reply-To: <3f0686ff.0405260841.6deba711@posting.google.com> Message-ID: <20040529170736.87796.qmail@web8301.mail.in.yahoo.com> py2exe is what you are looking for: http://starship.python.net/crew/theller/py2exe/ --- Q X wrote: > Hello everyone, > > I am wondering what kind of tools are available to > wrap python scripts > into just 1 .exe file (with no other files) in > windows. I also want > the .exe file to be able to use command line > arguments ie. > pythonprogram.exe -classpath d:/temp -file > c:/hi.text > > Also, is this possible to do this free ie. without a > commercial > compiler like Visual Studios? > > Help is greatly appreciated. > > Thanks!!!! > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From adalke at mindspring.com Sat May 15 20:21:14 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 16 May 2004 00:21:14 GMT Subject: python-dev Summary for 2004-04-01 through 2004-04-30 References: Message-ID: <_typc.1756$H_3.304@newsread1.news.pas.earthlink.net> Brett C. > Anthony Baxter, fearless release manager, decided to run the Misc/ACKS > file through ``cvs annotate`` which prints out who edited every line and > when it was edited and then he sorted it. This was to see when people > were added to the ACKS file and thus find our roughly how long people > have been hacking on the Python core. ... > `__ Roughly indeed. My name was originally added as "ndrew Dalke" in 1.41 of 1998/12/21 and not 1.45 of 1999/04/10 when it was corrected. But who's counting. ;) Andrew From peter.maas at mplusr.de Mon May 24 15:15:41 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Mon, 24 May 2004 21:15:41 +0200 Subject: cannot fin sum() in python 2.3 In-Reply-To: <425cc8d1.0405240829.31e6471@posting.google.com> References: <425cc8d1.0405240829.31e6471@posting.google.com> Message-ID: mir nazim wrote: > i cannot find sum() built in fuction in 2.3 version. What is the output of dir(__builtins__)? > please tell me where can i find Python Imaging Library libxml2 > for python2.3 all the rpms/sources work for python 2.2 I'm quite sure that lbxml2 is an XML library, not an imaging library. Assuming that you work on a UNIX type OS: - Where was the python2.3 executable installed? - Did you verify that python is really linked to python2.3 and not to python2.2? AFAIK the sum() builtin function was introduced with python2.3. - Is libxml2 only in the python2.2 directory or also in the python2.3 directory? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From mwh at python.net Thu May 6 06:39:15 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 6 May 2004 10:39:15 GMT Subject: question: parameters for create_polygon() method References: <40984D5A.B819BF28@shaw.ca> <40986DD6.F06FF651@shaw.ca> Message-ID: Andrew Bennetts writes: > Odd, though -- I thought that calls that put non-keyword args after keyword > args were a syntax error, but using varargs syntax seems to workaround that > -- e.g. try: > canvas.create_polygon(fill="blue", (20, 20), (50, 150), (200, 50)) > > Or without Tk: > > >>> def f(*args, **kw): print args, kw > ... > >>> f(x=1, 2) > SyntaxError: non-keyword arg after keyword arg > >>> f(x=1, *[2]) > (2,) {'x': 1} > > Interesting. And even documented in all its tortuosity: http://docs.python.org/ref/calls.html (I know, I wrote that bit...) Cheers, mwh -- Well, yes. I don't think I'd put something like "penchant for anal play" and "able to wield a buttplug" in a CV unless it was relevant to the gig being applied for... -- Matt McLeod, alt.sysadmin.recovery From apardon at forel.vub.ac.be Tue May 25 03:08:37 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 May 2004 07:08:37 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> Message-ID: Op 2004-05-22, David MacQuigg schreef : > On Sat, 22 May 2004 18:28:33 -0000, "Donn Cave" > wrote: > > This is OK for the first example. I would leave the __init__ methods > to the second example, but either way it will take about 8 pages to > comfortably explain OOP ( maybe ten if I include the "robust > programming" examples that JM says I must ). I would like students to > understand Python at the level they can follow what is going on in a > real program, and maybe write a few classes themselves. > >>Then I would go over that, showing what happens and why, until the >>concepts introduced above seem to be clear for everyone. That would >>conclude my treatment of classes. As an elementary language, there >>are some slightly hard things to learn about Python, but this isn't >>going to be one of them unless you make it hard. > > If you are saying we can totally ignore the different method forms, I > think you are wrong. Bound and unbound methods, for example, will be > needed in almost any sizable program. The need for static methods > will arise when the student first writes a method that needs to work > without a current instance. He doesn't need a method for that. He can just write a function. Why do you want to write a method in circumstances that call for a function? -- Antoon Pardon From sarah.tanembaum at yahoo.com Wed May 5 11:49:46 2004 From: sarah.tanembaum at yahoo.com (Sarah Tanembaum) Date: Wed, 5 May 2004 11:49:46 -0400 Subject: Web programming ... Message-ID: Is python good for creating Web application? I do like the OOness of Python, as a newbie, I'm trying to find out if Python has all its necessary modules/utilities for Web programming just as extensive as, say, PHP or Ruby(some say that Ruby is not ready for this sort of application and is not yet mature as Perl, Python, and PHP - is it true?). From skip at pobox.com Thu May 20 11:51:29 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 May 2004 10:51:29 -0500 Subject: Why does the "".join(r) do this? In-Reply-To: <545cb8c2.0405200738.296bb094@posting.google.com> References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: <16556.54273.776379.350880@montanaro.dyndns.org> Jim> I'm building up a web page by stuffing an array and then doing Jim> "".join(r) at the end. I intend to later encode it as 'latin1', so Jim> I'd like it to just concatenate. While I can work around this Jim> error, the reason for it escapes me. Try u"".join(r) instead. I think the join operation is trying to convert the Unicode bits in your list of strings to strings by encoding using the default codec, which appears to be ASCII. Skip From gherzig at fmed.uba.ar Mon May 24 17:33:42 2004 From: gherzig at fmed.uba.ar (Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina) Date: Mon, 24 May 2004 18:33:42 -0300 Subject: smtplib data error In-Reply-To: References: Message-ID: <200405241833.42110.gherzig@fmed.uba.ar> If the drugs i got are still working, `550' error code stands "No soup for you!!" (Relaying Denied). Maybe the IP in your web server is not into the sendmail's access configuration file. Gerardo > Does anyone know what causes an SMTPLIB DataError? > > The only thing I can find in the manual is > exception SMTPDataError > The SMTP server refused to accept the message data. > > My problem is a previously functioning script suddenly failed last week. > My ISP thinks it maybe something to do with upgrading CPanel on their > server -- maybe a library was missed, but when I try and execute a > script I get... > > Traceback (most recent call last): File "test-py.cgi", line 790, in ? > sendemail(EmailFrom, EmailTo, emsg) File "test-py.cgi", line 20, in > sendemail failed = server.sendmail(EmailFrom, EmailTo, emsg) File > "/usr/lib/python2.2/smtplib.py", line 685, in sendmail raise > SMTPDataError(code, resp) smtplib.SMTPDataError: (550, 'Administrative > prohibition') > > Thanks for any suggestions. > > Lester. -- Gerardo Herzig Departamento de Proyectos Especiales e Internet Facultad de Medicina U.B.A. From lbates at swamisoft.com Thu May 6 16:27:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 6 May 2004 15:27:49 -0500 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: I use type() quite a lot. I poked around and couldn't find where it was being deprecated. I did see that types module is slated for deprecation. Maybe I overlooked it? I use: class foo: _stringtype=type('') _tupletype=type(()) _listtype=type([]) def __init__(self, variable): if type(variable) == _stringtype: self.variable=variable # check for string type if type(variable) in (_listtype, tupletype): self.variable=str(variable) # check for list/tuple . . . Seems to work well. You might also want to look at isinstance() function Larry Bates Syscon, Inc. wrote in message news:997a06e0.0405061128.6768676d at posting.google.com... > What's the standard way to implement polymorphic behavior in a python > method, given that method arguments can't declare their types as > they're being passed in, and method definitions don't have signatures? > > For instance, if I wanted to write a method that auto-detected whether > it was being passed a string or a tuple/list, how would I do so > without using type() to identify the parameter's type? Using type() is > deprecated in the documentation I've read. > > Thanks in advance. From jfabiani at yolo.com Mon May 17 19:07:39 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 17 May 2004 23:07:39 GMT Subject: module for working with the result set In-Reply-To: References: Message-ID: <%Abqc.68176$qY6.54842@newssvr25.news.prodigy.com> Paul McNett wrote: > john fabiani writes: > > >>mydata=cursor.fetchmany(10) >>for field in mydata[0]: >> print mydata[0][field] > > > I think you want: > > mydata=cursor.fetchmany(10) > > for record in mydata: > print "--- record ---" > for field in record: > print field > > Hi Paul, What I'd like to see is the data. So I can do Scan list the rows somewhat like a browse window. endscan But I don't even understand what is returned. The first part appears perfect but the rest who knows. John From lvirden at yahoo.com Fri May 7 11:34:25 2004 From: lvirden at yahoo.com (lvirden at yahoo.com) Date: 7 May 2004 15:34:25 GMT Subject: Tkinter on way out? (was: Newbe-books) References: <109hm398jc2uk3e@corp.supernews.com> Message-ID: According to Cameron Laird : :Perhaps so. I trust that asdf believes the evidence he sees :for Tkinter's demise. I agree that wxPython has much to re- :commend it. What's most certain, though, is that there have :been similar predictions about Tkinter's destiny for at least :the last eight years. The ... prematurity of these claims in :the past makes me hesitate to write Tkinter off now. Sorry - I hit the wrong button. I guess I misunderstood mxPython - I thought it was designed around a specific toolkit. Does it provide kde and gnome desktop compatibility? If not, then it seems strange that pythonians would move from one non-standard library to another. -- In God we trust. Even if explicitly stated to the contrary, nothing in this posting should be construed as representing my employer's opinions. From ptmcg at austin.rr._bogus_.com Mon May 17 13:44:18 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 May 2004 17:44:18 GMT Subject: Pyparsing question References: Message-ID: "Khoa Nguyen" wrote in message news:mailman.13.1084809534.6949.python-list at python.org... > Hi, > > I am a newbie to Python and pyparsing. I am having difficulty creating a > grammar that spans multiple lines, the input data look like this > > RTSP/1.0 200 OK\r\n > Cseq: 1\r\n > Session: 12345-1\r\n > \r\n > > Greatly appreciate if anyone can give me a sample or point me to the > right direction > > Thanks, > > > Khoa Nguyen ========================= Khoa - In general, pyparsing will ignore line breaks as whitespace. This data could be parsed with as broad a grammar as: response = Literal("RTSP") + restOfLine.setResultsName("RTSPline") + \ Literal("Cseq:") + restOfLine.setResultsName("CseqLine") + \ Literal("Session:") + restOfLine.setResultsName("SessionLine") For more structure, enclose each line inside Group objects. response = Group( Literal("RTSP") + restOfLine ).setResultsName("RTSPline") + \ Group( Literal("Cseq:") + restOfLine ).setResultsName("CseqLine") + \ Group( Literal("Session:") + restOfLine ).setResultsName("SessionLine") Here is a working (and tested!) sample. -- Paul ========================== from pyparsing import Literal, restOfLine, Group data = """RTSP/1.0 200 OK Cseq: 1 Session: 12345-1 """ print "========" print data print "========" response = Literal("RTSP") + restOfLine.setResultsName("RTSPline") + \ Literal("Cseq:") + restOfLine.setResultsName("CseqLine") + \ Literal("Session:") + restOfLine.setResultsName("SessionLine") respFields = response.parseString(data) print respFields for k in respFields.keys(): print k,"=",respFields[k] =========================== Output: ======== RTSP/1.0 200 OK Cseq: 1 Session: 12345-1 ======== ['RTSP', '/1.0 200 OK', 'Cseq:', ' 1', 'Session:', ' 12345-1'] SessionLine = 12345-1 RTSPline = /1.0 200 OK CseqLine = 1 ============================ Output (using Group'ed constructs): ======== RTSP/1.0 200 OK Cseq: 1 Session: 12345-1 ======== [['RTSP', '/1.0 200 OK'], ['Cseq:', ' 1'], ['Session:', ' 12345-1']] SessionLine = ['Session:', ' 12345-1'] RTSPline = ['RTSP', '/1.0 200 OK'] CseqLine = ['Cseq:', ' 1'] From martin at v.loewis.de Sat May 22 18:48:55 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 May 2004 00:48:55 +0200 Subject: terminological obscurity In-Reply-To: <40aec6ff$0$17254$a1866201@newsreader.visi.com> References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> Message-ID: <40AFD8D7.9090500@v.loewis.de> Grant Edwards wrote: > I think the fact that Python lists can be heterogogenous is one > of the most brilliantly useful things in the language, but > apparently we're not supposed to use lists like that. Since > tuples aren't mutable, I'm completely at a loss as to how we're > supposed to deal with mutable heterogenous sequences. You should define classes. Regards, Martin From tismer at stackless.com Sat May 29 10:44:42 2004 From: tismer at stackless.com (Christian Tismer) Date: Sat, 29 May 2004 16:44:42 +0200 Subject: cPickle bug (was: Saving recursive objects to disc. cPickle wan't work) In-Reply-To: <20040528141128.GC2175@matijek.plusseven.com> References: <20040526142220.GA2289@matijek.v10a.ath.cx> <20040528141128.GC2175@matijek.plusseven.com> Message-ID: <40B8A1DA.1070907@stackless.com> Alex Polite wrote: > On ons, maj 26, 2004 at 02:22:21 +0000, Alex Polite wrote: > >>I need to put recursive data structures on disc and found out that cPickle >>doesn't like recursion. >> >>What are my options? >> >>alex > > > Christian Tismer had the kindness to look at my code and point out > that I might want to use pickle instead of cPickle, at least if I > wanted to benefit from using stackless. Chaning from cPickle to pickle > allowed to run the code under stackless as well as under standard > python. > > thanks Christian. Although I'm happy that things work even without Stackless, this implies that there is an incompatibility between pickle and cPickle. If objects are treated identically by both, that normal Python must use even more stack space for recursive objects that cPickle, so I'd expect it crashes earlier. But it doesn't crash. cPickle must have a bug. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From vincent at visualtrans.de Tue May 18 13:11:51 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 May 2004 19:11:51 +0200 Subject: print / str / repr In-Reply-To: <4mm9a05hjv10vgle5bh07d9bpf2e7sj44b@4ax.com> References: <4mm9a05hjv10vgle5bh07d9bpf2e7sj44b@4ax.com> Message-ID: Nikolai Kirsebom wrote: > How do I (in a program) achieve the same result as using the print > statement (interactive). > > In the interpreter: > > >>>>s = u "some '\xcf' text" >>>>print s > > Traceback (most ....): > UnicodeError: ASCII encoding error: ordinal not in range(128) > >>>>s.encode('latin-1') > > "some '\xcf' text" > >>>>print s.encode('latin-1') > > some '?' text > >>>>`s.encode('latin-1')` > > '"some \'\\xcf\' text"' You mean you want to print/write/store the exact line '"some \'\\xcf\' text"' ? s = u"some '\xcf' text" s = `s.encode('latin-1')` print repr(s.encode('latin-1')) # prints '"some \'\\xcf\' text"' Is this what you're looking for? -- Vincent Wehren From tim.one at comcast.net Thu May 27 02:55:24 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 27 May 2004 02:55:24 -0400 Subject: why learn Message-ID: [mr_vocab] >> hey i finished working through alot of python stuff and no a fair bit >> bout it >> >> now what can i do with it??? [Tim] > Follow your bliss: in your case, it looks like you'd really enjoy writing > a program to post the same question 100 times. It's a lot easier to write > a program for that than to stay up all night doing it by hand . Oops! My apologies! That wasn't you. A particularly nasty piece of spam wedged my ISP, and your message was immediately before it: every time I downloaded mail, I got your message again, and then the connection died while trying to transfer the ill-formed spam. Anyway, following your bliss remains sincere if cryptic advice. What are you interested in? What do you love? If you're not using Python for your job (and sometimes even if you are ...), those are the questions to answer first. Python will then fit in or won't. You can use Python for anything a computer has ever been used for, and for a boundless number of things nobody has thought of yet. What do you care about? From asdf at asdf.com Mon May 3 18:20:42 2004 From: asdf at asdf.com (asdf sdf) Date: Mon, 03 May 2004 22:20:42 GMT Subject: Experience with vb2py? Message-ID: <_Azlc.44378$r37.39639@newssvr29.news.prodigy.com> vb2py sounds terric but i don't want to be the first guineau pig who gambles his project on it. i have a large VB project lying around that may have to be upgraded. i would love to see it go to python. anybody have experience with vb2py, the vb to python converter? how solid is it? how complete? my VB project use custom controls, is a multi-tier ActiveX project, with a custom (non-ASP) architecture, using sockets and a COM component on IIS. is vb2py ready for this scale? i see that vb2py converts to pythoncard. that raises concerns because i'm not aware that pythoncard is suitable for large, complex, multipage forms containing hundreds of controls. can vb2py handle that kind of conversion? From ptmcg at austin.rr._bogus_.com Fri May 14 11:22:42 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 14 May 2004 15:22:42 GMT Subject: Troubles with CSV file References: Message-ID: <6v5pc.107833$hR1.1658@fe2.texas.rr.com> "Vladimir Ignatov" wrote in message news:mailman.8.1084529146.4157.python-list at python.org... > Hello! > > I have a big CSV file, which I must read and do some processing with it. > Unfortunately I can't figure out how to use standard *csv* module in my > situation. The problem is that some records look like: > > ""read this, man"", 1 > > which should be decoded back into the: > > "read this, man" > 1 > > ... which is look pretty "natural" for me. Instead I got a: > > read this > man"" > 1 > > output. In other words, csv reader does not understand using of "" here. > Quick experiment show me that *csv* module (with default 'excel' dialect) > expects something like > > """read this, man""", 1 > > in my situation - quotes actually must be trippled. I don't understand this > and can't figure out how to proceed with my CSV file. Maybe some > *alternative* CSV parsers can help? Any suggestions are welcomed. > > Vladimir Ignatov > > Vladimir - Here is the CSV example that is provided with pyparsing (with some slight edits). I wrote this for exactly the situation you describe - just splitting on commas doesn't always do the right thing. You can download pyparsing at http://pyparsing.sourceforge.net . -- Paul ========================== # commasep.py # # comma-separated list example, to illustrate the advantages of using # the pyparsing commaSeparatedList as opposed to string.split(","): # - leading and trailing whitespace is implicitly trimmed from list elements # - list elements can be quoted strings, which can safely contain commas without breaking # into separate elements from pyparsing import commaSeparatedList import string testData = [ "a,b,c,100.2,,3", "d, e, j k , m ", "'Hello, World', f, g , , 5.1,x", "John Doe, 123 Main St., Cleveland, Ohio", "Jane Doe, 456 St. James St., Los Angeles , California ", "", ] for line in testData: print "input:", repr(line) print "split:", line.split(",") print "parse:", commaSeparatedList.parseString(line) print ========================== Output: input: 'a,b,c,100.2,,3' split: ['a', 'b', 'c', '100.2', '', '3'] parse: ['a', 'b', 'c', '100.2', '', '3'] input: 'd, e, j k , m ' split: ['d', ' e', ' j k ', ' m '] parse: ['d', 'e', 'j k', 'm'] input: "'Hello, World', f, g , , 5.1,x" split: ["'Hello", " World'", ' f', ' g ', ' ', ' 5.1', 'x'] parse: ["'Hello, World'", 'f', 'g', '', '5.1', 'x'] input: 'John Doe, 123 Main St., Cleveland, Ohio' split: ['John Doe', ' 123 Main St.', ' Cleveland', ' Ohio'] parse: ['John Doe', '123 Main St.', 'Cleveland', 'Ohio'] input: 'Jane Doe, 456 St. James St., Los Angeles , California ' split: ['Jane Doe', ' 456 St. James St.', ' Los Angeles ', ' California '] parse: ['Jane Doe', '456 St. James St.', 'Los Angeles', 'California'] input: '' split: [''] parse: [''] From asdf at asdf.com Fri May 7 01:41:09 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 07 May 2004 05:41:09 GMT Subject: Newbie : Greek letters In-Reply-To: <8KDmc.45741$Sf4.40969@newssvr29.news.prodigy.com> References: <8KDmc.45741$Sf4.40969@newssvr29.news.prodigy.com> Message-ID: You reminded me that I would find this handy myself so I set up a program to display greek letters. Pay no attention to the sizer handling. Working on that. sorry if the mailer munges the linewrapping. shouldn't be a biggie in a script this small. good luck. # # greek.py # import wx import string class Greek(wx.Frame): ''' greek alphabet ''' alphabet = string.ascii_letters def __init__ (self, parent, id, title): wx.Frame.__init__(self, parent, id, title) # wx.Font(points, family, style, weight, face='') romanfont = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.NORMAL) greekfont = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.NORMAL, face='SYMBOL') gs = wx.GridSizer(-1, 10, 5, 5) roman = [] greek = [] textstyle = wx.ALIGN_CENTER|wx.ST_NO_AUTORESIZE cellstyle = wx.EXPAND for x in range(len(Greek.alphabet)): letter = Greek.alphabet[x] roman.append(wx.StaticText(self, -1, letter ,wx.Point(-1,-1), wx.Size(-1,-1), textstyle)) roman[x].SetFont(romanfont) roman[x].SetBackgroundColour('Yellow') greek.append(wx.StaticText(self, -1, letter ,wx.Point(-1,-1), wx.Size(-1,-1), textstyle)) greek[x].SetFont(greekfont) greek[x].SetBackgroundColour('White') gs.Add(roman[x], 1, cellstyle, 10) gs.Add(greek[x], 1, cellstyle, 10) # layout sizers self.SetSizer(gs) self.SetAutoLayout(1) gs.Fit(self) self.Show(True) app = wx.PySimpleApp() frame = Greek(None, -1, 'Greek Alphabet') app.MainLoop() # ------------------------------------- # greek.py - end of file # ------------------------------------- From peter at engcorp.com Mon May 31 09:24:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 May 2004 09:24:19 -0400 Subject: exceptions In-Reply-To: References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: Zunbeltz Izaola wrote: > Peter Hansen writes: >>Zunbeltz Izaola wrote: >> >>>I've the following problem with try/exception. >>>I've a try block that will raise some exceptions. >>>I want the program to ignore this exceptions completely. Is it >>>possible? >> >>In the following, all exceptions will be ignored: >> >>try: >> # something that raises exceptions >>except: >> pass > > I've trid this, but the problem is that this finished the try block. > I want to continue executing the try block from the point the > exception was raised. Not possible except, perhaps, with a significant amount of working involving sys.settrace(). I think you need to find another way to solve the problem. What you are trying to do is not something that other people who do unit testing seem to have to do. Why do you think you need to actually *disable* exceptions entirely in order to test this code? Perhaps the code needs to be restructured? -Peter From dmq at gain.com Tue May 11 06:58:39 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 11 May 2004 03:58:39 -0700 Subject: Ideas for Python 3 References: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> Message-ID: <2r91a0tlksovkn20maa7mk5vekr8h2joa5@4ax.com> On Mon, 10 May 2004 20:41:24 -0700, Josiah Carlson wrote: >I've read the link you posted, and I've previously taken a look at >Prothon. Prototype syntax does not suit my taste in programming >languages. If Python 3.0 becomes Prothon, I'll fork the most recent >Python 2.x codebase that I prefer, maintaining it myself if necessary. > >Just as my anti-prototype perspective colors my opinions on what is >reasonable, I would imagine that your pro-prototype perspective colors >yours. I am currently neutral on the idea of prototypes, still waiting for anyone to show me a good use case, so I can include it in my webpage. I still have "cloning" of instances in my proposal, but you will notice they are at the bottom of the list of benefits at http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm I typically get enthusiastic about something when I first see it, then I learn a little more, and some of the new tricks/features drop to the bottom of my list. What remains of my original enthusiasm for Prothon is still in the unification of methods and functions. The main thing that changed my mind on the need for Prothon-like prototypes is Michele Simionato's posting on 4/28/04 "Prototypes in Python". If anyone is seriously interested in prototyping, they can do it in Python right now, using Michele's 'prototype.py' module. Until we get some actual users with a demonstrated need, I'm not pushing for anything beyond the current module. The key to finding what is fundamentally good in these other languages, and what is just someone's personal preference for being different, is keeping an open mind. It's astonishing how few people can do that in comparing computer languages. I guess it is just easier to be "anti" or "pro" and skip the investigation and thinking. >I would also expect that someone who enjoys using lisp or >perhaps SML would have their opinion on what is reasonable, colored by >their preferences. Considering that Python is not a prototype-based >language today in 2.3 (or the forthcoming 2.4 in the fall), having it >become one in Python 3 would be quite a drastic change, quite literally >like going from Python 2.3 to Prothon. I continue to find new surprises in Python. The ability to change classes into prototypes by using descriptors is the latest exammple. This seems like a drastic change, but it is all within the capability of Python. Prothon does have some changes that are more drastic, but in my opinion have no real benefit over Python. I measure drastic by how much effort it will take to translate existing Python programs to Prothon. By this measure, the unification of functions and methods is not a drastic change. I believe it will be possible to automatically translate all Python methods into the new form. So if we categorize syntax changes as ( Compatible / Migratable / Totally Different ), the proposed changes are in the middle. -- Dave From wojsal1 at gazeta.pl Tue May 18 07:21:17 2004 From: wojsal1 at gazeta.pl (WOJSAL) Date: Tue, 18 May 2004 13:21:17 +0200 Subject: beginner - viewer HTML-text with TkInter Message-ID: I want show HTML-text (messages, textarea etc.) with TkInter. What free package, module i need? Please help. -- Regards WOJSAL http://www.wojsal.prv.pl From troy at gci.net Thu May 20 06:16:16 2004 From: troy at gci.net (Troy Melhase) Date: Thu, 20 May 2004 02:16:16 -0800 Subject: GTK or TKinter (or what else?) In-Reply-To: References: Message-ID: <200405200216.16199.troy@gci.net> On Wednesday 19 May 2004 11:57 pm, Marco Terzuoli wrote: > I use python under linux and would like to create some GUI applications. Consider PyQt and/or PyKDE. You can get both from Riverbank: http://riverbankcomputing.co.uk/ The reasons I like using these two, in no particular order: Quality: Qt and KDE are both very well designed Docs: Everything is documented Polish: Most things are consistent Tools: The GUI designer is awesome Platforms: Reasonable portability to Mac and Windows Quantity: More widgets than you can shake a stick at -- Troy Melhase, troy at gci.net -- It is terrible to contemplete how few politicians are hanged. - G. K. Chesterton From winexpert at hotmail.com Wed May 26 09:39:38 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 26 May 2004 13:39:38 +0000 Subject: re best way to enumerate something in Python Message-ID: I'm going to try using the range function. as in: ID_COL, ANIMAL_COL, HOUSING_COL = range(3) This appears to assign assign those vars as 'constants' with values of 0,1,2 David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From no.email at please.invalid Tue May 4 13:22:08 2004 From: no.email at please.invalid (Guido) Date: Tue, 04 May 2004 17:22:08 GMT Subject: curses and python (linux, debian) In-Reply-To: References: Message-ID: <4jQlc.95615$YC1.6104179@phobos.telenet-ops.be> David M. Cooke wrote: > At some point, Guido wrote: > > >>Hello >> >>I'm new to python and i'm trying to write a script that shows a menu. >> >>Now, I have some troubles with curses.setsyx() >> >>I do: >> >>import curses >> >>curses.setsyx(2, 20) >>curses.putp("TEST TITLE") >>curses.setsyx(25, 35) >>curses.putp("TEST CENTER") >>curses.setsyx(12, 35) >>curses.putp("TEST CENTER") >> >>but it just prints all the string after each other at the first >>lines.. > > > Er, that's really the wrong way to do it. For one thing, curses.putp > doesn't do what you think you want it to do. Have a look at "Curses > Programming with Python": > http://www.amk.ca/python/howto/curses/ > > Something like this: > > import curses > > def main(stdscr): > stdscr.addstr(2, 20, "TEST TITLE") > stdscr.addstr(25,35, "TEST CENTER") > stdscr.addstr(12,35, "TEST CENTER") > while 1: > c = stdscr.getch() > if c == ord('q'): > return > > curses.wrapper(main) > thx very much very handy tutorial! Now, i'm using DrPython, it looks fine, but i can't debug my curses program It gives an error with this message: curses.wrapper returned ERR on curses.cbreak if i run it with python, it works! anybody? From apardon at forel.vub.ac.be Wed May 12 07:23:04 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 May 2004 11:23:04 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> Message-ID: Op 2004-05-10, Greg Ewing schreef : > Antoon Pardon wrote: >> IMO having operators that should work in place for object that >> are immutable, sound contradictory. Having the following code: > > But restricting += etc. to work only on mutables would > mean you wouldn't be able to do things like > > x = 42 > x += 1 > > which is a very handy thing to be able to do. But it creates confusions because the semantics is not consistent. IMO lacking an assignment that copies the value of one object into another was a mistake and which creats IMO a lot of difficulties. If I have a function with an object as a paramter. and this object is mutable. Now within this function I find a second object with the value I want the argument to have. Now I can't simply copy the second object over the argument but I have to copy attribute by attribute from the second object into the argument. -- Antoon Pardon From tdelaney at avaya.com Mon May 31 02:03:57 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 31 May 2004 16:03:57 +1000 Subject: API : constness ? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0188091B@au3010avexu1.global.avaya.com> Beno?t Dejean wrote: > Le Mon, 31 May 2004 11:56:57 +1000, Delaney, Timothy C (Timothy) a > ?crit?: > >> Beno?t Dejean wrote: > >>> static const char * const kwlist[] = { "uri", "open_mode", >>> "exclusive", "perm", NULL }; >> >> Does this give any performance or size improvement? > > of course, it avoids a lot of relocation, reduces load time, and > manque the compiler to make further informations because data will be > in a readonly segment. it is safe to apply this kind of change to > static data. I hope it does work out that there are improvements (anything to stop Guido getting a pie in the face ;) but I also expect those improvements to be marginal. Hope I'm wrong :) I was just wondering how smart GCC (and MSVC) are about this. As you state, the real value of this would be to extension writers not having to cast (and hence having cleaner code). > my first goal is const correctness, i don't know if i can show > something. it will just remove warnings and move data to the text > segment, etc Anything that gets rid of warnings *correctly* is IMO a Good Thing(TM). Tim Delaney From CousinStanley at HotMail.Com Sat May 15 18:57:47 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Sat, 15 May 2004 15:57:47 -0700 Subject: Where do I find what colors and fonts are available? References: <40A3FD3E.B1B71DA8@shaw.ca> Message-ID: On Thu, 13 May 2004 22:56:44 GMT, SeeBelow at SeeBelow.Nut wrote: > I'm learning Tkinter, from Grayson's book and some online sources. > > I don't know how to find out which color names and font names are > available on my system. I'm using Windows 2000. I assume that info is > in some file or files somewhere, buy I don't know the file name or > directory. > > Thanks, > > Mitchell Timin Mitchell .... For a list of fonts in Tkinter, you might try .... import Tkinter import tkFont root = Tkinter.Tk() list_fonts = list( tkFont.families() ) list_fonts.sort() for this_family in list_fonts : print this_family For a list of colors in Tkinter check the list at .... http://www.tcl.tk/man/tcl8.3/TkCmd/colors.htm -- Cousin Stanley Human Being Phoenix, Arizona From peter at engcorp.com Wed May 26 07:08:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 07:08:50 -0400 Subject: Bad interpreter In-Reply-To: References: Message-ID: BaBS wrote: > I've a problem whith my python script, > i chmod'ed it to +x, addes the line : > #!/usr/bin/python2.3 > and i verified that /usr/bin/python2.3 exists > but i've something like > : bad interpreter: No such file or dir ... > > What's the matter ?? Remove the hidden CR character which you got at the end of the lines by moving the file to a Windows system and editing it. ;-) This one is pretty tricky to figure out the first few times... -Peter From cappy2112 at yahoo.com Mon May 17 21:37:12 2004 From: cappy2112 at yahoo.com (Tony C) Date: 17 May 2004 18:37:12 -0700 Subject: how to run an arbitrary function with timeout? References: <2004051413541084557280@k2.sage.att.com> <140520041613369125%mday@apple.com> Message-ID: <8d3e714e.0405171737.58fd641d@posting.google.com> jbore at tjtech.com (Joseph T. Bore) wrote in message news:... > Mark Day writes: > > In article <2004051413541084557280 at k2.sage.att.com>, Garry Hodgson > > wrote: > import signal > > # > # a alarm signal handler > # > def alarmHandler(signum, frame): > raise TimeExceededError, "Your command ran too long" > > # > # a function that would run for too long > # > def infinite(): > while 1: > pass > return > > # > # set the alarm signal handler, and set the alarm to 1 second > # > signal.signal(signal.SIGALRM, alarmHandler) > signal.alarm(1) This is a very interesting solution. However, signal.alarm() and signal.SIGALRM are not defined in my signal module I'm using 2.3.3 From arkon at ragestorm.net Mon May 3 15:27:18 2004 From: arkon at ragestorm.net (Arkon) Date: 3 May 2004 12:27:18 -0700 Subject: Bug in PyCallable_Check References: Message-ID: Heiko Wundram wrote in message news:... > Am Montag, 3. Mai 2004 13:39 schrieb Arkon: > > And then the PyCallable_Check won't *detect* that it's not a real > > function(pointer) passed...then later when you intend to run that > > function, you get an error. > > PyCallable_Check does as it is told, it checks whether the argument can be > called. > > There are loads of callable things in Python, method references being just one > of them. A class is callable (instantiation or overridden __metaclass__ or > the like), an instance is callable (using the __call__ method of the class), > and many other things too. What you're seeing (complaining about) is that > types are nothing else than classes, and so they are callable too. > > If you really have to check that it is a function, you'll have to check the > type of the reference for types.FunctionType. > > HTH! > > Heiko. Well, I wasn't sure from the beginning, but thanks for making it clear to me, I haven't thought of it in that way! As for Diez B. Roggisch example I get "TypeError: cannot create 'function' instances"... Arkon From mariube+netnews+ at ifi.uio.no Thu May 20 17:03:18 2004 From: mariube+netnews+ at ifi.uio.no (Marius Bernklev) Date: Thu, 20 May 2004 23:03:18 +0200 Subject: stat module In-Reply-To: (Gian Mario Tagliaretti's message of "Thu, 20 May 2004 22:47:51 +0200") References: Message-ID: <3cfsmdu24mh.fsf@kolme.ifi.uio.no> Gian Mario Tagliaretti writes: > I've tried to read very carefully the manual and the module > description but there is something that probably I don't understand 644 is base8. 420 is base10. Marius -- "Who needs crypto WYCWLT?" -- William Newman From tertius at localhost Mon May 24 16:37:25 2004 From: tertius at localhost (tertius) Date: Mon, 24 May 2004 22:37:25 +0200 Subject: jython 2 cpython bridge In-Reply-To: <8dssc.179150$f_5.163363@lakeread01> References: <8dssc.179150$f_5.163363@lakeread01> Message-ID: <2K-dnTPc2L5gxy_dRVn-jw@is.co.za> Randall Smith wrote: > I would like to use a type 4 JDBC driver in my Python program. I > believe I can use in with Jython. Do you know of some way to > communicate between the Jython and Python processes so that the CPython > program can use the Jython JDBC database connection? > > Randall Write the application using Jython. Then use SimpleXMLRPCServer on the Jython side to register the necessary functions for an XML-RPC client written in Python. HTH T From dygimailNo at SPAMpoczta.fm Thu May 20 08:12:09 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 20 May 2004 12:12:09 GMT Subject: Unknown Tkinter bug Message-ID: Hi all Like i said, i'am back. With another problem of course. This is my code: ---BEGIN win=Tkinter.Tk() can=Tkinter.Canvas(win,width=500,height=500,background='blue') can.pack() # creating main lines can.create_rectangle(10,10,490,490) can.create_line(25,225,485,225) can.create_line(250,470,250,20) can.create_polygon((245,20),(250,10),(255,20)) can.create_polygon((475,230),(485,225),(475,220)) can.create_text(460,250,text='dV [m3]') can.create_text(280,25,text='dU [J]') # creating sublines while x<450 or y<450 : can.create_line((30+x,220),(30+x,225),(30+x,230)) can.create_line((245,25+y),(250,25+y),(255,25+y)) x=x+10 y=y+10 # starting drawing function image for i in range(0,len(deV)): can.create_oval(250+deV[i],250-deU[i],250+deV[i]+1, 250-deU[i]+1,width=3,outline='white') for i in range(0,len(deV)-1): can.create_line(250+deV[i],250-deU[i],250+deV[i+1], 250-deU[i+1],width=1,fill='yellow') # creating etiquettes can.create_text(250+200,210,text=int(maxdeV),fill='white') can.create_text(250+10,250-200,text=int(maxdeU),fill='white',anchor='w') can.create_text(250-200,240,text=int(mindeV),fill='white') can.create_text(250-30,250+200,text=int(mindeU),fill='white',anchor='s') win.mainloop() ---END After i close graphcial window, shell gives this error message: ---BEGIN Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python232\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Program Files\Python232\lib\idlelib\ScriptBinding.py", line 157, in run_module_event interp.runcode(code) File "C:\Program Files\Python232\lib\idlelib\PyShell.py", line 658, in runcode self.interp.restart_subprocess() AttributeError: ModifiedInterpreter instance has no attribute 'interp' ---END Where should i look for a mistake? -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From dmq at gain.com Tue May 18 06:26:56 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 18 May 2004 03:26:56 -0700 Subject: Unification of Methods and Functions References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> Message-ID: On Mon, 17 May 2004 16:40:00 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> James has been telling me it is terribly wrong to keep data as >> attributes of classes > >There's nothing inherently wrong with that, as long as >you're certain you will only ever want one instance of that >piece of data. > >In my chip example, you might want to keep a count of the >total number of transistors in your chip as a class variable >of the Transistor class. But that only works if your program >only ever deals with one chip at a time. If there can be more >than one chip, then you'll need a Chip class whose instances >either keep a count of Transistors contained in that chip, >or have a method that can compute the count when needed. > >Even if you think you will only deal with one chip at a >time, it would be good design practice to plan on having >a Chip class anyway, in case the requirements change. The >amount of work involved is about the same either way, and >the design which avoids class variables is more flexible. This makes a lot more sense than a total ban on data in classes. I think the generalization to a "multi-zoo" program probably belongs in the third example, along with perhaps some techniques like James showed to make the code more robust by generating the classes rather than writing them. The first and second examples ( Animals_1 and Animals_2 need to be very simple. -- Dave From jepler at unpythonic.net Sat May 15 09:03:50 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 08:03:50 -0500 Subject: problem with regular expression? In-Reply-To: <6A4549342FC81B45B1C86E10C7AFC71C114222@cobra.corp.es.com> References: <6A4549342FC81B45B1C86E10C7AFC71C114222@cobra.corp.es.com> Message-ID: <20040515130350.GB434@unpythonic.net> I get similar behavior with a slightly simpler program on my system. $ cat /tmp/kbaum.py import re pat = re.compile(r'(a)?(b)') hay = "a b" m = pat.search(hay) if m: print m.groups() print [m.span(i) for i in range(3)] $ python2.2 /tmp/kbaum.py ('a', 'b') [(2, 3), (0, 1), (2, 3)] $ python2.3 /tmp/kbaum.py (None, 'b') [(2, 3), (-1, -1), (2, 3)] I tested on these versions: 2.2.2 (RedHat 9): Buggy 2.2.3 (Fedora Core 1): Buggy 2.3.2 (RedHat 9): Correct 2.3.4 CVS (Fedora Core 1): Correct so this bug has been fixed in newer versions of Python, at least for my simplified regular expression. If it's been fixed for the expression you're using, then you should upgrade if you can. Otherwise, you should create a bug report on http://sourceforge.net/projects/python/ with the expression that still doesn't work. Jeff From SeeBelow at SeeBelow.Nut Wed May 26 13:37:09 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 26 May 2004 17:37:09 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <40b4baf9$0$2104$afc38c87@news.easynet.co.uk> Message-ID: <40B4D5E2.C64779DF@shaw.ca> Peter Hickman wrote: > > SeeBelow at SeeBelow.Nut wrote: > > I see the value of a class when two or more instances will be created, > > but Python programmers regularly use a class when there will only be one > > instance. > > This is a lot like putting code in functions. "Its only called in one place, why put it in a function, why not just leave it where it is?" I had a conversation with a dBase > programmer many years ago on just these lines and what it came down to was this. > > for x = 1 to length(orderitems) > calculate_tax(orderitems[x], .175) > next > > (forgive the pseudo code) is easier to read and the intent of the code is much clearer, and also we had 24 * 80 screens and so you could see much more of the 'flow' of the program > than if the code was in lined. Objects just take all that one step further. > > order.calculate_tax( .175 ) > > Why read fifty lines of code to work out that tax is being calculated for each item in the order when you can read one line? How you achieve this is not all that important, functions > or classes only that the flow of the program can be comprehended quickly. I see the value of replacing many lines of code by a function definition, for readability, even if that only happens once. In fact I regularly do this. But does using a class acheive this better than a function? It seems to me that a function is simpler and clearer. m -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From ggg at zzz.it Fri May 14 04:11:39 2004 From: ggg at zzz.it (deelan) Date: Fri, 14 May 2004 10:11:39 +0200 Subject: Retrieve Email Attachments In-Reply-To: <7b454334.0405131902.60550e4c@posting.google.com> References: <7b454334.0405131902.60550e4c@posting.google.com> Message-ID: <62328c.l5b.ln@news1.interplanet.it> Fazer wrote: > Hello, > > I need to access a POP or mayb IMAP based email account and extract > attachments (probably images) from the email messages. How can this > be done with the current two module libraries? i've posted an example script non too long ago: cheers, deelan -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From pruggera at san.rr.com Sat May 22 14:08:32 2004 From: pruggera at san.rr.com (Phil) Date: Sat, 22 May 2004 18:08:32 GMT Subject: COM server being passed an instance of an interface References: <40ae9a20_5@127.0.0.1> Message-ID: Hi Roger, Thanks for the help. So now the program looks like: import win32com.client class HelloWorld: _reg_clsid_ = "{4E797C6A-5969-402F-8101-9C95453CF8F6}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Hello'] _public_attrs_ = ['softspace', 'noCalls'] _readonly_attrs_ = ['noCalls'] def __init__(self): self.softspace = 1 self.noCalls = 0 def Hello(self, WL ): # In VB this looks like Public Sub Hello(ByVal objWL As WealthLab.IWealthLabAddOn3) WL = win32com.client.Dispatch(WL) self.noCalls = self.noCalls + 1 # insert "softspace" number of spaces return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) The Python Trace Collector gives me: Object with win32trace dispatcher created (object=None) in _GetIDsOfNames_ with '('Hello',)' and '2048' in _Invoke_ with 1002 0 3 () Traceback (most recent call last): File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 40, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, in _invokeex_ return func(*args) File "G:\Python\Dev\COM Server - win.py", line 27, in Hello return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .BarCount pythoncom error: Python error invoking COM method. Traceback (most recent call last): File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 129, in _Invoke_ return DispatcherBase._Invoke_(self, dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 42, in _Invoke_ self._HandleException_() File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 107, in _HandleException_ reraise() File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line 40, in _Invoke_ return self.policy._Invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, in _Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, in _invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, in _invokeex_ return func(*args) File "G:\Python\Dev\COM Server - win.py", line 27, in Hello return "Hello" + " " * self.softspace + str(self.noCalls) + str(WL.BarCount()) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) exceptions.AttributeError: .BarCount in _Invoke_ with 0 1024 2 () in _Invoke_ with 0 1024 2 () "Roger Upole" wrote in message news:40ae9a20_5 at 127.0.0.1... > You ought to be able to do > win32com.client.Dispatch(WL) > to get a usable com object. > hth > Roger > > "Phil" wrote in message > news:rXsrc.542$wO4.145 at twister.socal.rr.com... > > I am using a Pascal like language (Wealth-Lab) on W2K and call this > server: > > > > class HelloWorld: > > _reg_clsid_ = "{4E797C6A-5969-402F-8101-9C95453CF8F6}" > > _reg_desc_ = "Python Test COM Server" > > _reg_progid_ = "Python.TestServer" > > _public_methods_ = ['Hello'] > > _public_attrs_ = ['softspace', 'noCalls'] > > _readonly_attrs_ = ['noCalls'] > > > > def __init__(self): > > self.softspace = 1 > > self.noCalls = 0 > > > > def Hello(self, WL ): # WL is an instance of a interface class that > > exists in the client > > # In VB this would look like Public Sub Hello(ByVal objWL As > > WealthLab.IWealthLabAddOn3) > > self.noCalls = self.noCalls + 1 > > # insert "softspace" number of spaces > > return "Hello" + " " * self.softspace + str(self.noCalls) + > > str(WL.BarCount()) > > > > if __name__=='__main__': > > import win32com.server.register > > win32com.server.register.UseCommandLine(HelloWorld) > > > > How do I get the instance of the interface to have its methods? The > Python > > Trace Collector gives me: > > > > Object with win32trace dispatcher created (object=None) > > in _GetIDsOfNames_ with '('Hello',)' and '2048' > > > > in _Invoke_ with 1002 0 3 ( 0x331ea00>) > > Traceback (most recent call last): > > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > > 40, in _Invoke_ > > return self.policy._Invoke_(dispid, lcid, wFlags, args) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 283, > > in _Invoke_ > > return self._invoke_(dispid, lcid, wFlags, args) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 288, > > in _invoke_ > > return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, > None) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 550, > > in _invokeex_ > > return func(*args) > > File "G:\Python\Dev\COM Server - win.py", line 27, in Hello > > return "Hello" + " " * self.softspace + str(self.noCalls) + > > str(WL.BarCount()) > > AttributeError: 'PyIDispatch' object has no attribute 'BarCount' > > pythoncom error: Python error invoking COM method. > > Traceback (most recent call last): > > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > > 129, in _Invoke_ > > return DispatcherBase._Invoke_(self, dispid, lcid, wFlags, args) > > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > > 42, in _Invoke_ > > self._HandleException_() > > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > > 107, in _HandleException_ > > reraise() > > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > > 40, in _Invoke_ > > return self.policy._Invoke_(dispid, lcid, wFlags, args) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 283, > > in _Invoke_ > > return self._invoke_(dispid, lcid, wFlags, args) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 288, > > in _invoke_ > > return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, > None) > > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line > 550, > > in _invokeex_ > > return func(*args) > > File "G:\Python\Dev\COM Server - win.py", line 27, in Hello > > return "Hello" + " " * self.softspace + str(self.noCalls) + > > str(WL.BarCount()) > > exceptions.AttributeError: 'PyIDispatch' object has no attribute > 'BarCount' > > in _Invoke_ with 0 1024 2 () > > in _Invoke_ with 0 1024 2 () > > > > > > From jjl at pobox.com Wed May 12 16:14:19 2004 From: jjl at pobox.com (John J. Lee) Date: 12 May 2004 21:14:19 +0100 Subject: Qt, multiple inheritance: QApplication and new-style class not possible References: <2geeh2F1vag1U1@uni-berlin.de> Message-ID: <87u0yltnc4.fsf@pobox.com> Sibylle Koczian writes: [...] > a) use SIP v4, but it's pre-release. Moreover I'm just starting with [...] I'd say the acceptability of this depends on what kinds of people the program needs to be distributed to -- yourself being a special case of distributee :-) If I know I'll never distribute something, or won't for, say, a year or so, I feel few qualms about using new code. Depends what people have said about the stability of the code, of course, but I'd be surprised if Phil Thompson's pre-release code was bug-ridden. > Linux anyway, so I'd like to keep to ready-made rpm packages for my > distribution (SuSE 9.1) and I can't find any. If you want to get into good habits, you could make your own rpm by copying the spec files from old sip / PyQt packages -- it's not too hard, I'm told. Personally, I have slovenly habits and just compile from the original tarball when it's not on a distro CD or automatically fetch-able with dependencies (using apt-get, in my case). > b) make MyAppClass a classic class. A shame to lose properties, assuming you have a good use for them. > c) instead of deriving my QAppClass from QApplication and from > MyAppClass, derive it only from QApplication and put a reference to a > MyAppClass instance into it as an attribute. > > What's the best way (and why), c). :-) > or is there a d)? Surely. John From dpharris76 at msn.com Tue May 25 08:42:26 2004 From: dpharris76 at msn.com (Dave Harris) Date: Tue, 25 May 2004 12:42:26 +0000 Subject: Tkinter - One Canvas to Rule Them All? Message-ID: Fredrik Lundh wrote: > >>Dave Harris wrote: >> >>I derived two Frame classes and created a Canvas in each. I was extremely >>surprised when frame1.canvas.delete('all') erased the image in >>frame2.canvas! >> >>I deduce from this behavior that there is a single database behind the >>scenes for the Canvas implementation. >nope. that's not how the canvas work, in any Tkinter version I've ever >used. >reminds me a little of all those "here's something I don't understand, so >it has >to be a bug in Python" posts we're seeing these days... Thanks for the gentle reminder. And thanks to Peter Otten for requesting an example. When I culled the code down to a one page example, the behavior described above did not occur. Then I went back to my code, restored the delete('all'), and the behavior did not occur. Hmm. Working back through my changes I found that I had cloned the two Frame classes, including a clearAll() function, that contained (you're way ahead of me, I know), delete('all'). Where I got mystified is that at some point in time, I removed the clearAll() from one class because I wanted the graphic elements in that canvas to be preserved. The fact that deletion by tag seemed to work was that the change was made at the same time clearAll() disappeared. So, a retraction...Tkinter.Canvas works as advertised, and only a fool makes a deduction on a single incident. Foolishly, Dave Harris From miki.tebeka at zoran.com Tue May 4 02:59:35 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 04 May 2004 08:59:35 +0200 Subject: Distributing a Python App In-Reply-To: <109dom0k7mqqu95@corp.supernews.com> References: <109dec4c2bdn38e@corp.supernews.com> <4096cf70$0$568$e4fe514c@news.xs4all.nl> <109dom0k7mqqu95@corp.supernews.com> Message-ID: <40973F57.8040309@zoran.com> Hello Allan, > I'm looking to records detailing network status, which will be updated > frequently. I then want to be able to retrieve and sort the data to > present reports based on that data. If you want a minimal database try metakit (http://www.equi4.com/metakit.html) which has good Python bindings and it's only one dll. > I'm guessing I could use some sort of tool to package the > python app and PySQLite into one nice tidy package which the end user > could then install? py2exe, cx_Freeze, Installer ... IMO py2exe seems to be the most active. HTH. Miki From goodger at python.org Mon May 3 08:44:50 2004 From: goodger at python.org (David Goodger) Date: Mon, 03 May 2004 08:44:50 -0400 Subject: Embedded comments in Python? In-Reply-To: <5b42ae4.0405030330.5bba90f5@posting.google.com> References: <5b42ae4.0405030330.5bba90f5@posting.google.com> Message-ID: <40963EC2.5000308@python.org> Ernie wrote: > Whats the legal way in Python to embed comments in Python code? > Example: > > def foo(a <:int>, b <:float>): <:array> > return [a, b] def foo(a, #int b #float ): #array return [a, b] Or better yet, put it all in a docstring: def foo(a, b): """Given an int and a float, returns an array of [int, float].""" return [a, b] > In C/C++, this would be no problem with /* */. This is not C/C++. In Python, comments begin with a "#" and end at the end of the line. That's it. -- David Goodger From no.mail at available.net Tue May 11 18:32:09 2004 From: no.mail at available.net (Georgy) Date: Tue, 11 May 2004 22:32:09 GMT Subject: CGI Proplem displaying image References: Message-ID: "matthiasjanes" wrote in message news:d588131f.0405102237.15106ea5 at posting.google.com... > matthiasjanes at gmx.net (matthiasjanes) wrote in message > news:... > > BUT What I want is that I display the image on an HTML page with text > together. You should have a script (if you don't want to have two different scripts), which would return an image or a page depending on its parameters, something like http://your.site.net/cgi-bin/witty_page.py?action=page to return """ ...... Content-type: plain/text\n\n ...... ...... """ and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture. As an example, please have my counter script. It can return either a picture, or a page: a 1x1 pix. picture when counting pages (...?site=999&actn=incr) or an html page with the visitors list (...?site=999&actn=list). Regards, Georgy #!C:\Apps\Python\python.exe import sys, os def read_counter( file_name ): counter = "0" if os.access( file_name, os.R_OK|os.W_OK ): f = open( file_name, "rt" ) if f: counter = f.read().strip() if counter == '': counter = "0" f.close() return counter def write_counter( file_name, counter ): f = open( file_name, "wt" ) if f: f.write( counter ) f.close() file_cnt = "counter/c_nn_%04d.dat" # i.e. in cgi-bin/counter/ file_ips = "counter/c_ip_%04d.dat" file_dsc = "counter/c_descr.dat" def show_list( site, name ): file_cnt_name = file_cnt % site file_ips_name = file_ips % site counter = read_counter( file_cnt_name ) f = open( file_ips_name, "rt" ) if not f: raise ValueError lines = f.readlines() f.close() style = "" title = "Visits to %s" % name sys.stdout.write( "Content-type: text/html\n\n" ) # yield html sys.stdout.write( "%s%s" % (style,title) ) sys.stdout.write( "%s visits to %s" "

\n" % (counter,name) ) sys.stdout.write( "\n" % ('Date','Time','IP') ) try: gray = False for ln in lines: ln = ln.strip() if not ln: continue dt,tm,ip = ln.split() if ip == '217.77.77.77': ip = 'my friend 1' elif ip == '218.88.88.88': ip = 'my friend 2' if gray: bg = "#E0E0E0" else: bg = "#FFFFFF" gray = not gray sys.stdout.write( "\n" % ( bg,dt,tm,ip ) ) except Exception,e: sys.stdout.write( "%s" % e ) sys.stdout.write( "" ) sys.stdout.close() def do_count( site ): # returns image file_cnt_name = file_cnt % site file_ips_name = file_ips % site counter = read_counter( file_cnt_name ) counter = str(int(counter)+1) write_counter( file_cnt_name, counter ) import datetime dt = str(datetime.datetime.now())[:-7] ip = os.environ.get("REMOTE_ADDR",'?') f = open( file_ips_name, "at" ) if f: f.write( "%s %s\n" % (dt,ip) ) f.close() return_image() def return_image(): # 1x1 black pixel data = ('GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00' '\xFF\xFF\xFF\x21\xF9\x04\x00\x00\x00\x00\x00' '\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x03\x44\x01\x00\x3B') sys.stdout.write( "Content-type: image/gif\n\n" ) sys.stdout.write( data ) sys.stdout.close() def read_descriptions( filename ): dict = {} for line in file( filename ): if not line or line[0]=='#': # ignore empty and comment lines continue fields = line.split() if len(fields) < 2: continue num, title = fields[:2] dict[int(num)] = title return dict sites = read_descriptions( file_dsc ) # now we accept: # site=sitenumber (all digits) # actn=list|incr # How to insert a counter into your page: # def processing(): try: if os.environ.has_key('QUERY_STRING'): query = os.environ['QUERY_STRING'] import parsequery query = parsequery.parsequery( query ) # get dictionary if 'site' in query and 'actn' in query: site = query['site'] actn = query['actn'] site = int(site) if site in sites: if actn == 'list': show_list( site, sites[site] ) return if actn == 'incr': do_count( site ) return except: pass # all bad cases -- just return a picture return_image() processing() # used to allow return from the middle # EOF From jhefferon at smcvt.edu Thu May 20 11:38:32 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 20 May 2004 08:38:32 -0700 Subject: Why does the "".join(r) do this? Message-ID: <545cb8c2.0405200738.296bb094@posting.google.com> Hello, I'm getting an error join-ing strings and wonder if someone can explain why the function is behaving this way? If I .join in a string that contains a high character then I get an ascii codec decoding error. (The code below illustrates.) Why doesn't it just concatenate? I'm building up a web page by stuffing an array and then doing "".join(r) at the end. I intend to later encode it as 'latin1', so I'd like it to just concatenate. While I can work around this error, the reason for it escapes me. Thanks, Jim ================= program: try.py #!/usr/bin/python2.3 -u t="abc"+chr(174)+"def" print(u"next: %s :there" % (t.decode('latin1'),)) print t r=["x",'y',u'z'] r.append(t) k="".join(r) print k ================== command line (on my screen between the first abc and def is a circle-R, while between the second two is a black oval with a white question mark, in case anyone cares): jim at joshua:~$ ./try.py next: abc?def :there abc�def Traceback (most recent call last): File "./try.py", line 7, in ? k="".join(r) UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position 3: ordinal not in range(128) From singh_tarandeep at yahoo.com Tue May 18 05:50:10 2004 From: singh_tarandeep at yahoo.com (Tarandeep) Date: 18 May 2004 02:50:10 -0700 Subject: python threads reading material Message-ID: can anybody point me to some good and *detailed* explaination of python threads. thanks... Tarandeep From donn at drizzle.com Sun May 30 22:40:38 2004 From: donn at drizzle.com (Donn Cave) Date: Mon, 31 May 2004 02:40:38 -0000 Subject: Redirect stdout & stderr (similar to a daemon) References: <40b9cd69@news.starhub.net.sg> <1085934830.617304@yasure> <40ba7a0d@news.starhub.net.sg> Message-ID: <1085971237.33929@yasure> Quoth Tsai Li Ming : | Donn Cave wrote: | > There is, if I understand what you meant by that. Consider | > | > old0 = os.dup(0) | > os.dup2(si.fileno(), 0) | > | > The original input stream is held open on some arbitrary | > unit, which you may use at any point to restore it to standard | > input. | > | > os.dup2(old0, 0) | > os.close(old0) | > | > Donn Cave, donn at drizzle.com | | Thanks Donn, | | Why is there a need to close old0? Because of the extra file handle? Good question. It's just barely conceivable that it could cause a problem - say, where a child process redirects 0 but doesn't account for the dup'd version, the parent exits, the file stays open when it should have closed on exit, and something else has been depending on that. To start with, most normal ways to fork a child process will close all the extra files anyway, so this is highly improbable. I would still do it, but it's more style than function. Donn Cave, donn at drizzle.com From michael at foord.net Mon May 17 09:41:48 2004 From: michael at foord.net (Fuzzyman) Date: 17 May 2004 06:41:48 -0700 Subject: Troubles with CSV file References: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> Message-ID: <8089854e.0405170541.568a96ea@posting.google.com> [snip...] > > I replace all "" to """ as suggested and all works fine now. This is not the > ideal solution (sometimes csv file have a data like > , 123, "", 345, > > ... which supposed to be a blank string (not shure). But it is irrelevant > for me now and *replacing* approach is pretty satisfactory. > > Thanks again for your help. > > BTW > http://www.voidspace.org.uk/atlantibots/pythonutils.html is unreachable > ( "The page cannot be displayed" error ) > > Vladimir Ignatov For the record...... http://www.voidspace.org.uk/atlantibots/pythonutils.html is reachable - although it might have been temporarily unavailable.... I still think it would be very easy to amend my unquote function to handle double quoted elements...... Heck - email me and I'll do you one..... Regards, Fuzzy From gnosticray at aol.com Mon May 3 02:57:26 2004 From: gnosticray at aol.com (A B Carter) Date: 2 May 2004 23:57:26 -0700 Subject: Method binding confusion Message-ID: I'm a bit confused by the behavior of the following code: import math import myModule class Klass(object): def doOperation(self, x, y): return self.operator(x, y) class KlassMath(Klass): operator = math.pow class KlassMyModule(Klass): operator = myModule.pow km = KlassMath() kmy = KlassMyModule() km.doOperation(2,4) km.doOperation(2,4) The last call fails with "TypeError: takes exactly 2 argumetns (3 given)" I understand that in KlassMyModule the operator is being treated as a method and a reference to the class instance is being past as the first argument. And I also understand that Python is treating a function from the standard math libary differently from a function I defined in my own module. What I don't understand is why. A B Carter From davidf at sjsoft.com Mon May 17 06:16:13 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 17 May 2004 12:16:13 +0200 Subject: PEP: import version In-Reply-To: <40a52416$0$22119$636a15ce@news.free.fr> References: <40a52416$0$22119$636a15ce@news.free.fr> Message-ID: Christophe Cavalaria wrote: > Manlio Perillo wrote: > > >>Hi. >>I'm a new user of Python but I have noted a little problem. >>Python is a very good language but it is evolving, in particular its >>library is evolving. >>This can be a problem when, ad example, a module change its interface >>or its implementation in a fundamental way (an example: wxPython). >>This, I think, can be resolved by allowing an user to explicitly say >>what version of a module it wants (sush as version numbers in Linux >>shared objects). >> >>A possible syntax is this: >>import wxPython version '2.4' > > > I would say that the fault is on wxWindow and their constantly mutation API. > A good API should be compatible whit older programs with each minor > revision ( with only a few changes here and there if needed ) and would get > a new name for each major revision. Have you actually used it extensively? If so, I doubt you would be saying this... wxWiindows (now wxWidgets) doesn't have aconstantly mutating API. But the new major revision does have some changes. The point is you can still get programs to work with both versions, so you don't need to have a new name. But if a program does rely on a particular version, it would be nice to have a way to specify it. David From noemail at noemail4u.com Thu May 13 08:29:51 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Thu, 13 May 2004 12:29:51 GMT Subject: pyparsing References: <87fza46evn.fsf@bostjan-pc.mf.uni-lj.si> Message-ID: On Thu, 13 May 2004 08:05:32 +0200, bostjan.jerko at mf.uni-lj.si (Bo?tjan Jerko) wrote: >Hello ! > >I am trying to understand pyparsing. Here is a little test program >to check Optional subclass: > >from pyparsing import Word,nums,Literal,Optional > >lbrack=Literal("[").suppress() >rbrack=Literal("]").suppress() >ddot=Literal(":").suppress() >start = Word(nums+".") >step = Word(nums+".") >end = Word(nums+".") > >sequence=lbrack+start+Optional(ddot+step)+ddot+end+rbrack > >tokens = sequence.parseString("[0:0.1:1]") >print tokens > >tokens1 = sequence.parseString("[1:2]") >print tokens1 > >It works on tokens, but the error message is showed on >the second string ("[1:2]"). I don't get it. I did use >Optional for ddot and step so I guess they are optional. > >Any hints what I am doing wrong? > >The versions are pyparsing 1.1.2 and Python 2.3.3. > >Thanks, > >B. I don't see anything "obviously" wrong to me, but changing it thusly seems to resolve the problem (I added a few intermediate rules to make it more obvious): pref = lbrack + start midf = ddot + step suff = ddot + end + rbrack sequence = pref + midf + suff | pref + suff I've run into "this kind of thing" now and again, and have always been able to resolve it by reorganizing my rules. --dang From peter at engcorp.com Tue May 4 12:26:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 May 2004 12:26:38 -0400 Subject: calling functions at the same time In-Reply-To: <5600d16b.0405040352.47c9087e@posting.google.com> References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> <4093de02$0$17252$a1866201@newsreader.visi.com> <5600d16b.0405040352.47c9087e@posting.google.com> Message-ID: Tim Sharpe wrote: > Peter Hansen wrote > > >>The last sentence is really the whole point. The OP needs >>to be aware that the accuracy *cannot* be *guaranteed* >>to better than "tens of milliseconds", overall, regardless >>of the "accuracy" of the clock tick or the resolution of >>anything... > > As a network geek who writes crude software to test problems, I wonder > if we're not getting overly hung up on "exact". [snip] > If you really need more accuracy, then your best bet is to use libpcap > (or winpcap for Windows, see http://www.tcpdump.org), as it provides > packet timestamps that I've found to be accurate to fractions of > milliseconds. Tim, you're quite right of course. I think many of us were just sort of caught up in the fun of trying to show the OP how futile his attempt at "exact and simultaneous" timing really was. Someone really needed to come along and give some useful practical advice instead, and you're that guy. :-) -Peter From brian at sweetapp.com Thu May 27 09:22:14 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 27 May 2004 15:22:14 +0200 Subject: SimpleXMLRPCServer performance issue in MSWin In-Reply-To: <20040525162824.78925.qmail@web60604.mail.yahoo.com> References: <20040525162824.78925.qmail@web60604.mail.yahoo.com> Message-ID: <40B5EB86.3050305@sweetapp.com> danu kusmana wrote: > Hi > > Im trying to figure out why the same server script I > use is running slower in Windows than in Linux. Please provide more details e.g. timings, whether the performance problem is found in the client/server/both, etc. Cheers, Brian From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu May 20 17:12:58 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 20 May 2004 23:12:58 +0200 Subject: ANN: kronos, a task scheduler Message-ID: <40ad1f5c$0$36860$e4fe514c@news.xs4all.nl> Hello I've written a task scheduler called "kronos". This task scheduler is designed to be used from inside your own program. (i.e. it is not a cron daemon replacement). You can schedule Python functions to be called at specific intervals or days. It uses the standard 'sched' module for the actual task scheduling, but provides much more: - repeated tasks (at intervals, or on specific days) - error handling (exceptions in tasks don't kill the scheduler) - optional to run scheduler in its own thread or separate process - optional to run a task in its own thread or separate process It is available from http://www.razorvine.net/download/kronos.py Because it is the first version I'd like to request feedback from others! Suggestions, bugs, improvements? Please let me know. Your input is highly appreciated. --Irmen de Jong From smcg4191 at frii.RemoveThisToReply.com Tue May 25 13:30:57 2004 From: smcg4191 at frii.RemoveThisToReply.com (Stuart McGraw) Date: Tue, 25 May 2004 11:30:57 -0600 Subject: popen and unicode Message-ID: <40b382d2$0$206$75868355@news.frii.net> When I run (Python 2.3.3) this script on a MS Windows 2000 machine: import os print "1st popen..." f = os.popen ("echo " + u"\u0054\u0045\u0053\u0054.txt") print f.read () print "2nd popen..." f = os.popen ("echo " + u"\u5927\u7530\u8061\u7f8e.txt") print f.read () I get this: 1st popen... TEST.txt 2nd popen... Traceback (most recent call last): File "test.py", line 6, in ? f = os.popen ("echo " + u"\u5927\u7530\u8061\u7f8e.txt") UnicodeEncodeError: 'ascii' codec can't encode characters in position 5-8: ordinal not in range(128) Does os.popen() work with unicode strings containing characters outside the ASCII range? (I think I answered my own question, above.) How can I call popen to process non-ascii filenames on a Windows box? Is there anything else I could use (e.g. spawn) that will work with unicode filnames? From vignatov at colorpilot.com Fri May 14 06:08:15 2004 From: vignatov at colorpilot.com (Vladimir Ignatov) Date: Fri, 14 May 2004 14:08:15 +0400 Subject: Troubles with CSV file Message-ID: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> Hello! I have a big CSV file, which I must read and do some processing with it. Unfortunately I can't figure out how to use standard *csv* module in my situation. The problem is that some records look like: ""read this, man"", 1 which should be decoded back into the: "read this, man" 1 ... which is look pretty "natural" for me. Instead I got a: read this man"" 1 output. In other words, csv reader does not understand using of "" here. Quick experiment show me that *csv* module (with default 'excel' dialect) expects something like """read this, man""", 1 in my situation - quotes actually must be trippled. I don't understand this and can't figure out how to proceed with my CSV file. Maybe some *alternative* CSV parsers can help? Any suggestions are welcomed. Vladimir Ignatov From vincent at visualtrans.de Tue May 18 02:12:40 2004 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 May 2004 08:12:40 +0200 Subject: How does use of bsddb interact with Python in a commercial environment? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > This is something I've been curious about for a while, and have never > quite figured out... > > What are the legalities of writing commercial code which makes use > of the bsddb module in Python? I would expect that payment of some > sort would be necessary, but have no idea how much/under what terms. > Sleepycat's most basic fee is $25,000 I believe, if people wish to > incorporate code into their product, but what about the case (as > in Python) where the code is being accessed only indirectly? > > No wonder I'm an engineer and not a lawyer :-) > > Thanks, > Ken McDonald The comments below the following article addressing this issue might be of interest to you, although I can't really tell they will provide a definitive answer to your question: http://simon.incutio.com/archive/2003/11/26/discoveringBerkeleyDB Regards, -- Vincent Wehren From dygimailNo at SPAMpoczta.fm Sat May 15 13:58:18 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 15 May 2004 17:58:18 GMT Subject: looping over the files in a directory References: <40a4fba5$1@nntp0.pdx.net> Message-ID: "Elaine Jackson" wrote in news:uLcpc.478556$Ig.443767 at pd7tw2no: > elliptical <=> some information is left unspecified Thanks a lot. -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From kmmcdonald at wisc.edu Tue May 4 00:01:22 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Tue, 04 May 2004 04:01:22 GMT Subject: Very, very strange problem with properties Message-ID: For some reason, properties seem to have stopped working correctly on my system. (Mac OS X 10.3, custom-compiled Python 2.3.3) To the best of my knowledge, they were working correctly at some point in the not-too-distant past. The confusing thing is that they _partly_ work. Consider the following code: class foo: def __init__(self): self._x = 3 def __setx(self, val): print "Calling __setx" pass x = property(fget=lambda self: self._x, fset=__setx) f = foo() print f.__dict__ print f.x f.x = 2 print f.x f._x = 7 print f.x print f.__dict__ Running this _should_ print (ignoring the dict printouts) 3 Calling __setx 3 7 since the __setx function does nothing. In fact, what I get (dicts included) is: {'_x': 3} 3 2 2 {'x': 2, '_x': 7} i.e. the assignment f.x = 2 is overwriting the property! If I define the property as x = property(fget=lambda self: self._x) then running the code should cause an error on f.x = 7; in fact, I get the same result as when the fset is defined as __setx. So, it seems that the "getter" aspect of properties is working, but the "setter" aspect is ignored in such a way that regular attribute assignment takes place. I find this very, very strange. I would prefer to avoid reinstalling Python on my system, since keeping a custom Python working on OS X is a bit of a gamble anyway, at this point, but will if I have to. But I would prefer it if someone could suggest other alternatives to try first, and frankly, I'm also just curious as to what could cause an oddity like this. Thanks, Ken McDonald From greg at cosc.canterbury.ac.nz Tue May 4 00:54:34 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 04 May 2004 16:54:34 +1200 Subject: prototypes in Python [was: what is good in Prothon] In-Reply-To: References: <95aa1afa.0404280120.30176ca9@posting.google.com> <95aa1afa.0405012134.2b43ad6f@posting.google.com> Message-ID: David MacQuigg wrote: > On 1 May 2004 22:34:27 -0700, michele.simionato at poste.it (Michele > Simionato) wrote: > >>Probably you do not realize that methods and functions are *already* >>unified in Python: they are both examples of descriptors. > > Interesting! I wish that unification at the primitive level had been > provided in the original design of Python. It was. Methods have always been no more than functions that happen to live in classes, and they still are. Descriptors are a red herring here; they're just a generalisation that allows for some new things. They don't unify anything that was previously existing but not unified. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From p at ulmcnett.com Mon May 17 13:43:18 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 17 May 2004 10:43:18 -0700 Subject: module for working with the result set In-Reply-To: References: Message-ID: <200405171043.18797.p@ulmcnett.com> john fabiani writes: > mydata=cursor.fetchmany(10) > for field in mydata[0]: > print mydata[0][field] I think you want: mydata=cursor.fetchmany(10) for record in mydata: print "--- record ---" for field in record: print field From matthewleslie at hotmail.com Fri May 21 17:50:08 2004 From: matthewleslie at hotmail.com (Matt Leslie) Date: Fri, 21 May 2004 16:50:08 -0500 Subject: Stackless python and microthreads In-Reply-To: References: <1084504249.836501@yasure> Message-ID: >> Now instead of a tedious kind of state machine, you're writing an plain, >> ordinary function that sends messages to its peer and looks at the >> response, >> as though that were all synchronous, and it's so much simpler. Yet the >> execution underneath that isn't synchronous at all, because your >> computation >> is suspended in between your send and the response. It really does >> return >> every time it sends a message, it just starts up next time where it left >> off. > > Infact this is also similar to what I'm trying to do, except I'm doing it back to front. I want to write a package to help simulate distributed systems, making what would be simple synchronous method calls asynchronous. I do this by intercepting method calls between threads, and passing them on only after a simulated network delay - they are held in an event queue and basically only executed when there is nothing scheduled to happen 'before' it. It boils down to a similar structure, I think. Anyway, stackless would be good for this because I need lots of threads so simulate large scale P2P systems. The thing is although there was a fair amount of documentation on microthreads I can find nothing usefull on tasklets! Can anyone point me at some? Please? The stackless mailing list has turned up nothing so far... Matt From chris at acheris.net Thu May 27 17:42:52 2004 From: chris at acheris.net (The Dark Seraph) Date: Thu, 27 May 2004 21:42:52 +0000 (UTC) Subject: Detached interpreter threads Message-ID: Hi- I am writting an application in C++ that I am attempting to embed an interpreter in. I know about how I need to protect the interpreter internals from mean nasty threads in my program, but I am runnning across a problem I don't quite understand. Here is my flow of control: C++ Main starts up Py_Initialize() is run PyEval_InitThreads() is run ( or whatever it is called ) PyRun_SimpleFile() is called with Loader.py Loader.py begins to execute: Loader.py prints it is running Loader.py does a few imports Loader.py does a start_new_thread() Loader.py says it is done running Control returns to C++ program The problem is that the new thread started by Loader doesn't every have its entry point called. I made the very first line a print, but that didn't ever get executed. If I run Loader.py on its own, it works just fine and dandy. I have the same construct in Jython that works perfectly, so I am kind of puzzled as to why interpreter threads don't run. Any thoughts? -- chris at acheris.net | Fight Censorship, Boycott Wal-Mart Now is the winter of your discontent! - Stewie From claird at lairds.com Tue May 18 09:18:27 2004 From: claird at lairds.com (Cameron Laird) Date: Tue, 18 May 2004 13:18:27 -0000 Subject: Python compilers? References: <40A985CC.8A380731@shaw.ca> Message-ID: <10ak393iqicavd0@corp.supernews.com> In article <40A985CC.8A380731 at shaw.ca>, wrote: . . . >I really wish there was a python-to-native compiler, a good one that >would produce fairly fast execution. . . . Maybe there is. There's enough ambiguity in "python-to-native compiler" that it's possible what you (think you) want already exists. See Leif K-Brooks's follow-up, especially. -- Cameron Laird Business: http://www.Phaseit.net From john.cashman at gmail.com Mon May 17 15:01:08 2004 From: john.cashman at gmail.com (John) Date: 17 May 2004 12:01:08 -0700 Subject: Boa+wxpython2.4+wxGTK2.4 Message-ID: Hi, I'm trying to get Boa running on MDK cooker but keep getting this error. I have googled around for the error and it seems to have something to do with the wxGTK version I'm using. What version does everyone else use??? Thanks, John Starting Boa Constructor v0.2.8 importing wxPython Traceback (most recent call last): File "./Boa.py", line 194, in ? from wxPython import wx File "/usr/lib/python2.3/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: /usr/lib/wxPython/lib/libwx_gtk2u-2.4.so.0: undefined symbol: _gtk_accel_group_detach From mark_mitwrong at wrongbellsouth.net Fri May 28 12:16:36 2004 From: mark_mitwrong at wrongbellsouth.net (Mark Mitchell) Date: Fri, 28 May 2004 16:16:36 GMT Subject: Non-programmer needs help with PyGTK-2.0.0 References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2004-05-28, Holger T?rk wrote: > > > Mark Mitchell wrote: >> I have a program written in python that tells me it requires PyGTK, so I >> DLed, ./configure, make, make install and the process seems to go ok. Some >> errors but the process finishes so I assumed they weren't fatal errors. > > It often complains about missing functions, or something. > It compiles though, so I assume, it's built completely. > >> >> So now I attempt to run my python program and I get; >> $ gccp.py >> Traceback (most recent call last): >> File "./gccp.py", line 9, in ? >> import pygtk >> ImportError: No module named pygtk >> >> I'm running Slackware 9.1 with a 2.6.6 kernel, and I don't know what other >> information would be helpful. > > Most probably, pygtk is installed in a directory where python > cannot find it (i.e. the wrong directory). So setting PYTHONPATH > may help. If not: > > Did you get python from a Slackware package? > No, I compiled from source. > Where's the python standard library? > in /usr/lib/python?.? or /usr/local/lib/python?.? ? > I have a /usr/lib/python2.3 that has a bunch of .py .pyo .pyc files, and I also have a; $ ls -l /usr/local/lib/python2.3/ total 1 drwxr-xr-x 3 root root 192 2004-05-26 23:56 site-packages/ > Where did it install pygtk? > /usr/lib/python?.?/site-packages or /usr/local/lib/python?.?/site-packages ? > I'm not sure what exactly you're referring to here. Looking at my install log, I have a number of .py .pyc .pyo files in usr/local/lib/python2.3/site-packages/gtk-2.0/gtk/ and usr/local/share/pygtk/2.0/ Is there a single filename or extension I should be looking for? > What's your --prefix for ./configure ? > I didn't use one, just straight ./configure. Mark - -- Remove both wrongs to make the email address right. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAt2fPLVmEOl6/PWERAkW2AKCw+gK/pTYQ7JdDTbh4jrO7TvPXiwCfVGBK Hip5c0CaZ/T9NAuyvZfkfg4= =8hIu -----END PGP SIGNATURE----- From peter at engcorp.com Mon May 3 08:56:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 08:56:44 -0400 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: References: Message-ID: F. GEIGER wrote: > I wanted to look at the PyOpenGL demo in the wxPython demo, but had no luck: > > "Runtime Error > Program: C:\...\pythonw.exe > abnormal program termination" > > Has anyone overcome this problem? I have this as well after a recent upgrade and a series of other problems (which will never be reproducible), and it's still here after a re-install of all things Python-related. (So I assume I have some video driver problems.) I cannot say for sure that it ever worked on this machine as it's fairly new and I don't recall running any PyOpenGL on it since I got it. > P.S.: Python 2.3.2 on Win2k, wxPython 2.4.2.4u, PyOpenGL (from > PyOpenGL-2.0.1.07.py2.3-numpy23.exe), glut.dll (from GLUT 3.7.6) copied into > \WINNT\System32. Python 2.3.3 on WinXP, wxPython 2.5.1.5, same PyOpenGL, and no idea what glut.dll version I have. This is running the "GLCanvas" demo, as the old OpenGL demo appears to be gone in the latest wxPython release (or is it just a name-change?). (Don't know what glut.dll is or where it's from either... my last-modified date says 1998-08-11 but the attributes say it was created 2004-3-7. I'll dig further if it appears to be relevant.) -Peter From __peter__ at web.de Mon May 10 12:09:44 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 May 2004 18:09:44 +0200 Subject: newbie question - remove a module from ram References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> Message-ID: Paul McGuire wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:c7nvr1$fsc$01$1 at news.t-online.com... >> Paul McGuire wrote: >> >> > "john fabiani" wrote in message >> > news:4AAnc.6791$dH5.4946 at newssvr27.news.prodigy.com... >> >> Hi, >> >> >> >> I believe I have good understanding of import but it occurred to me > that >> >> I might want to remove an imported module. I.e I load a module into > ram >> >> and I no longer need the module. Modules just stays in ram? In the >> >> windows world I would "thisform.release()" and the garbage collector >> >> would release the ram. So did I miss something or is there no release >> >> method. How about a method within a class like destroy()? >> >> >> >> I just got to believe it's there???? But where? >> >> John >> > >> > Well, you were pretty close with calling something like .release(). >> > Use the del statement. >> > >> >>>> import random >> >>>> print random.random() >> > 0.475899061786 >> >>>> del random >> >>>> print random.random() >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > NameError: name 'random' is not defined >> >>>> >> >> and then >> >> >>> import sys >> >>> sys.modules["random"].random() >> 0.43459738002826365 >> >>> >> >> should make it clear that (next to) no memory is freed in the process. >> >> Peter >> > So then what if he follows up with: > > del sys.modules["random"] > > Are there any other dangling references to this module that would stymie > the garbage collector (assuming that the OP hasn't saved off his own > reference to the module)? Python 2.3.3 (#1, Jan 3 2004, 13:57:08) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random, sys, weakref >>> sys.getrefcount(random) 3 >>> del sys.modules["random"] >>> sys.getrefcount(random) 2 This is one reference for the function call and one for the __main__.random reference, i. e. reference count should indeed go to zero if we perform del random I could not trick the module into telling me directly: >>> def f(r): print "i'm gone" ... >>> w = weakref.ref(random, f) Traceback (most recent call last): File "", line 1, in ? TypeError: cannot create weak reference to 'module' object >>> Second try, working around the limitations of weak references: >>> import random, sys, weakref >>> class Flag: pass ... >>> random.flag = Flag() >>> def goodbye(r): print "I'm gone" ... >>> w = weakref.ref(random.flag, goodbye) >>> del random >>> del sys.modules["random"] I'm gone >>> So at least the objects in the module are garbage-collected. Peter From deetsNOSPAM at web.de Mon May 24 05:25:01 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 24 May 2004 11:25:01 +0200 Subject: Pygame classes and files References: <9125a2e9.0405231913.7d8e40f@posting.google.com> Message-ID: <2hdtibFbs332U2@uni-berlin.de> Nickchch wrote: > Can anyone help me, I need to document the pygame framework - ie > classes/packages etc. Does anyone have anything like this already ?? > or point me in the right direction. > > I am a newbie to pygame !! www.pygame.org - always remember, google is your friend. -- Regards, Diez B. Roggisch From noemail at noemail4u.com Fri May 7 09:30:19 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Fri, 07 May 2004 13:30:19 GMT Subject: classes vs dicts References: Message-ID: On 06 May 2004 07:22:05 -0400, Heather Coppersmith wrote: ... >In the end (and in the implementation), classes are just syntactic >sugar for dictionaries. > > object.attribute is equiv. to dictionary[ 'key' ] I think you're overgeneralizing, or I'm reading overgenerality into your response. I assume you mean that manipulating an instance of a class attribute is syntactic sugar for manipulating a single dictionary entry? You can't arbitrarily add or remove attributes to an instance of a class (without using "magic", which kinda puts a major sour in the syntactic sugar!). Classes are not syntactic sugar for dictionaries. --dang From dkuhlman at rexx.com Sat May 22 20:08:57 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 22 May 2004 17:08:57 -0700 Subject: What is the name of this Python programming style Message-ID: <2ha8alFaq80qU1@uni-berlin.de> I'd like to learn more about this style of programming in Python. In this style or pattern, a high level class is given an instance (or a class from which it creates an instance), then uses that instance to perform its tasks. A user of the higher-level class can customize the function of that class by implementing or customizing details in lower-level class. I've seen it a number of times. It seems quite useful. It provides loose coupling between a higher-level policy class and a lower-level mechanism or implementation class. The coupling is defined by an abstract base class which the lower level class must implement. This loose coupling frees the higher-level policy class from dependency on details in a lower-level mechanism class. One example of this style is in BaseHTTPServer in the Python standard library. The constructor to BaseHTTPServer takes a handler class as an argument. The handler class should be sub-class of BaseHTTPRequestHandler. So, in this example: - BaseHTTPServer is the higher-level policy class. - BaseHTTPRequestHandler defines the interface. Or should it be called the protocol? - And, the sub-class of BaseHTTPRequestHandler that I'm supposed to implement is the lower-level mechanism class. I think the general name for this is Inversion of Control (IoC). Can someone tell me if this Python pattern or style has a name among Pythonistas? It's not unique to Python, of course, but once again Python seems very well suited to this pattern or style. I've been reading about PEAK (http://peak.telecommunity.com/). PEAK supports this style of programming in a much more complex way. Does anyone have some experience with PEAK? Is the PEAK way better or more powerful? Learning the PEAK way seems to require immersion in a complete Zen of PEAK. It is pretty opaque to me. I'd be thankful for a pointer or URL to help me gain a little understanding. I've read the tutorial and quite a bit of the PEAK Wiki. Is there more somewhere? Thanks for help. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From nirmalkannan at hotmail.com Wed May 12 07:06:45 2004 From: nirmalkannan at hotmail.com (N.K) Date: 12 May 2004 04:06:45 -0700 Subject: How to batch download files from web page? References: Message-ID: <5b04353b.0405120306.175f4057@posting.google.com> Consider http://harvestman.freezope.org ( Python) sj wrote in message news:... > I wish to download hundreds of files from the University of Iowa sound > archive. Doing it manually would be a daunting task especially since the > files are each a few mega bytes long. Is there a standard way of using > Python for such a task? I have a fair amount of programming experiance but > very little of it relates to networks. > > For those who are intrested the University of Iowa's sound archive may be > found at http://theremin.music.uiowa.edu/MIS.html > > Thanks in advance > Steven Jones From mwilson at the-wire.com Sun May 23 09:01:33 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 23 May 2004 09:01:33 -0400 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <40AFDAF1.4080400@v.loewis.de> <83qva01mh68c319d23e9o4ldtl62qm3188@4ax.com> Message-ID: In article <83qva01mh68c319d23e9o4ldtl62qm3188 at 4ax.com>, Arthur wrote: >On Sun, 23 May 2004 00:57:53 +0200, "Martin v. L?wis" > wrote: > >> >>The fact that I use cm to measure X, Y, and Z still doesn't make >>them homogenous. > >A question on some IQ test: > >X,Y & Z rerpesent the 3d coordinates of a point in some coordinate >system. > >X=1 >Y=1 >Z=1 > >The ordred seqence (1,1,1) of the X,Y & Z coordinates represents > >a) heterogenous data >b) homogenous data >c) N/A > >has a right answer. > >A. > >I disagree. Depends on the coordinate system. If the bases are east, north and up, then you're right to disagree. If they're east, up and future, then you're also right although the argument is subtle. If they're height, weight and Nielsen Rating, then A may be the best answer. Regards. Mel. From segphault at sbcglobal.net Wed May 26 19:59:55 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 26 May 2004 23:59:55 GMT Subject: Embedding Python at the OS level - build problems [success] References: <20040526003414.GA2712@unununium.org> Message-ID: On Wed, 26 May 2004 14:13:07 -0400, Phil Frost wrote: > Success! They said it can't be done. "Python is too big", they said. > "Too high level for an OS". And yet, it's done :) > congratulations! truly a unique and innovative endeavor. I can't wait to see how you use it. I'm quite curious about how you have bound python to the operating system: i'm particularly interested in what specifically this lets you do, that you couldnt otherwise do on a platform where python is just a command-line accessible application. On your web site you say that your OS is very modular (this conjures up thoughts about microkernels) Projects like the Hurd facilitate construction of userspace kernel extensions; can your OS allow for something similar, but with Python? It would be neat to see a compact and efficient OS designed to natively support things like a python-extendable VFS, or kernel level net services that support scripted extensions. I've experimented with the hurd, qnx, and a few others, and all of them support graceful and efficient userspace kernel extension- something that linux's monolithic kernel regrettably precludes. I think that pluggable micro-kernels are a wonderful technology, and I love studying implementations- any information you can provide about the model of your OS, particularly the embedded python components, would be greatly appreciated. I havent learned assembly yet, so looking at your code probably wouldnt be very useful for me, and your web site doesnt have the kind of technical details i'm interested in. If you have some time, i'd really like to hear more about your project! thanks, --SegPhault From dmq at gain.com Tue May 18 06:57:02 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 18 May 2004 03:57:02 -0700 Subject: classes vs dicts References: Message-ID: On Thu, 13 May 2004 13:33:11 -0400, "Terry Reedy" wrote: >"David MacQuigg" wrote in message >news:nj57a01tqsvtufcur2gqu3enbjll5l95id at 4ax.com... >> My problem is similar, with the additional requirement that I need a >> convenient way to access data deep within a hierarchy of parameters. >> I chose classes over dictionaries because the syntax to access items >> in a deeply nested dictionary is awkward. >> >> dict[window1][plot2][xaxis][label][font][size] = 12 >> >> vs >> >> statefiles.window1.plot2.xaxis.label.font.size = 12 >> >> The problem is I can't easily save the whole hierarchy to disk. >> Pickle doesn't work with classes. Also, I worry about the overhead of >> classes when I am just needing a simple container. A typical >> statefile will have 1000 parameters in 300 classes nested up to ten >> levels deep. As a structure of nested classes this takes about 74KB >> on disk. Importing the file creates a .pyc file that is 157KB !! It >> does seem to import quickly, however, so speed may not be a problem. > >I believe you could write a class whose instances would correspond to >(wrap) a dictionary with possible subdicts. It would have a getattribute >method that turned the attribute name into a dict key and either return a >new instance or a 'raw' object depending on whether the corresponding value >was a nested dict or something else. You would start with one instance >representing the top level dict and work down from there. I'll leave >implementation to you. > >I also believe you could instead do this as a subclass of dict itself. I >might have even seen such somewhere. I wrote a module, based on Dave Brueck's example, adding load and save methods to his basic Bag class. The class definition is copied below. The complete module, including unit tests is at http://ece.arizona.edu/~edatools/Python/Statefiles/bag01.py The work remaining is to make the output "statefile" an even neater, more compact format. This will allow a user to scan through thousands of parameters to find the ones he needs, then cut-and-paste a section of the parameter file into a script, and have the copied parameters load into his program. -- Dave # Organize statefiles as nested "bags" of parameters. # Load and save in a neat format for external editing. TAB = 3; SP = ' '*(TAB-1); LINE = 0; LMAX = 15 TABMARKS = (('#'+SP)+('.'+SP)*4)*3 + '\n' class Bag: def __init__(self, **kwargs): self.__dict__.update(kwargs) self.Indent = '' def load(infile): strng = infile.read() exec( 'bag = Bag(\n' + strng + ')' ) return bag load = staticmethod(load) def save(self, outfile): global LINE for k,v in self.__dict__.items(): if k == 'Indent': continue Idt = self.Indent if isinstance( v, Bag ): if LINE > LMAX: outfile.write( TABMARKS ); LINE = 0 outfile.write( Idt + k + '=Bag(\n' ) LINE += 1 v.Indent = Idt + ' '*TAB v.save(outfile) outfile.write( Idt + '),\n' ) else: if type(v) is not str: v = str(v) else: v = "'%s'" % v outfile.write( Idt + k + ' = ' + v + ',\n' ) LINE += 1 From marco.terzuoli at libero.it Thu May 20 16:36:04 2004 From: marco.terzuoli at libero.it (Marco Terzuoli) Date: Thu, 20 May 2004 20:36:04 GMT Subject: Redrawing GUI while in a for loop Message-ID: Hi, I am making a program which has got some GUI. I need a timer in it which performs some kind of operations. What I am doing now is something like while 1: sleep(1) do_stuff() But this way I cannot interact with the GUI since the program is only run within the while loop. Is there any way to solve the problem either with a function that temporarily passes control to the OS (something like DoEvents in Visual Basic) or with a timer instruction which regularly calls a function I define? Thanks Marco From kenneth.m.mcdonald at sbcglobal.net Mon May 17 00:20:12 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 17 May 2004 04:20:12 GMT Subject: What's active and worthwhile in the Python 3D world? Message-ID: One of my current "fun" goals is to start playing with 3D related things, purely because I find it of interest. Since I also use and love Python in more serious endeavours, it would seem to make sense to try to find 3D related things that involve Python. In fact, there seem to be quite a few--so many that I'm not really sure what is active and growing, and what is dying off. So I was wondering if there are Pythonistas out there with similar interests, and if so, what you might recommend looking at? I realize this is broad in scope, but I really am just looking to play right now. If I were to state a long-term interest, it might be in a modeller that had a more command-oriented (as opposed to GUI) approach to modelling, but there are many things I could be interested in. Thanks, Ken From ralf at tecont.de Wed May 12 08:18:15 2004 From: ralf at tecont.de (Ralf Muschall) Date: Wed, 12 May 2004 14:18:15 +0200 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: <848yfxsut4.fsf@tecont.de> Kirk Job-Sluder writes: > I still find: > awk 'BEGIN {FS="\t"} {printf("pattern", $1,$4,$3,$2)}' file > to be more elegant and easier to debug. It does the required task in > two easy-to remember statements. It misses the "-i" thing. You have to wrap it: NEWNAME=mktemp foo.XXXXXX mv file $NEWNAME your_awk $NEWNAME > file rm $NEWNAME (unless there is a backup argument after the "-i") mv $NEWNAME file.bak (if there is one) Ralf -- GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V- PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv b+++ DI+++ D? G+ e++++ h+ r? y? From pschmied at yahoo.com Thu May 27 12:29:17 2004 From: pschmied at yahoo.com (Peter Schmiedeskamp) Date: Thu, 27 May 2004 09:29:17 -0700 (PDT) Subject: Determine rights and privileges on Windows. Message-ID: <20040527162917.97270.qmail@web11602.mail.yahoo.com> Hello, I'm writing a python program (in Windows) from which I would like to determine whether or not either: 1. The user has administrative access on the current PC. or (better) 2. The currently running process has administrative access. For the first scenario, the win32security.LsaEnumerateAccountRight() seems to to be the ticket. The documentation doesn't describe what this function requires as parameters. It appears to require a PySID object and some sort of PyHANDLE object. I've figured out how to get the PySID object, but I'm not sure what type of PyHANDLE is required (or how to create such a thing) My other alternative is to check the running process for its authority. There appear to a number of functions that sound potentially logical to use, however I'm unable to determine which I should use. Has anyone done such a thing? Many thanks to anyone who can give me a shove down the right path. -Peter __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From ssk at chol.nospam.net Wed May 26 11:52:29 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Wed, 26 May 2004 15:52:29 GMT Subject: gencache.EnsureModule Error Message-ID: <133tc.4247$e_1.2887@newssvr27.news.prodigy.com> Hello! I use Python for ASP. When I request a page for the first time in a session, I get an error message like below. If I refresh the same page, it doesn't cause any error. I believe that the error occurs at def ensuremodule(): gencache.EnsureModule('{00000201-0000-0010-8000-00AA006D2EA4}',0,2,1) which is for ADO for SQLServer. Does anybody know why? Error Type: Python ActiveX Scripting Engine (0x80020009) Traceback (most recent call last): File " === By the way, if you have the courage to distance yourself from every other language under the sun, I would propose that you throw an exception on unknown escape sequences. It is very easy in Python to accidentally used an escape sequence that is incorrect as above. Plus, it is near impossible to add new escape sequences to Python because they may break some code somewhere. I don't understand why this case is special enough to break the usual Python commitment to "not guess" what programmers mean in the face of ambiguity. This is another one of those things you have to get right at the beginning because it is tough to change later! Also, I totally hate how character numbers are not delimited. It should be \u{1} or \u{1234} or \u{12345}. I find Python totally weird: >>> u"\1" u'\x01' >>> u"\12" u'\n' >>> u"\123" u'S' >>> u"\1234" u'S4' >>> u"\u1234" u'\u1234' >>> u"\u123" UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-4: end of string in escape sequence ==== So anyhow, the Python model is that there is a distinction between character strings (which Python calls "unicode strings") and byte strings (called 8-bit strings). If you want to decode data you are reading from a file, you can just: file("filename").read().decode("ascii") or file("filename").read().decode("utf-8") Here's an illustration of a clean split between character strings and byte strings: >>> file("filename").read() >>> file("filename").read().decode("ascii") "abc" Now the Javascript model, which also seems to work, is a little bit different. There is only one string type, but each character can take values up to 2^16 (more on this number later). http://www.mozilla.org/js/language/es4/formal/notation.html#string If you read binary data in JavaScript, the implementations seem to just map each byte to a corresponding Unicode code point (another way of saying that is that they default to the latin-1 encoding). This should work in most browsers: (ignore the reference to "Xml" above. For some reason Microsoft decided to conflate XML and HTTP in their APIs. In this case we are doing nothing with XML whatsoever) I was going to write that Javascript also has a function that allows you to explicitly decode. That would be logical. You could imagine that you could do as many levels of decoding as you like: objXml.decode("utf-8").decode("latin-1").decode("utf-8").decode("koi8-r") This model is a little bit "simpler" in that there is only one string object and the programmer just keeps straight in their head whether it has been decoded already (or how many times it has been decoded, if for some strange reason it were double or triple-encoded). But it turns out that I can't find a Javascript Unicode decoding function through Google. More evidence that Javascript is brain-dead I suppose. Anyhow, that describes two models: one where byte (0-255) and character (0-2**16 or 2**32) strings are strictly separated and one where byte strings are just treated as a subset of character strings. What you absolutely do not want is to leave character handling totally in the domain of the application programmer as C and early and versions of Python did. On to character ranges. Strictly speaking, the Unicode cap is 2^20 characters. You'll notice that this is just beyond 2^16, which is a much more convenient (and space efficient) number. There are three basic ways of dealing with this situation. 1. You can use two bytes per character and simply ignore the issue. "Those characters are not available. Deal with it!" That isn't as crazy as it sounds because the high characters are not in common use yet. 2. You could directly use 3 (or more likely 4) bytes per character. "Memory is cheap. Deal with it!" 3. You could do tricks where you sort of page switch from two-byte to four-byte mode using "surrogates".[1] This is actually not that far from "1" if you leave the manipulation of the surrogates entirely in application code. I believe this is the strategy used by Java[2] and Javascript.[3] [1] http://www.i18nguy.com/surrogates.html [2] "The methods that only accept a char value cannot support supplementary characters. They treat char values from the surrogate ranges as undefined characters." http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html "Characters are single Unicode 16-bit code points. We write them enclosed in single quotes ? and ?. There are exactly 65536 characters: ??u0000??, ??u0001??, ...,?A?, ?B?, ?C?, ..., ??uFFFF?? (see also notation for non-ASCII characters). Unicode surrogates are considered to be pairs of characters for the purpose of this specification." [3] http://www.mozilla.org/js/language/js20-2000-07/formal/notation.html From a correctness point of view, 4-byte chars is obviously Unicode-correct. From a performance point of view, most language designers people have chosen to sweep the issue under the table and hope that 16 bits per char continue to be enough "most of the time" and that those who care about more will explicitly write their own code to deal with high characters. Paul Prescod From stani_ at hotmail.com Sun May 9 18:00:53 2004 From: stani_ at hotmail.com (SM) Date: 9 May 2004 15:00:53 -0700 Subject: Best IDE? References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> Message-ID: <99230dbb.0405091400.63a4ccbe@posting.google.com> "Neal D. Becker" wrote in message news:... > SM wrote: > > > Hi, > > Just to let you all know that there is a new version of SPE being > > developped with a much faster class/index/todo browser (can be even > > realtime!), wxPython 2.5 support, simultaneous view of source code, > > you can choose between MDI or SDI both with tabs, better control of > > calltips (only first paragraph or all doc) ... If you are curious, > > you can download it from http://projects.blender.org/projects/spe/ The > > windows XP version is already quite stable, for linux and mac os x, > > I'm dependent of other users. > > Stani > > > > Does SPE feature running python subprocess? Like what? > Python debug? Nope (or not yet). > Jump to error? Yes Stani http://spe.pycs.net From spam at pky2k.de Wed May 26 11:20:50 2004 From: spam at pky2k.de (Philipp Kruse) Date: Wed, 26 May 2004 17:20:50 +0200 Subject: py2exe setup script problem In-Reply-To: References: <2hchapFbelulU1@uni-berlin.de> <2heo0tFbiqgvU1@uni-berlin.de> Message-ID: <2hjquiFchj6eU1@uni-berlin.de> From: Thomas Heller Date: 25.05.2004 21:19 ------------------------------------------------------------ > There's a bug when using windows=[] which may be triggered when you > don't have an > import sys > in your main script. Reading the py2exe/boot_common.py file might give > you a hint. If you can, please get the py2exe CVS version and try with > this. Got the CVS version, installed it and everything works smoothly now, thanks a lot. Philipp From mcherm at mcherm.com Fri May 21 12:47:21 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 21 May 2004 09:47:21 -0700 Subject: terminological obscurity Message-ID: <1085158041.40ae3299602d5@mcherm.com> Elaine Jackson writes: > All tuple methods are also list methods, and most list methods are also tuple > methods; among those that are NOT also tuple methods, there are exactly two > ('count' and 'index') that do not involve mutation. Is there any special reason > why they AREN'T also tuple methods? Yes. Both make sense only if you consider a tuple as a homogeneous sequence of items, and that's not what Guido intended it to be used for. > A question about terminology ('namespace'): > > >>> prince=tuple() > >>> king=[prince] > >>> del prince > > At this point, does the object formerly known as prince belong to the > namespace implemented by globals()? More generally, is there a > terminological way to distinguish between (1) a function from a set > of names into a set of objects, and (2) the aforementioned set of > objects? After executing your code, there exist two objects, one is a tuple and the other is a list. The global namespace contains one binding: the name "king" is bound to the aforementioned list. The tuple is not referred to directly by any name in the global namespace but it will not be garbage collected yet because it is referenced by the list and cannot be freed until the list itself is freed. Whether this answers your questions I'm not sure... the questions didn't make sense to me. > Is there a handy noun that refers to sameness of identity in the same > way that 'equality' refers to sameness of value? ('Identicalness' is > pretty clumsy, and 'identity' is confusing, since it already has a > meaning that is closely related but needs to be kept distinct.) I've usually heard "identity" used. I don't know of any other synonynms to use here. > Suppose X is a container that contains n items (incidentally, is 'items' > the right term?) and i in an integer with 0<=i<=n. Does " X[i] " count > as a 'name'? "items" is a perfectly good term for the things in a list. In common usage, "X[i]" is not a name. It is, however, an "L-value" -- a slightly related term which (unlike "name") has a fairly precise definition. -- Michael Chermside From cmtaylor at ti.com Thu May 27 14:22:42 2004 From: cmtaylor at ti.com (Taylor, Martin) Date: Thu, 27 May 2004 13:22:42 -0500 Subject: Python with TestDirector Message-ID: Limor Hevroni asked on Mon Apr 19 06:49:06 EDT 2004 if anyone was using Python for testing with TestDirector. I am doing this extensively and would welcome discussions with other people who are either doing it or are interested in doing it. Regards, C. Martin Taylor Sr. Test Automation Specialist Texas Instruments, Inc. Educational and Productivity Solutions 7800 Banner Dr. MS 3946 Dallas, TX 75251 -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Fri May 14 23:32:00 2004 From: grante at visi.com (Grant Edwards) Date: 15 May 2004 03:32:00 GMT Subject: book on wxPython? Message-ID: Can anybody recommend a good book on wxPython? Are there any books on wxPython? I've been trying to learn wxPython and/or wax for a few weeks, and I'm just not getting it. [I wrote and shipped one small wxPython app a couple years ago, and it was a cut/paste, trial and error sort of exercise.] wxWindows seems to be more low-level than the other GUI toolkits I've used (Tk, GTK, and Trestle[1]), and there are all sorts exposed details in wxWindows/wxPython that I find weird. For example, I'm still confused about how to tell what the "parent" of a widget should be. When you put a StaticBox in a Panel, the Panel is the parent of the StaticBox. When you put SomeOtherWidget in the StaticBox, why is the parent of SomeOtherWidget the Panel and not the StaticBox? And what about sizers? They seem to be a sort of parallel, phantom tree of widgets that's stuck on the side of the real tree of widgets, while other GUI toolkits treat layout widgets (grids, hboxes, vboxes, etc) as a "first-class" widgets that reside in the same tree as the widgets that actually draw stuff. Anyway, I'd really love to find a good book on wxPython. I'm still working through wxPython tutorials, and I've read through some of the wxWindows ones (which are of limited value for somebody steadfastly determined to remain clueless about C++). I'm also still reading stuff on wiki.wxpython.org, but Wikis always seem so fragmented... [1] I still think the hbox/vbox/glue abstraction used by Trestle was one of the easiest to use. Probably because I've been using TeX and LaTeX for 25 years. -- Grant Edwards grante Yow! How do I get HOME? at visi.com From Chris.Barker at noaa.gov Thu May 13 18:51:59 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Thu, 13 May 2004 15:51:59 -0700 Subject: PEP: import version In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Perhaps I'm missing something... If you need to futz around at runtime, > futz around with sys.path. Can you summarize the wxPython discussions for > those of us who don't use that toolkit (and have apparently never run into > this problem in such an intractable way that we felt the need to change > Python because of it)? Actually, I was personally advocating an approach that did not require changing python, but would hopefully be standardized. I posted a question to this newsgroup about it a short while back, and I think PyGTK and PMW both do this in some way or another, so it's not a totally unique problem. > In particular it would be helpful to understand why > you don't know what version of wxPython you want to use before running > the program. I know what version I want when writing it, but not necessarily when running it. This is analogous to why I ALWAYS use: #!/usr/bin/env python2.3 rather than: #!/usr/bin/env python at the top of my scripts. RedHat doing the later created a major pain-in-the-behind for many of us. I only wish there were a way for Windows Python to handle that kind of thing gracefully. MacPython uses a "PythonLauncher" mini-app to take care of it (and for other reasons). Anyway, as for wxPython (and many other packages, I imagine), I have a handful of small utilities that work just fine with Python version X and wxPython version Y. If I upgrade python while keeping the old one in place, they all still work (thanks to my specifying the version on the #! line), However, if I add wxPython version Z, I'm stuck. The way it's ordinarily installed is in site-packages/wx. If I do a standard install, it blows away version Y, and all my existing programs are broken. What I, and other "early adopters" of new versions do is do a custom install and run a script that re-names or sym-links site-packages/wx to the version we want. That helps, but then at any given moment, only one is the active version, so I can't run a new and old program at the same time. So what some of us would like is for the standard way that wxPython is installed to allow for versioning. The Wiki page pointed to earlier has some suggestions about how to do this. > Chris> Basic Goals: > Chris> * Multiple versions of wxPython being installed at the same time > Presumably in different directories, so setting PYTHONPATH, LD_LIBRARY_PATH, > etc will distiguish them for applications. Well, yes, but unfortunately, the standard install puts it in site-packages, so you have to do a custom install to make this work. > Chris> * Two or more programs, each using a different version could run > Chris> at once. This doesn't require a change to the language. This requires a proper > setting of PYTHONPATH and/or LD_LIBRARY_PATH, etc. Well, yes, but that's a PITA that I don't want to have to go through. I want to be able to distribute apps also, and not everyone is going to have the same paths as me, and certainly not the same on different OSs. > Chris> * Easy for developers - for testing with multiple versions etc > > That's fine, and precludes the use of something like a hardcoded > > import wxPython version '2.4' No, it doesn't. Change the 2.4 to 2.5 and you test again. However, there have been requests for: > a > WXPYTHON_VERSION environment variable which the wxPython framework could use > or for setting PYTHONPATH. yup, that's one option, but good for developers, not good for users. > > Chris> * Easy for users - their apps detect the right version to run > Chris> with > Getting the right version of dependent packages is an installation issue. > This should be detectable from either configure script, Makefile or > distutils setup.py script. Actually this is poorly worked, I don't want the app to detect anything, I want to to specify something: import wx-2_5 as wx for instance. > Chris> * Cross-Platform solution > > Distribute your apps with .bat file front ends on Windows, shell scripts > on Unix. Yuck, yuck yuck! First of all, I don't know a .bat from a hole in the ground (though I suppose I need to learn this to deal with python versioning anyway..sigh), and second of all, I'd much rather not have to write a wrapper script around a twenty line utility script (or a 2000 line one either!), and third of all, the wrapper script would be platform and individual system dependent > Chris> * The ability for the programmer to specify the version used in > Chris> the code, ideally only on (or before) the first import of > Chris> wxPython > I fail to understand why that's a problem that needs to be addressed in the > Python program. This is information which is know before the program is > run. It belongs in an environment variable or front-end shell/bat script. A front-end script script is one solution to these problems, but it's another layer I would rather not have to deal with! Another issue is for OS_X BundleBuilder Bundles. You can build them to use the Python installation, so I'd like to be able to to the version specifying inside the python script, not outside of it. > Chris> * The ability to specify the version wanted with an environment Chris> variable, so that multiple versions could be easily tested > > This is the correct way to do this. It is ONE way to so it, not THE way. > Chris> * The ability to specify multiple versions that all work, in a Chris> ordered list of some sort. > Your installation program should detect all installed versions and pick the > latest version which intersects with the set of multiple working versions. Again, simple solutions for simple problems. I don't want to write a complex installer. Frankly, I think this is getting too fancy (though it would be nice). I'm just as happy to have my apps Require a particular version, that way I know I've tested there. Disk space it cheap. > Chris> * The ability to specify a "minimal" version, and higher versions Chris> could be used. > > Again, this goes in your setup.py script (or configure, or Makefile, or > whatever). It's an install-time decision. Again with the installer! What's wrong with dropping a script in /usr/local/bin? Granted when you get beyond small utilities, there is often a need for a proper installer, but in that case, you could be building stand alone apps with PY2EXE or whatever anyway. > Chris> * The ability for "from wx.lib import Something" to work as well, Chris> respecting the version > Assuming your installation software worked correctly this should be a > no-brainer. ;-) This was addressing why you couldn't just do: import wx-2_5 as wx because then you'd have to change all the "wx" to "wx-2-2_5" everywhere else which could get ugly. One thing that makes this harder, at least for wxPython, is that there is a legacy way that wxPython has been installed and imported, and people would like to preserve that, so that import wx and from wx.lib import Something and import wx.lib.Something need to all still work. By the way, as my thought about this started with wxPython, and now I'm advocating a more general solution, I realize there are some differences. A big one is that you could never use more than one version of wxPython in a single program, but you might very well be able to use multiple versions of other packages in the same program. So, while for wxPython it makes sense for __main__ to specify the wxPython version, and all other modules that "import wx" get than version, this may not be the case with other packages, where each module using it might want a different version. This is really analogous to shared libraries. I see a Python package as no different to a shared lib in function. When you compile and link and app, the version of the shared lib is specified. When it is run, the linker looks for an links that version. The user doesn't have to set an environment variable first, or change the lib path, or anything else. All I'm looking for is that same functionality. Does anyone remember the old DOS days of DLL hell? why would we want that? (Is Windows any better now? I'm wouldn't know) -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From mail at joachim-bauch.de Mon May 10 19:02:53 2004 From: mail at joachim-bauch.de (Joachim Bauch) Date: Tue, 11 May 2004 01:02:53 +0200 Subject: [ANN] PyLZMA 0.0.3 Message-ID: <40A00A1D.6040908@joachim-bauch.de> Hi, I'm pleased to announce the release of PyLZMA 0.0.3. PyLZMA is a Python wrapper around the LZMA SDK by Igor Pavlov and allowes you to use great compression ratios in your Python programs. Typically, LZMA compresses data about 20% better than bzip2. New features in this release: - compression from a file-like object - streaming decompression via multiple calls to "decompress" - initial library that supports reading of 7-zip archives It should run on all platforms (currently being tested on Windows and Linux). Grab it from http://www.joachim-bauch.de/projects/python/pylzma Subversion repository available at https://leviathan.joachim-bauch.de/cgi-bin/viewcvs.cgi/pylzma/trunk/ Feedback welcome! Greetings, Joachim From sbard at lexpert-auto.com Tue May 25 08:44:49 2004 From: sbard at lexpert-auto.com (sbard at lexpert-auto.com) Date: Tue, 25 May 2004 14:44:49 +0200 Subject: hard disk serial Message-ID: Hi every one I try to get hard disk serial number how can i do this ? -> THANK'S A LOT From Sebastien.Perochon at mmarelli-se.com Tue May 25 12:26:38 2004 From: Sebastien.Perochon at mmarelli-se.com (Perochon Sebastien) Date: Tue, 25 May 2004 18:26:38 +0200 Subject: Displaying os commands Message-ID: <33F0779A2CA2D711BECF0002A545B67AA7D72B@ex5chantd01.chatellerault.marelli.fr> Thanks for all your answers. I just wanted to know if python got a variable to enable/disable the output. It seems not. Thanks, Sebastien. -----Message d'origine----- De: Dennis Lee Bieber [mailto:wlfraed at ix.netcom.com] Date: mardi 25 mai 2004 18:03 ?: python-list at python.org Objet: Re: Displaying os commands On Tue, 25 May 2004 15:57:41 +0200, "Fredrik Lundh" declaimed the following in comp.lang.python: > > the command is dir, not c:\dir. > I suspect that was supposed to be c:\>dir IE, the console prompt followed by the submitted command text. > > How to display the launched command ? > > print command > os.system(command) > If I'm right, the more complete code would be: print "".join([os.getcwd(), ">", command]) os.system(command) -- > ============================================================== < > 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 dmq at gain.com Wed May 19 17:56:05 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 19 May 2004 14:56:05 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> Message-ID: <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> On 17 May 2004 20:11:44 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:<4ka7a0t585802d81i417j5ufmrdjbq6hei at 4ax.com>... >> We need to make a distinction between users and programmers in our >> expectations of what kind of errors they will make. Users only need >> to *read* a class definition and understand what it does. Programmers >> are the group that needs to remember to add a call to the superclass >> when they write a new class. >> >> I am a user of the Qt Toolkit, but I would not attempt to add a class >> to their existing hierarchy. Nor would I expect Trolltech to provide >> me with some kind of robust class-generating function that was >> guaranteed to generate an error-free class at any point in their >> hierarchy I might chose to insert it. > >If you're writing code, you're writing it to be modified at some >point, unless it's a few lines-long script. If the modifications are >made by someone else then they will reasonably expect that the code >doesn't contain implicit deathtraps, like non-local data. The trade-off, in the case of _numAnimals is: Do we want a simple program with instant display of this number, or a more complex program that scans the entire hierarchy to re-create the total every time it is needed. There is an analogy in the netlisting programs used in circuit design. Netlisting a big design is a time-consuming operation, so each cell is netlisted when it is saved. When the design is simulated, there is a quick check of the time-stamps on the entire hierarchy, to make sure all of the incremental netlists are up-to-date. One could argue that somehow the time-stamps could get out-of-sync (incorrect clock setting on a client machine, etc.). Yet nobody says that not netlisting the entire design every time is bad programming. It's always a compromise. Robustness is never absolute. -- Dave From pvl at por.to Thu May 13 07:54:19 2004 From: pvl at por.to (Pedro Lima) Date: Thu, 13 May 2004 12:54:19 +0100 Subject: General Ledger/Accounting Libraries References: Message-ID: You may also want to check this project: custom.sourceforge.net From paulo.pinto at cern.ch Fri May 7 04:31:50 2004 From: paulo.pinto at cern.ch (Paulo Pinto) Date: Fri, 07 May 2004 10:31:50 +0200 Subject: A simple xml.dom.minidom question In-Reply-To: <409ab05f$0$24803$9b622d9e@news.freenet.de> References: <409ab05f$0$24803$9b622d9e@news.freenet.de> Message-ID: There are a set of applications that use XML files as their configuration mechanism. Inside these files there is some data that isn't standard XML but it in form expected by the tools. For example "value1" "value2" Now, if I use writexml(), I get the following, "value1" "value2" Which I understand, because it is how it should be in standard XML. However I am really required to use the first form. So I guess that the only way with xml.dom.minidom is to write my own code to tranverse the XML tree. Right? -- Paulo Martin v. L?wis wrote: > Paulo Pinto wrote: > >> I want to have some control of how the xml in writexml() is >> written. > > > Depending on precisely what kind of control you want to have: > yes, that is possible. > >> Is that possible? Or do I have to do navigate the XML tree by >> myself? > > > That may also be the case. > > Regards, > Martin > From drw0rm at tmbg.org Tue May 25 03:48:33 2004 From: drw0rm at tmbg.org (Aquarion) Date: Tue, 25 May 2004 08:48:33 +0100 Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: On Tue, 25 May 2004 08:10:51 +1000, "mr_vocab" wrote: >i never got this its always in my tutial bookfor i in range(...) It's arbitrary, but some programmers use "i" in an iteration to either stand for iteration or index. -- Aq2 From indigo at bitglue.com Tue May 25 23:00:03 2004 From: indigo at bitglue.com (Phil Frost) Date: Tue, 25 May 2004 23:00:03 -0400 Subject: Embedding Python at the OS level - build problems In-Reply-To: References: Message-ID: <20040526030003.GA12146@unununium.org> On Wed, May 26, 2004 at 01:09:38AM +0000, Ryan Paul wrote: > On Tue, 25 May 2004 20:34:14 -0400, Phil Frost wrote: > > > Greetings all. I'm attempting to embed a python interpreter at a very > > low level in an OS I am writing. > > > > [snip lotts of problems] > > interesting project. what are the benefits of integrating python into an > operating system? I could understand making kernel modules for services > that you would otherwise run as a daemon, but what is the motivation for > such low level integration of a high level interpreter? Well, it's an interesting story... The project started entirely in x86 assembly, and we got something like modern MS-DOS done like that. We had fun playing with the hardware, and breaking floppy drives by seeking them too far, and it was very fast, but we looked back and realized we hadn't really written anything new, so we started a rewrite. We have produced tons of ideas now, and some of them we think are even new. One side effect of this is that we are often rewriting code to fit new ideas, which really becomes a pain in assembly, because slight changes in function might require now eight registers, rather than the usually availible 7, and well, now you have to rewrite the whole thing to accommodate an additional parameter. Of course the usual solution is "use C!", but I hate C. It's almost as much of a pain as assembly, but it doesn't allow anything near the freedom or the satisfaction of working directly with the hardware. It's my belief that there are two enjoyable aspects to programming: the joy of creation, and the satisfaction of solving a puzzle. C removes most of the puzzle aspect because no longer must one allocate registers and optimize. It also deemphisizes the creation aspect by requiring the programer to manage all the tedious aspects of computing - memory management, string manipulation, basic data structures, etc. Very little time is spent creating something new in C. Consequently, it was decided that a language should be assembly, and failing that it should remain a joy to use. We considered many languages that were not C, such as D, Ada, Ocaml, and Python, as well as dozens of languages too academic to remain in my memory. D and Ada both fall short of the goal of a joyful language. Ocaml was definately cool, especially since it maintains extremely good performance. However, it's not as accessible as Python. Of course, I realize Python isn't exactly erm...fast. It is my belief that this is a matter of the way python is run, and not a problem with the language itself. Current projects such as Pyrex and Psyco demonstrate that Python can be made faster, and I think this trend will continue. Furthermore, in the worst case we can always write Python modules in C, or assembly (wheee!) where speed is important, and take comfort in knowing that the rest of our code is maintainble, allowing us to focus on making an OS and not cursing at C. If you are interested, our webpage is http://unununium.org/. I hear that the page looks very professional all the time, but I must say at this point it's mostly fluff. There really isn't much of an OS there, and most of our ideas havn't been documented. Time and money have been in very short supply recently, so the project has been nearly idle for longer than I'd like to admit. However, some day... -- Phil Frost From elainejackson7355 at home.com Fri May 14 11:32:32 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 14 May 2004 15:32:32 GMT Subject: looping over the files in a directory Message-ID: Can anyone please tell me the actual syntax for saying something like this: for in : (?) Muchas gracias. Peace From bram at nospam.sara.nl Wed May 12 10:24:38 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 12 May 2004 16:24:38 +0200 Subject: win32com and Excel Message-ID: <20040512162438.68134d36@pistache.sara.nl> Hi there, I am accessing Excel's functionality via COM, by using the win32com extention. This works somewhat: If I run it from the 'IDLE' editor, I get frequent hangs or errors. Sometimes the app hangs, and Excel then waits indefinately for a COM operation completion. Sometimes, I get errors about properties not being writable (which realy are writable). I then need to kill excel en python stuff, and try again. Sometimes it works, sometimes I get in a corrupt state. Running without the IDLE environment, I get much better results. After checking the testMSOfficeEvents.py file, I deciced to add a OnQuit() to my event handler. Strangely enough, OnQuit events are only sent for MS-Word, and not MS-Excel. Is this an ommission in win32com, or in MS Excel itself? I cant find a mention of OnQuit in the Visual Basic script help files. I would like to discern between the closing of a workbook, and the closing of the entire excel app. Thx, Bram Stolk -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From frank at chagford.com Sun May 2 03:34:49 2004 From: frank at chagford.com (Frank Millman) Date: 2 May 2004 00:34:49 -0700 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> Message-ID: <246a4e07.0405012334.5e5474db@posting.google.com> Heather Coppersmith wrote in message news:... > On 1 May 2004 05:47:20 -0700, > frank at chagford.com (Frank Millman) wrote: > > [ details of a multi-level object hierarchy, and worries of __init__ > methods bypassing it ] > > > By inheriting from the incorrect class, the special methods to > > handle a 'Master' type table have been bypassed. My question is, > > how can Table check that objects have inherited from the correct > > subclasses? > > Python usually takes the "we're all adults here" point of view, > and leaves that question to unit tests and/or code reviews. No > amount of B&D is sufficient to protect from a malicious coder > anyway. > I fully agree, but this is not the scenario I am trying to cater for. I will explain what I am doing - maybe you can suggest a better approach. I am writing a general-purpose accounting/business package. It is the nature of such beasts that no matter how powerful/generalised it is, certain users will always have special requirements. I am therefore including a large number of 'hooks' where users or their consultants can add their own code without interfering with the main body of code. One example of this is adding features to a particular database table definition. I have a standard class definition to represent a table, with various attributes and methods. I allow the user to create their own subclass for a particular table, adding/overriding where necessary. I have a function to 'open' a table. This uses a try/except to 'try' to import and instantiate a subclass for the table, 'except' instantiate the standard class. I have recently introduced the concept of a 'table type', such as 'Master' or 'Transaction', and have written my own subclasses with standard methods to handle each type of table. The table type is passed as an argument to the 'open' function. which now checks for a user-defined subclass first, if not found checks the type to see if a standard subclass exists, if not found instantiates the main class. This works well. The concern is that a table may be of type Master, but a user may create their own subclass and inherit from Table instead of Master by mistake. I want to detect this error and raise an exception. > > You could unwind the stack frame and look at who's calling > Table.__init__, but that's rather un-Pythonic, too. > I do not know what this means, and I really do not want to know :-) > IMO, the most Pythonic solution is to provide factory functions > that do the Right Thing instead of instantiating your classes > directly from your application code. > If you can give a simple example, I would be interested in learning more about this. Alternatively, I will leave things as they are for now, and focus on getting my app to a point where I can get some live installations. If things look promising, I will release it as Open Source, and then I will be very happy to get feedback on this and, I am sure, many other aspects of my coding that could be substantially improved. > HTH, > Heather Many thanks for your input. Frank ps What does B&D mean? From sholden at holdenweb.com Mon May 17 08:42:32 2004 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 17 May 2004 08:42:32 -0400 Subject: RELEASED Mailman 2.1.5 In-Reply-To: References: Message-ID: Barry Warsaw wrote: > Today I am releasing Mailman 2.1.5, a bug fix release that also contains > new support for the Turkish language, and a few minor new features. > Mailman is free software for managing email mailing lists and > e-newsletters. Mailman is used for all the python.org mailing lists. > > Mailman 2.1.5 is a significant upgrade which should improve disk i/o > performance, administrative overhead for discarding held spams, and the > behavior of bouncing member disables. This version also contains a fix > for an exploit that could allow 3rd parties to retrieve member > passwords. It is thus highly recommended that all existing sites > upgrade to the latest version. > > For more information, please see: > > http://www.list.org > http://mailman.sf.net > http://www.gnu.org/software/mailman > > Finally, a personal note. I have left Zope Corporation to join Secure > Software, a company started by John Viega -- Mailman's original author. > Although I won't be working on Mailman in any official capacity, it is > exciting to be working with him and the rest of the folks there. I > leave Zope Corp on a positive note and wish nothing but success for them > too. > > You can find Secure Software on the web at > http://www.securesoftware.com. Please continue to use my > barry at python.org email address for all Mailman correspondences. I don't > expect much to change for the Mailman project at all. > > Enjoy, > -Barry > > 2.1.5 (15-May-2004) > > - The admindb page has a checkbox that allows you to discard all held > messages that are marked Defer. On heavy lists with lots of spam holds, > this makes clearing them much faster. > > - The qrunner system has changed to use only one file per message. > However the configuration variable METADATA_FORMAT has been removed, and > support for SAVE_MSGS_AS_PICKLES has been changed. The latter no longer > writes messages as plain text. Instead, they are stored as pickles of > plain strings, using the text pickle format. This still makes them > non-binary files readable and editable by humans. > > bin/dumpdb also works differently. It will print out the entire pickle > file (with more verbosity) and if used with 'python -i', it binds msg to > a list of all objects found in the pickle file. > > Removed from Defaults.py: PENDINGDB_LOCK_TIMEOUT, > PENDINGDB_LOCK_ATTEMPTS, METAFMT_MARSHAL, METAFMT_BSDDB_NATIVE, > METAFMT_ASCII, METADATA_FORMAT > > - The bounce processor has been redesigned so that now when an address's > bounce score reaches the threshold, that address will be sent a probe > message. Only if the probe bounces will the address be disabled. The > score is reset to zero when the probe is sent. Also, bounce events are > now kept in an event file instead of in memory. This should help > contain the bloat of the BounceRunner. > > New supporting variables in Defaults.py: VERP_PROBE_FORMAT, > VERP_PROBE_REGEXP > > REGISTER_BOUNCES_EVERY is promoted to a Defaults.py variable. > > - The pending database has been changed from a global pickle file, to a > unique pickle file per mailing list. > > - The 'request' database file has changed from a marshal, to the more > secure pickle format. > > - Disallow multiple password retrievals. > > - The email package is updated to version 2.5.5. > > - New language: Turkish. > > - Bugs and patches: 869644, 869647 (NotAMemberError for old cookie data), > 878087 (bug in Slovenian catalog), 899263 (ignore duplicate pending > ids), 810675 (discard all defers button) > > Barry: I hope this is congrats time. How's Jim Fulton nowadays, I don't hear much of him lately. regards Steve From nospan at thanks.com Mon May 3 20:24:32 2004 From: nospan at thanks.com (Allan Hughes) Date: Mon, 03 May 2004 19:24:32 -0500 Subject: Distributing a Python App In-Reply-To: <4096cf70$0$568$e4fe514c@news.xs4all.nl> References: <109dec4c2bdn38e@corp.supernews.com> <4096cf70$0$568$e4fe514c@news.xs4all.nl> Message-ID: <109dom0k7mqqu95@corp.supernews.com> Irmen de Jong wrote: > Allan Hughes wrote: > >> I'm a python noob and have a question. >> >> I would like to write a little app and then share it with others. >> >> It is going to need to store potentially large amounts of data and >> then generate reports based on that data. >> >> I could just write to a DB, but that wouldn't be very portable. > > > Define "a DB". MySQL for instance. >> I would like a solution that will work 'out of the box' for any old >> shmo who wants to use it without worrying about whether they have the >> right DB. How can I build this in? Suggestion? What have you done >> in the past? > > > I've successfully used plain text data files, standard Python pickles, > and an (py)sqlite embedded database. None of them requires a full-blown > database engine to be present. PySQLite is also a self-contained package. > It depends on the amount and structure of your data what the best > solution will be. I'm looking to records detailing network status, which will be updated frequently. I then want to be able to retrieve and sort the data to present reports based on that data. PySQLite sounds like it might be a good solution. I have never done any kind of distribution of a desktop app before, so maybe this is a dumb question. I'm guessing I could use some sort of tool to package the python app and PySQLite into one nice tidy package which the end user could then install? Or something like that... From vonehr at ipm.fhg.de Thu May 27 13:18:04 2004 From: vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 27 May 2004 19:18:04 +0200 Subject: send event from extension? Message-ID: Hi everybody, I'd like to create an event which I have to post/set within an extension (new frame signal from a camera). In python I would like to react on this event. How could I create and post the event in c and how could I receive it in a python event handler routine done with the win32event module? Thanks for any answer, Markus From peter at engcorp.com Sun May 23 09:07:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 May 2004 09:07:31 -0400 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <30260531.0405222153.5027c135@posting.google.com> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: simo wrote: > Proper encapsulation is needed before the C++ brigade will take > P[y/ro]thon seriously as an OO language If by "C++ brigade" you mean simply "C++ programmers", then I can assure you that you are wrong since I was, once, such a beast. If by "C++ brigade" you mean "programmers who think C++ does things the right way" then the only way to get them to take Python seriously will be either (a) to change Python into something that closely resembles C++, or (b) to change those programmers so that their thinking fits Python better. Merely adding "proper encapsulation" (and I happen to believe Python already has encapsulation that is quite proper) will not suffice. And that's a good thing, too.... ;-) -Peter From ssk at chol.nospam.net Mon May 24 16:13:07 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Mon, 24 May 2004 20:13:07 GMT Subject: urllib.urlretrieve error References: <87pt8t1vk6.fsf@pobox.com> Message-ID: Thanks for the reply. The problem was that url was wrong. It's not the library's fault...:-) Thanks again. Sam "John J. Lee" wrote in message news:87pt8t1vk6.fsf at pobox.com... > "Sam Sungshik Kong" writes: > > > Hello! > > Hello! > > > I'm trying to download PDF files from web to my computer using urllib. > > Some pdf files are fine but other files are downloaded only 6kB which is > > wrong. > > It didn't show any error message. > > > > I use urllib.urlretrieve(url, fn). > > > > So I tried to download with Internet Explorer and it worked fine. > > > > Anyone knows why? > > What was the content of the 6kb file? Don't assume it was the first > 6kb of the PDF file: for instance, it may be an HTML page. > > > > My another question is how I can retrieve "mms:..." files. > > urllib.urlretrieve doesn't work with that protocol. > > IIRC, that's a proprietary Microsoft scheme that's designed for > 'streaming' (ie. downloading and playing back the contents at the same > time). I think there's a dodgy C program around somewhere which is > just about able to grab them, but I don't know of a Python-accessible > implementation. > > > John From RobbTiger at softhome.net Thu May 20 12:18:07 2004 From: RobbTiger at softhome.net (Noldoaran) Date: 20 May 2004 09:18:07 -0700 Subject: "Extracting" a dictionary References: Message-ID: <5fd6ba56.0405200818.60b0259@posting.google.com> Arnold Filip: > How about this: > > In [1]: d = {'foo' : 23, 'bar' : 42} > > In [2]: for item in d.items(): > ...: exec "%s = %d" % item > ...: > > In [3]: foo > Out[3]: 23 > > In [4]: bar > Out[4]: 42 you could extract them in to there own namespace: >>> class AttrDict: ... def __init__(self, d): ... self.__d = d ... def __getattr__(self,attr): ... return self.__d[attr] ... def __setattr__(self,attr,value): ... self.__d[attr] = value ... def __delattr__(self,attr): ... del self.__d[attr] ... >>> d = AttrDict({'foo' : 23, 'bar' : 42}) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ File "", line 10, in __setattr__ (snip) RuntimeError: maximum recursion depth exceeded >>> d.foo That didn't work like I hoped. I decided to share it anyway in case someone can get it to work. --Noldoaran From n/a Sun May 30 13:25:12 2004 From: n/a (Maboroshi) Date: Sun, 30 May 2004 10:25:12 -0700 Subject: Jython Forum Message-ID: <10bk67t3t6sqp4b@corp.supernews.com> Just thought I would let everyone know of my Jython Forum I couldn't really find one specific to Jython so I set this up if anyone wants to contribute anything visit http://www.pacificflame.com and if you think its a stupid idea let me know if you have any ideas for the forum please post to this message From dave at pythonapocrypha.com Sun May 23 23:23:43 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 23 May 2004 21:23:43 -0600 Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: <019e01c4413e$84f0d510$6500a8c0@YODA> David MacQuigg wrote: > >> I can't comment on the usage statistics you cite, but it seems to me > >> that unbound methods are more important than these statistics would > >> imply. > > > >All I'm saying is that for most programs, the bound method form is way, way, > >way more commonly used than is the unbound calling form. > > I would agree if you cut out two of the "ways" in this sentence. :>) Well, for kicks I looked at the standard Python library, since I figured it would have the greatest concentration of unbound method use (my reasoning was that since it was a library more than a consumer of a library, you'd have lots of class hierarchies and therefore more occurences of unbound method calls to super classes. Even in this situation it appears that unbound method calls are less than 2% of all method calls. The real point is simply that unbound method calls are pretty rare. > Still this is like saying names that start with the letter 'q' are way > less common than all other names, so it is OK if we have a special > form for functions with such names. Not at all - that's a flawed analogy because variable names can be pretty arbitrary and interchangable. The different types of function calls, method invocations, whatever, are neither arbitrary nor interchangable. > I've never stated or implied that unbound methods are as common as > bound methods. Nor would I say that confusion abounds. The different > calling sequences are just an unnecessary complexity that trips up > some new users, especially those that don't have experience in some > other OOP language. I'm beginning to understand the real root of the disagreement - you see no value in the differences and therefore see the existence of the differences as a flaw. But that's just the problem: these are not merely syntactic differences, but they are semantic - they are different in purpose and in use, so your suggestion to get rid of them seems very unappealing: from my perspective you are removing something useful from the language to solve a "problem" that I've yet to encounter, or seen anyone else encounter (including new users of the language). > > I know what static methods are _for_, but I don't see what is > >necessarily complex about them, nor how your proposed unification would help - > >in fact, ISTM that it would make it much more confusing because both the > >implementor and caller of the code would never be quite sure if the method was > >a static one or not, and that's something that needs to be known by both > >parties. > > I think you have not understood the proposal. It is *not* necessary > in the new syntax to know the difference between a static and > non-static method. There *is* no difference. A "static method" (a > function without instance variables) simply ignores __self__. And this is why the proposal seems so lousy: the difference between a static and a non-static method is _not_ just a syntactic difference, their existance is not _caused by_ the syntax. The syntax merely reflects that they are different things to begin with. They are different tools, different features - you use them for different things, so making them appear identical to the maintainer of the code and the caller of the code seems like a really bad idea - a maintenance nightmare. If you remove any syntactic difference, then that information is lost from the code itself. But since that info is useful, people will instead track that info in comments or something - yuck. > The differences are an artifact of the syntax, not any fundamental > difference in purpose. Normal methods have a special first argument. > Static methods do not. That's all there is to it. No, no, no - they are different tools, plain and simple. The difference just isn't skin deep - changing the syntax won't make them go away, it'll instead make the language more ambiguous. Without meaning to be offensive, I must ask: how much have you actually used any of these features you're interesting in consolidating? (static method, unbound methods, bound methods, etc.) > If there is were some fundamental purpose to static methods, there > would be something they can do that can't be done with the proposed > simpler syntax? That's just my point: after consolidating the syntax, static methods will still exist, but there will be no way of knowing which ones are static and which ones aren't _without reading every line of the code_ - there will be no syntactic way to express the idea. Egads! > I may be wrong, but it looks to me like there *are* no benefits of the > current binding syntax over the proposed syntax. Yes, I understand that it looks that way to you, but why is it that so many people who have used the language for a long time disagree with you? Is it because everyone else has blinders on? Could it be _possible_ that these features have value and/or that the solution you propose is worse than what currently exists? Again, how much did you use the language before coming to the conclusion that you have? > What are the benefits of the current design? I guess my real gripe with the proposal is that it takes what is currently clear and makes sense and combines it in such a way to make it ambiguous to everyone involved with the code. The features you propose consolidating really are different in real programs, and making them all look the same just for the heck of it doesn't seem to make much sense. > What can you do in the current syntax that can't be done more easily in the proposed syntax? Understand my code 6 months from now. Modify the code with less risk. Understand the level of intent in someone else's code I'm using. > Show me some code, and I will show you the equivalent in "Python 3". No, that burden is on your shoulders, as everyone not in favor of your suggestions can let the thread die off and nothing will change. <0.5 wink> In another thread I suggested you take the time to learn what the 2 or 3 most common uses are for each of the features that will be affected, and show both the implementation and use in current Python and after your proposed changes. Not only will doing this give a clear example to everyone, it'll also show that you are at least aware of how the different function/method forms are used today in _real programs_ and not contrived examples - after re-reading some of your comments I have my doubts. > >> When you say the distinction between methods and functions makes > >> sense, I assume you mean it has some value to the user. I would like > >> to hear more about this, because I am assuming just the opposite. > > > >Yes it has some value, but more than that: it fits the brain quite well. IMO it > >adheres to the principle of least surprise, > > The Principle of Least Surprise has always been one of my favorites. > It's a shame this principle offers us so little guidance in resolving > a simple issue like this unification question. All of those guiding principles are subjective, but IMO it's pretty clear here :) > us in opposite directions. I think the difference may be in our > backgrounds. You seem quite comfortable with Java, so I would guess > these different method forms fit with what you have learned there. I abhor Java, actually, and I'm not even sure how to do the bound method form in Java (or C++, which is where my background lies more than Java). > I need to feel like I understand what is going on. I'm not > comfortable with a bunch of arbitrary rules Please understand that these are not arbitrary. The fact that you think they are arbitrary makes me wonder if you really understand them. Don't be offended! > especially if I > frequently run into cases where forgetting the rules can cause a problem. What I like about the current syntax, is that you don't really need to memorize any rules because how you call them is pretty obvious, unless of course you're not thinking about what you're doing, in which case there are bigger problems at hand. For example, when I learned Python I never came across some tutorial showing how to do an unbound method call - I got to the point where I needed it, I tried the most obvious thing, and it worked. Likewise, the first time I needed to get a reference to a bound method, I was impressed that the first thing I tried worked (impressed with the language, not with myself :) ). > I need specific examples of problems introduced by the new syntax, or > of something the old syntax can do better. We can argue general > principles forever, but one good example will settle this question. Like I said, if you really are interested in making headway with your proposal, *you* need to demonstrate through some non-contrived examples that you understand how things work today. I've read the pages on your site and either they don't show all cases that will be affected, or the examples are too buried by other changes so I missed them. So, show a few examples of how bound methods are implemented and used today in Python, and how they'd be used and implemented the new way. Show a few examples of how unbound methods are implemented and used today, etc. Just showing one example and stating that everything will be like that glosses over the fact that these things are all used in very different ways today, and leaves the reader wondering if you have really thought things through. > We can learn a lot by looking at > how languages designed *after* Python have tried to improve on it. Look at the changes to Python, especially over the past few years - many of the features are publicly credited as having come from other languages. -Dave From donn at u.washington.edu Thu May 6 14:39:01 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 06 May 2004 11:39:01 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <1083822394.7883@yasure> Message-ID: In article , David MacQuigg wrote: ... > How did you know to add self in Mammal.talk(self)? This is a perfect > example of an experienced Python programmer sailing right past a > problem that trips up less proficient users, and not even being aware > that the problem exists. What surprises me is that even after > pointing out a problem like this, I will get someone telling me -- > It's real simple, dummy. Mammal is a class. When you call a method > from a class, you get an unbound method, which requires an explicit > 'self'. > > Yes, I know that. I remember it because I use Python almost every > day. My students and clients, three months after learning it, will > not remember. Maybe they won't, I don't know. But if it's difficult, it's a benign sort of difficulty. You CAN understand how it works, you can't use it WITHOUT understanding how it works, and the more you use it, the more obvious it becomes (sail right past.) This is what Python is all about - a consistent, explicit system. If you're searching for unbearable difficulties, I'd look for things you can use without understanding, like the object/reference storage model, and its interactions with mutable default parameters, +=, etc. But at any rate, from my perspective, this is your problem, not your students and clients problems. I've been hearing for years from sophisticated users who think they know how to speak for the unsophisticated users, and after a couple decades I have come to be highly skeptical. I've dealt with scientists myself, and I think I have an idea of what you're talking about, the principles make sense, but the connection between the general principles and the specific details ... a black art. You're not unique here because you represent non-programmers, you have a unique idea of how that relates to the language. As would anyone. My own perspective is, present the core language and leave them to solve problems in that model, "bad programming" or not. The static method, for example, is not really a core concept - not just the implementation, but the basic principle. So don't go there. You'll be surprised at how little pain they feel over software engineering issues. Actually, my only Python-using colleague here, really the only one who actively uses Python for our core software, doesn't even use "class". Donn Cave, donn at u.washington.edu From cappy2112 at yahoo.com Mon May 31 03:31:48 2004 From: cappy2112 at yahoo.com (Tony C) Date: 31 May 2004 00:31:48 -0700 Subject: OT: Python in a Nutshell References: Message-ID: <8d3e714e.0405302311.82eab7b@posting.google.com> "kbass" wrote in message news:... > Does anyone have an idea when the next release of the book, ' Python in a > Nutshell' will come out? I am looking for reference material that covers > Python 2.3 other than the online documentation. I also notice that Amazon > and other book outlets have cut the price on this book so I am hoping that > this is an indication that another book is coming out soon. Your thoughts. > Thanks! > > kbass Python in a Nutshell DOES cover Python 2.3(but not exclusively), and often contrasts the differences between 2.2, and 2.3. (Take a look at the upper right corner of the book) Learning Python Second Edition (also from Oreilly) also covers Python 2.3, and was just released in 2004 From me at privacy.net Fri May 21 07:10:36 2004 From: me at privacy.net (Heather Coppersmith) Date: 21 May 2004 07:10:36 -0400 Subject: Python compilers? References: <38Yqc.166$eO6.128@fe2.columbus.rr.com> <7x1xlf8p9z.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 21 May 2004 03:03:51 GMT, Carl Banks wrote: > Paul Rubin wrote: >> >> >> Carl Banks writes: >>> > The example above kills any attempt to turn a.bar() into a static >>> > procedure call. >>> >>> Of course it does--but it's one method. A compiler, if it's good, >>> would only make the optization on methods named "bar", and it could >>> probably pare the number of possible classes it could happen to down >>> to only a few. >> >> How could it possibly know? The reassignment of a.bar could happen >> anytime, anywhere in the code. Maybe even in an eval. > And if it happens anytime, anywhere in the code, the compiler will see > it and create more general code. Or is that impossible? The compiler might not see it. Any function/method/module called while a is in scope might change a.bar. It doesn't even take a perverted introspection tool: module foo: import bar class C: pass a = C( ) a.bar = 'bar' bar.bar( a ) a.bar = a.bar + 'bar' # which 'add' instruction should this compile to? module bar: def bar( x ): x.bar = 3 > As for eval, well it would be silly to even allow eval in a compiled > program; kind of defeats the purpose of compling. You might let it > run in its own namespace so it can only affect certain objects. I reiterate my comments regarding type declarations, add new comments regarding backwards compatibility, and note that Lisp allows eval in compiled code. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From j_mckitrick at bigfoot.com Tue May 4 22:51:25 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 May 2004 19:51:25 -0700 Subject: Different values for property vs attribute??? References: Message-ID: > As someone else pointed out in another thread within the last 24 hours, > properties are only supported for new-style classes. Try changing the first > line to > > class Klass(object): > > and see if it works. That was it, thanks. Sorry for the redundant question, but didn't know (object) was necessary. I thought the new interpreter added those qualities automagically. thanks again From no.email at please.invalid Wed May 5 03:10:03 2004 From: no.email at please.invalid (Guido) Date: Wed, 05 May 2004 07:10:03 GMT Subject: curses and python (linux, debian) In-Reply-To: References: <4jQlc.95615$YC1.6104179@phobos.telenet-ops.be> Message-ID: David M. Cooke wrote: >> >>Now, i'm using DrPython, it looks fine, but i can't debug my curses >>program >> >>It gives an error with this message: curses.wrapper returned ERR on >>curses.cbreak > > > I'm not familiar with DrPython, but it looks like a IDE. The console > widget it uses for the Python shell probably doesn't support enough to > be a 'real' terminal, so curses likely doesn't work in it. You'll have > to run it in a terminal program like xterm. > > >>if i run it with python, it works! > > > From the command line, right? There you go :-) > well, I like a good editor, and DrPython seemed nice. Do you have any other suggestions? Otherwise I'll stay with the combo solution From jepler at unpythonic.net Sun May 23 20:47:28 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 23 May 2004 19:47:28 -0500 Subject: Reading a file, sans whitespace In-Reply-To: <10b2dvrfqhmbm5a@corp.supernews.com> References: <8a0bb987.0405221102.dc679ff@posting.google.com> <5sl4o1-crf.ln1@eskimo.tundraware.com> <10avdpe73rnj20d@corp.supernews.com> <8a0bb987.0405222327.78ef180e@posting.google.com> <10b2dvrfqhmbm5a@corp.supernews.com> Message-ID: <20040524004728.GB17178@unpythonic.net> It looks like the impact of not compiling should be fairly small. sre.split calls sre._compile() which has a 100-entry cache. The total overhead is something like 3 function calls and a dictionary lookup. You might switch from in-line REs to compiled ones to get the last little bit of speed out of some code, but IMO the big reason is for code clarity and to re-use the same RE in multiple places without duplicating the RE string. Jeff From fumanchu at amor.org Sat May 29 11:14:08 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 29 May 2004 08:14:08 -0700 Subject: mod python confusion Message-ID: Kylotan wrote: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/225299 > > Hi Robert. You've recommended this recipe to me in the past > when I asked a similar question on this newsgroup. However, > I must admit that I really don't understand 90% of it, > since there are so many layers of abstraction and it spans > several classes - and indeed, 2 recipes! > Surely there has to be something simpler? Okay, let me break down the steps for just mod_python, so you can follow the logic. There is quite a bit of abstraction in the recipe, but for the most part, it's very linear--just broken up into parts you can swap out. Let's put it all in one module, which you place in your apache /htdocs/myapp folder. Say you have three web pages you wish to create: a default page, a "view" page, and an "edit" page. They might look like this: def default(req): req.write("Nothing to see here") return apache.OK def view(req): newData = util.FieldStorage(req, 1).list req.write("Now this is something") req.write(repr(newData)) req.write("
click me") return apache.OK def edit(req): req.write("Edited successfully.") return view(req) In the same file, you can include the mod_python interface and dispatching directly, if you want. The first part, the session initialization, boils down procedurally to this: from mod_python import apache, util def dispatch(req): atoms = req.uri.split("/") script = atoms.pop() # At this point, "script" = the name of the page # which was requested. So we dispatch based on # the value of "script". dispatches = {'default.htm': default, 'view.htm': view, 'edit.htm': edit, } try: nextHandler = self.dispatches[script] except KeyError: nextHandler = self.dispatches['default.htm'] return nextHandler(req) That's it for our demo module. The only thing left is to tell Apache that all requests should be handled by our dispatch() function. Therefore, in either the main Apache .conf file, or using another, included .conf file (which is more work but more maintainable) we write: AddHandler python-program .htm PythonHandler dispatch ...and you now have a working mod_python app. > Everything seems to suggest a major rewrite because I not only > need to shift from printing everything to calling req.write or > whatever, but I may also need to sort out some sort of dispatching > mechanism mapping URLs to functions if I use mod_python directly. Yes, you have a major rewrite on your hands. The reason I recommend abstracting the webserver as in the recipe is to avoid having to rewrite your application *again* the *next* time, when you stumble across Roxen and decide that's the coolest webserver yet. :) If you want to talk further about how to "meet in the middle", making an abstraction layer that better fits your application style, let's talk! I certainly don't use the recipe as-is; there's plenty to tweak. I'll also quickly note one other thing abstraction buys you: you don't have all of your core business logic hanging out in your /htdocs folder--you can move that back into site-packages where it belongs. In the recipe, the dispatch module (the only file in /htdocs) is only three lines. Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From mesteve_b at hotmail.com Sun May 9 10:16:43 2004 From: mesteve_b at hotmail.com (python newbie) Date: Sun, 09 May 2004 14:16:43 GMT Subject: Distutils confusion - probably something simple Message-ID: Ok, I am struggling with this setup.py. My python script happens to use the mxBase library, specifically the mx.DateTime package. That's the only "third party" package I use. I've gone through Nutshell book and the distutils docs, but am not getting the syntax probably.. I always get this at the end of the distutils command ( python setup.py py2exe ): The following modules appear to be missing <-- pasted directly ['mxDateTime.__version__'] ( A menu1.exe file is in fact created though) My setup.py is: ------------------------------------------ #!Python from distutils.core import setup import py2exe setup( console=["menu1.py"], name="MyBackup", version="1.0", packages=['mx', 'mx.DateTime'], py_modules=['menu1','OregonBackup','backup_config'], data_files=[('.',['backup.xml','some.ini'])] ) ------------------------------------------ ( incidentally, menu1.py specified above is the py file that calls everything else of course, but my OregonBackup.py file is what actually contains: "import mx.DateTime" - I don't know if that actually matters) I actually put all of my files directly into the C:\Python23\Lib\site-packages folder, so that "mx" folder can be seen by distutils. Running on Win XP. Thanks Steve From NAIGIMSESRIMAIL at gims.com Sat May 15 16:12:39 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sat, 15 May 2004 22:12:39 +0200 Subject: ALERT - GroupShield ticket number OB18_1084651946_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: aahz at pythoncraft.com Sent: -236577280,29637304 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1817 bytes Desc: not available URL: From usenet at zly_adres.com Tue May 18 19:23:53 2004 From: usenet at zly_adres.com (CYBER) Date: Wed, 19 May 2004 01:23:53 +0200 Subject: alternatives to making blocks like { } or other ?? In-Reply-To: References: Message-ID: > Of course there is another way! > > Just use # in front of your favourite block separator. > > I'm too lazy now to search the archives on who first suggested this, > but it works: > > def something(x): > #{ > return x > #} > > Thank you. From winexpert at hotmail.com Tue May 25 09:57:30 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 25 May 2004 13:57:30 +0000 Subject: hard disk serial Message-ID: I'm glad I could help. A lot of the windows apis are hard to find. I know when I was learning them i found the documentation to be less than wonderful. But i'm a beginner too now as I'm still learning python.... David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: >To: python-list at python.org >Subject: Re: hard disk serial >Date: Tue, 25 May 2004 15:44:40 +0200 > >THANK'S david !!!! >it's works very well !! > >i feel like a student, but sometimes it's good ! > > a ?crit dans le message de news: >c8vevf$9g4$1 at s1.read.news.oleane.net... > > Hi every one > > I try to get hard disk serial number > > how can i do this ? > > > > -> THANK'S A LOT > > > > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From me at privacy.net Wed May 5 09:11:19 2004 From: me at privacy.net (Duncan Booth) Date: 5 May 2004 13:11:19 GMT Subject: Several questions about embedding Python References: Message-ID: Miki Tebeka wrote in news:c79ucp$4i6$1 at news2.netvision.net.il: > I'm trying to extend a hardware simulator (written in C/C++) by > embedding Python. > After reading the documentation and playing around several questions > popped up: > > 1. Is there a way (using SWIG/Boost.Python ...) to export existing C/C++ > functions other than hand writing the wrapper functions. > Something like: py_export(a_c_function) > Since the Python module need to get information from the simulator I > can't just write pure SWIG wrapper (or can I?) If you have C-like functions (rather than C++ classes) take a look at Pyrex (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/). You still need to hand write wrapper functions, but in most cases they are pretty short. e.g. to wrap char *a_c_function(char *, int) you might get away with: cdef extern from "someheader.h": char *real_a_c_function(char *, int) "a_c_function" def a_c_function(s, i): return real_a_c_function(s, i) This would give you a module loadable in Python with a Python function a_c_function that passes its arguments through to to the underlying a_c_function written in C and converts the result back into a Python string. The quoted string in the function prototype renames the C function when used by Pyrex so you can reuse the same name. In most cases you are likely to want to do a bit more with arguments and results than just passing them through, and as soon as you do this Pyrex wins over SWIG. From azeemjobs at hotmail.com Mon May 31 16:39:42 2004 From: azeemjobs at hotmail.com (Mohammad Azeem) Date: Mon, 31 May 2004 15:39:42 -0500 Subject: XML Parsing problem using DOM Parser: HELP NEEDED Message-ID: An HTML attachment was scrubbed... URL: From kamikaze at kuoi.asui.uidaho.edu Wed May 5 16:18:18 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 5 May 2004 20:18:18 GMT Subject: a=([],); a[0]+=[1] References: <7ff790taojrrqka0trq9ltm82g0ac95ria@4ax.com> Message-ID: Andrea Griffini wrote on Sat, 01 May 2004 15:18:16 GMT: > When reading about python "warts" i stepped in this > example I find quite puzzling: > a = ( [] , ) > a[0] += [1] > this gives an error, because a tuple cannot be > modified. But if you print the content of "a" > it will show it has indeed been modified. > How can this happen ? if "+=" for list was called > then no modification to the tuple was requested and > so no error should have been raised; if instead "+" > and "=" was executed then after a failing assignment > the original list is safe... (or at least I thought > so; if you type "a[0] = [2]" you get the error and > "a" is not modified). > Is there an explanation simpler than investigating > on python sources ? First, as a matter of principle you probably shouldn't be modifying the contents of a tuple, even if those contents are mutable. What you're seeing is that += is shorthand for "add, then store back in the original container". So it appends to the mutable list, then tries to store that list back in the tuple, which fails. Here's an alternative: Python 2.3.3 (#1, Mar 10 2004, 15:56:38) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=([],) >>> a ([],) >>> a[0] [] >>> a[0].append(1) >>> a ([1],) But see "First" above, and don't do this. If you want the outer list to be mutable, use a mutable list instead of a tuple. -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From graham__fawcett at hotmail.com Wed May 12 09:39:42 2004 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 12 May 2004 06:39:42 -0700 Subject: OT: Idea for Python T-shirt References: Message-ID: Christos "TZOTZIOY" Georgiou wrote in message news:... > (Don't mind me, my frequent late night "I should be sleeping by now" > brainstorm) > > A python smiling, its body curled in the background, 1's and 0's visible > in its body visibly grouped in fours, and below the slogan: > > "With Python your nibbles explode with desire" > > I'll do one for myself :) Personally, I wouldn't post an announcement to Usenet that I'm about to "do one for myself", even when my nibbles /are/ exploding with desire. Maybe it's a cultural difference; Anglo-Canadians can be pretty modest about such things. Oh, you were talking about the t-shirt... -- Graham From wweston at att.net Sat May 1 20:00:47 2004 From: wweston at att.net (wes weston) Date: Sun, 02 May 2004 00:00:47 GMT Subject: why an exception In-Reply-To: References: Message-ID: Patch submitted. wes From gb at cs.unc.edu Mon May 24 16:31:00 2004 From: gb at cs.unc.edu (Gary Bishop) Date: 24 May 2004 16:31:00 -0400 Subject: ANN: Pyrex wrapper for the Aspell API References: <40b1ff18_3@news.unc.edu> <1c6dnV3--rqvsi_dRVn-vw@comcast.com> Message-ID: <40b25b84_3@news.unc.edu> Doug Holton wrote: > If you use distutils with pyrex then others won't have to download, > install and setup Aspell, MS Visual C++, or Pyrex to use your module. > http://ldots.org/pyrex-guide/2-compiling.html#distutils > http://www.python.org/doc/current/dist/ Done. You can now download a windows installer for the module. You'll need the source to see how to use it. The Windows installer is for Python2.3. gb From xaver_hinterhuber at web.de Mon May 17 06:15:15 2004 From: xaver_hinterhuber at web.de (Xaver Hinterhuber) Date: Mon, 17 May 2004 12:15:15 +0200 Subject: function causing core dump References: Message-ID: Hi Peter, I now have tried it. My problem is now, that I get unicode encoding errors. I am working on a german windoze machine. Could you plz give me a tip what encoding I should use (iso8859-1 and utf-8 dont't work)? -- with kind regards Xaver Hinterhuber "Xaver Hinterhuber" schrieb im Newsbeitrag news:c7qger$mml$1 at online.de... > Hi Peter, > > "Peter Otten" <__peter__ at web.de> schrieb im Newsbeitrag > news:c7q1vs$oph$04$1 at news.t-online.com... > > Xaver Hinterhuber wrote: > > > > > I don't show you codeString because it is a real string variable. > > > > You could show an _example_ codeString, though. That would have greatly > > simplified the diagnosis. > > For clarification: The codeString contains up to 500 lines of code. It's a > complete program to render a pdf page with > reportlab. It's really a huge monster. But in future I'll try give an > example with all variables declared. > > > > > And yes, its uncompiled. > > > The user in my program enters a python program in this variable without > a > > > def statement > > > and then the code is executed and the result returned. > > > > > > Maybe you can help me to add a "def f():" to the codeString, take care > of > > > the > > > indentation and then execute the code? > > > > > > I really don't know how to handle the indentation thing. A "def > > > f():\n"+codeString is easy, but this doesn't solve > > > this issue. > > > > Maybe you can get away with a simple expression: > > > > >>> from math import * > > >>> codeString = "sin(0.5) + 23" > > >>> eval(codeString) > > 23.479425538604204 > > > > If not, try > > > > >>> codeString2 = "a=0.5\nb=23\nreturn sin(a) + b" > > >>> funcString = "def f():\n " + "\n ".join(codeString2.split("\n")) > > >>> funcString > > 'def f():\n a=0.5\n b=23\n return sin(a) + b' > > >>> exec funcString > > >>> f() > > 23.479425538604204 > > >>> > > Thats a good idea. I'll try it as soon as possible. > > Thanx > > From vbasicboy at aol.com Sun May 23 01:26:18 2004 From: vbasicboy at aol.com (Grant D. Watson) Date: 23 May 2004 05:26:18 GMT Subject: Running code on module import References: <8ef9bea6.0405220829.74478fcf@posting.google.com> Message-ID: <20040523012618.28410.00000946@mb-m28.aol.com> >I thought your posting had some more substance to it. But now I >realize you were simply a barbarian not used to the way of the Romans. I may have visited Rome only to build a mead hall, but I'm building it with concrete, arches and marble columns. ;-) >But if you really want to do things the barbarian way, here is one >way. The way you described is quite practical, but not nearly as fun. If I was just concerned with making things work, it would do very well. It just doesn't fall into the "neat hack" category. My first concept and first attempts at runmain didn't add anything to "if __name__..."; I just wanted to see if I could do it, and learn a little bit about Python in the process. I still want to see if I can do it, and learn something about Python; my target is a bit bigger, is all. Grant D. Watson grant_watson at yahoo.pleasedontspamme.com (Please use this address, not my AOL one.) From heikowu at ceosg.de Tue May 18 10:27:47 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 18 May 2004 16:27:47 +0200 Subject: Python compilers? In-Reply-To: References: Message-ID: <200405181627.47114.heikowu@ceosg.de> Am Dienstag, 18. Mai 2004 13:41 schrieb Jacek Generowicz: > Native compilers for other languages just as dynamic as Python > exist. These compilers manage to achieve very significant speed > increases[*]. You are again refering to LISP as an example of a dynamic language which when compiled gives huge speed increases. This is true in some respect, in others it isn't. LISP has the advantage that type-inference may be used throughout the program to create one version of each function, which can then be compiled. Of course it still has to call into runtime functions to do the high-level work, but there is actually only one representation of each finished LISP program, and only one set and one proper order of runtime-functions to call. In Python this isn't true. Python, instead of LISP, is "completely" dynamic, meaning that it's pretty impossible to do type-inference for each function that is called (even checking types isn't possible). E.g. how do you expect type-inference to work with the pickle module? string -> something/Error would be the best description what pickle does. For the function which calls pickle, do you want to create versions for each possible output of Pickle? Which outputs of Pickle are possible? (depends on the loaded modules, which can be loaded at runtime) There is no (sane) way to create machine-code which calls into the appropriate (low-level) Python-runtime functions (such as Py_List*, Py_Dict*, etc.) for such a method, at least not at compile-time. At runtime, this is possible. See what psyco does. There's a nice presentation on the psyco-website which explains what it does, and I guess you'll understand when you see that why writing a "compiler" for Python is pretty impossible. Heiko. From kirk at eyegor.jobsluder.net Wed May 12 00:48:54 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Wed, 12 May 2004 04:48:54 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: On 2004-05-12, Carl Banks wrote: > Kirk Job-Sluder wrote: >> Write me a two-line script in python that reads a character delimited >> file, and printf pretty-prints all of the records in a different order. > > How about one line (broken into three for clarity): > > for line in __import__('sys').stdin: > print ''.join([ x.rjust(10) for x in map( > line.strip().split(',').__getitem__,[4,3,2,1,0]) ]) > > Believe it or not, I actually do stuff like this on the command line > once in awhile; to me, it's less effort to type this in than to > remember (read: look up) the details of awk syntax. I don't think I'm > typical in this regard, though. This looks like using the proverbial hammer to drive the screw. I still find: awk 'BEGIN {FS="\t"} {printf("pattern", $1,$4,$3,$2)}' file to be more elegant and easier to debug. It does the required task in two easy-to remember statements. From tim.one at comcast.net Fri May 7 12:18:53 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 7 May 2004 12:18:53 -0400 Subject: usage/future status of PyProtocols In-Reply-To: <409bae0d$0$12099$fa0fcedb@lovejoy.zen.co.uk> Message-ID: [rjt-usenet at thegrindstone.me.uk] > We are considering making use of the PyProtocols > (http://peak.telecommunity.com/PyProtocols.html) package. I have read > through the documentation and it appears to offer much of what we > want. > > I have already used both Zope's Zope or Zope3? They differ too. > and Twisted's interface implementations to a greater or less extent in > existing projects and I have been a bit disappointed that no 'standard' > approach to interfaces has appeared in the Python libraries. There are two PEPs open in the general area, 245 and 246. You can read Guido's most recent public thoughts about them here: http://www.python.org/doc/essays/pepparade.html You may infer from the tone that Guido isn't overly excited about either of them -- but of course that would just be your opinion . > Before jumping into PyProtocols I was wondering: > > Are other people using it in real projects? What are their experiences > regarding payback for effort expended? I don't know, but I suggest also/instead asking on the PEAK mailing list: http://www.eby-sarna.com/mailman/listinfo/PEAK/ > Does anyone know if there are plans to include a 'standard' approach > to interfaces/protocols in the Python library? That's what the PEPs are about. They haven't been rejected yet, so "someday" I expect they'll make progress. > If so, is it likely that it will be PyProtocols? Your guess is as good as anyone's. I'm pretty sure Guido doesn't use any interface or adapter gimmicks today, so he won't favor one based just on familiarity (there was some chance that Zope's mechanisms would gain an advantage on that ground when Guido was employed by Zope Corp, but no more). > I just don't want to spend a lot of time, and persuade my team > members to use a package that is then superseded by a different > approach in a future standard library package. Sorry, no guarantees here. From __peter__ at web.de Fri May 28 04:44:31 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2004 10:44:31 +0200 Subject: Two questions about efficiency References: Message-ID: Steve M wrote: > Peter Otten <__peter__ at web.de> wrote > >> Two results stand out: misses are cheap for DictIn and expensive for >> DictTry. > > That's very interesting, thanks so much Peter and the others. > > So, contrary to your (and, incidentally, Wittgenstein's) admonition to > look not think, why, would you speculate, is this the case? The > overhead from creating an exception object? Again, why would I speculate if I can measure? try ... except: $ timeit.py -s"key='a'" "try: raise KeyError('KeyError: %r' % key)" "except KeyError: pass" 100000 loops, best of 3: 5.22 usec per loop share of exception object creation: $ timeit.py -s"key='a'" "KeyError('KeyError: %r' % key)" 100000 loops, best of 3: 2.96 usec per loop So the exception mechanism accounts for more than 5 of 9 extra usec. You can perhaps find out where the rest stems from if you dig deeper, but I'm too lazy right now. Which reminds me, timing with this simple tool is not only fun - I've found my intuition proved wrong often enough, so it saves me from optimizing portions of the code that are already fast. Peter From deetsNOSPAM at web.de Sat May 22 10:44:01 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 22 May 2004 16:44:01 +0200 Subject: operator over loading References: Message-ID: Anand K Rayudu wrote: > Hi all, > > I have defined q python class and want to know if i can over load '=' > operator. No you can't - that stems from the fact that assignment in python means that a value is bound to , not that there is made a copy of that value stored into some space referred to by , as it is done it C/C++. Think of variables as references. There is also no &= operator in C++ to overload. > Now the problem is cos(c), sin(b) creates new objects, which are used > for multiplication. > This again generates a new object, > What i want to do it automatically delete all intermediate objects. > except the one assigned to a. > currently i am deleteing c object in __del__ > So once I reassing some thing else to a that is also getting deleted. > So what i want to do is once i assign it to a variable, i want to set > flag so that i won;t delete it in _del_ Why do you care? Let pythons GC do the job for you. It looks like you try to impose C++ thinking on python here. While thats understandable, its never good to try to stick to the idioms of one language in anotherone - you miss the nice differences then :) -- Regards, Diez B. Roggisch From googled at heaviside.f9.co.uk Sun May 30 16:49:59 2004 From: googled at heaviside.f9.co.uk (gongoozler) Date: 30 May 2004 13:49:59 -0700 Subject: Boa+wxpython2.4+wxGTK2.4 References: Message-ID: Hi, I read John's post and find I'm trying to do the same thing, slightly different behaviour, if it helps someone point both of us in the right direction. My setup: Mandrake 10.0 Python 2.3.3.2.mdk wxPythonGTK-2.4.2.4-2mdk pyGTK2.0-2.0.0.2mdk Try starring Boa Constructor-0.2.3 [marc at localhost boa-constructor-0.2.3]$ python Boa.py Starting Boa Constructor v0.2.3 importing wxPython Traceback (most recent call last): File "Boa.py", line 179, in ? from wxPython import wx File "/usr/lib/python2.3/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: libwx_gtk2u-2.4.so.0: cannot open shared object file: No such file or directory So do I have the library... [marc at localhost boa-constructor-0.2.3]$ find /usr/lib -name libwx_gtk2u-2.4.* -print /usr/lib/wxPython/lib/libwx_gtk2u-2.4.so [marc at localhost boa-constructor-0.2.3]$ find /usr/lib -name "libwx_gtk2u-2.4.*" -print /usr/lib/wxPython/lib/libwx_gtk2u-2.4.so --> which is a link to libwx_gtk2u-2.4.so.0.1.1 Well nearly, but that ain't close enough. The import error looks like it is referencing a library that doesn't exist, maybe a badly formed name. I have identical versions of Python, wxPython, wx and Boa running on a W2K laptop with the same versions as the Mandrake box. Hints as to the process that constructs or resolves the library name, and it's location if it's in the Python, gratefully received. Regards, Gongoolzer From moughanj at tcd.ie Sun May 23 18:52:40 2004 From: moughanj at tcd.ie (James Moughan) Date: 23 May 2004 15:52:40 -0700 Subject: Unification of Methods and Functions References: <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> <16752bcc.0405230518.2023328a@posting.google.com> Message-ID: <16752bcc.0405231452.1fb55df@posting.google.com> moughanj at tcd.ie (James Moughan) wrote in message news:<16752bcc.0405230518.2023328a at posting.google.com>... > David MacQuigg wrote in message news:... > > On 22 May 2004 11:50:18 -0700, moughanj at tcd.ie (James Moughan) wrote: > > > > >David MacQuigg wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... > > >> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >> >David MacQuigg wrote: > > > >> I like your example, but not as a *substitute* for Animals_2. It's > > >> just too complex for non-CIS students at this point in the course. I > > >> think I understand your concerns about Animals_2. I think the best > > >> way to deal with those concerns is not by complicating the example, or > > >> by taking out everything that could lead to problems, but rather by > > >> pointing out the problems, and showing subsequent examples that fix > > >> those problems, even at the expense of more complexity. > > >> > > >> If you have a simple all-in-one alternative to Animals_2, show me. > > >> > > > > > >Again, clearly I have not communicated myself well - I mean a > > >*completely* different example to the entire Animals approach. The > > >difficulty with writing a good Animals-type example comes from the > > >things which it is trying to do, which aren't especially well > > >expressed by a class-heirarchy. > > > > What I am trying to do in Animals_2 is provide the simplest, most > > learnable example of Python OOP, which has at least one of every basic > > structure the students will encounter in a real program. So I include > > bound, unbound, and static methods, but not metaclasses or > > descriptors. > > > > Creating a good example like this is turning out to be more of a > > challenge than I expected. I'm fairly happy with Animals_2, but I > > appreciate the "maintainability" problems you have pointed out, and > > have added footnotes accordingly. The examples in Learning Python are > > too spread out in little pieces, and of course, no attention to the > > issues you are concerned about. If you know of another place I can > > look for a good all-in-one teaching example, I am interested. > > > > Just for the sake of example, this is one of the programs which I > always write while learning a language, written in a way I'd use to > demonstrate OO; all it does is read in a wordlist, then print out > synonyms for user-inputed words. [snip] Obviously the word 'synonym' should be replaced with 'anagram' in this post. :) Never give your classes cute names like Thesaurus then post before breakfast... From prudek at bvx.cz Fri May 21 03:42:40 2004 From: prudek at bvx.cz (Milos Prudek) Date: Fri, 21 May 2004 09:42:40 +0200 Subject: httplib set timeout Message-ID: <40ADB2F0.4060406@bvx.cz> How can I set httplib timeout for httplib.request() ? httplib.request timeouts after 3:10 with "socket" timeout error message. I found socket.settimeout() and I believe there is a way to add ".settimeout()" function to httplib without hacking httplib source. Is it possible? -- Milos From corey.coughlin at attbi.com Wed May 19 15:00:06 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 19 May 2004 12:00:06 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> Message-ID: Well yeah, my code would be proprietary, but you can probably reconstruct most of it from the description above. Just start with a basic outline, add some interface functions on the front end to read and write spice or verilog netlists, and see how it goes. (Starting with spice would be a lot easier, it's a much easier format to parse.) Maybe some of the other EE savvy people here would be willing to help out. The only real problem with using it as an example is that it isn't heavily object oriented. It uses some simple inheritance, some classes, and some operator overloading, but if you want to get into these complex ideas, it may not be the way to go. If you're looking to make a functional system of some kind, a basic netlist hierarchy would definitely be a good example. Given your descriptions of current analysis, it sounds like you might be doing something for power analysis. In the basic hierarchy I described, you can imagine having extra power attributes attached to each cell, and to get the total power you could easily write a little recursive instance power summation method. If you want to do something more complicated, like roll in table driven power data or state dependent power, you'll need to overlay some sort of simulation state on top of it, which sounds like it would involve adding state to each net. Hmm.... if everything inherited from some timescale object, and some basic functionality was added for transistor primitives, I suppose it could work. But starting with a good netlist container would be a great first step. So start with a netlist class that holds a list of cells, a cell class that holds lists (or dicts) of nets, instances, and ports, then fill in the instance, net and port classes, and you should be well on your way. David MacQuigg wrote in message news:... > > This is the kind of thinking I like. 90% of what we need to do can be > done with the simplest of programming constructs. I know your company > probably considers what you develop proprietary, but would it be > possible for you to contribute an example suitable for teaching OOP to > EE students? > > I will probably still keep the Animals example in the intro, since it > shows almost everything we will ever need in the simplest possible > structure. A netlister would be a great example, however, especially > since my students are studying EDA tools. > > -- Dave From peter at engcorp.com Sat May 1 12:18:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 May 2004 12:18:10 -0400 Subject: quotes at the edges of a triple quote string... In-Reply-To: References: Message-ID: <5eednTy2_ZjVUA7dRVn-uw@powergate.ca> Anthony Roberts wrote: > property = re.compile("""(?P[a-z0-9_\-]+)="(?P.*?)""""re.I) > > This doesn't work because the closing quote in my regex forms the first > quote of a triple quote to end the string... > > property = re.compile("""(?P[a-z0-9_\-]+)=("(?P.*?)")""", > re.I) > > This mucks up stuff I want to do later. > > I've thought about it for a while, and except for changing it to a > single-quoted string with escaped quotes, is there any clean way to do > this? Can't you still use a triple-quoted string, but escape the last quote? >>> """test\"""" 'test"' -Peter From icemon999 at yahoo.com Wed May 19 12:30:36 2004 From: icemon999 at yahoo.com (mr. ice) Date: 19 May 2004 09:30:36 -0700 Subject: what does this mean? Message-ID: I am new to python, The following statement is in the beginning of class definition in a python scripts, what does it mean? Help? class %(class_)s_W : public XMsg_W { icemon From bdesth.quelquechose at free.quelquepart.fr Mon May 17 16:18:42 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 17 May 2004 22:18:42 +0200 Subject: program works as a script, not interactively In-Reply-To: <40A8CED9.2AA19629@uk.ibm.com> References: <40A8CED9.2AA19629@uk.ibm.com> Message-ID: <40a9175a$0$22115$636a15ce@news.free.fr> Philip Carter wrote: > Hello there, > > I am using: > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > > on a win2k box. > > I have the following piece of python code: > (snip code) > When I save in a file - terry.py and run it: > python terry.py > it works fine. > > However, if I try and paste it into an interactive python window, I get > the following error: > > ... outFile.close() # close the output file > File "", line 14 > outFile.close() # close the output file > ^ > SyntaxError: invalid syntax > > Any idea why this is? Probably a problem with indentation... I sometime have this kind of problem when copy/pasting pieces of code in the interpreter. Bruno From j_mckitrick at bigfoot.com Mon May 10 10:27:56 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 10 May 2004 07:27:56 -0700 Subject: Has anyone gotten Pmw's BLT to work under Unix?? Message-ID: I've been looking all over for this solution, but I cannot find it. I cannot get even the simple demos for BLT to work. At the first use of any Pmw.Blt.* call, I get this error: _tkinter.TclError: invalid command name "::blt::vector" Is there some trick with the library location I need to be aware of? jonathon From peter at engcorp.com Sat May 15 18:00:20 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 18:00:20 -0400 Subject: Idea: PYTHONPATH_VER In-Reply-To: References: Message-ID: Fernando Perez wrote: > Thanks, Peter. I might start a separate thread asking about this, with a > clearer description of my problem. I don't think it's a linux issue, but > rather one of dealing with when python loads (or not) .pth files. As I said, > it may well just be my misunderstanding of how the system really works. Check the source in site.py first, then, as it is fairly straight- forward about what it does. -Peter From peter at engcorp.com Tue May 18 21:10:04 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 May 2004 21:10:04 -0400 Subject: Python compilers? In-Reply-To: <40AA2C16.C1245362@shaw.ca> References: <40AA2C16.C1245362@shaw.ca> Message-ID: <6PSdnRxCG8pxLjfdRVn-hg@powergate.ca> SeeBelow at SeeBelow.Nut wrote: > Leif K-Brooks wrote: >> >>What are you trying to achieve? > > Yes, fast execution. I have been using C. In my applications there is > a population of "chromosomes" which are arrays of floats, about 2 to 5 k > in length. Then there are subroutines which operate on a chromosome > using pointers. For example, the "crossover" routine uses two pointers > to swap portions of two chromosomes. My software sometimes runs for > hours, perform many millions of operations like these. Clearly, speed > of execution is of dramatic importance. The bottleneck is almost certainly in evaluating the fitness function, not in performing the mutations and cross-overs. What does your fitness function do with all those floats? Perhaps it can be handled much faster with one of the numeric extensions for Python... or with Pyrex. -Peter From newsgroups at jhrothjr.com Mon May 3 21:04:56 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 May 2004 21:04:56 -0400 Subject: PEP 328 update References: <109d87iiu30ct7a@news.supernews.com> Message-ID: <109dr3brevocb60@news.supernews.com> "Aahz" wrote in message news:c76k9g$rf0$1 at panix1.panix.com... > In article <109d87iiu30ct7a at news.supernews.com>, > John Roth wrote: > > > >I also don't particularly see the reason for banning the relative form > >from raw import statements. > > Did you see the rationale toward the end? Yes. From my point of view, the . is an operator or a decorator. It is not a part of the name; if it was, the system would be unable to find the module on disk, because that name does not have the dot. The rationale makes no sense whatsoever. John Roth > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Adopt A Process -- stop killing all your children! From apardon at forel.vub.ac.be Thu May 13 03:58:07 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 07:58:07 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: Op 2004-05-13, Greg Ewing schreef : > Antoon Pardon wrote: >>> x = 42 >>> x += 1 >>> >>>which is a very handy thing to be able to do. >> >> But it creates confusions because the semantics >> is not consistent. > > Practicality beats purity, though, and this does seem > to be very practical. Well one could drop the immutability of certain classes instead. One would then loose the immutabilty purity and gain the consistency purity. In a choice between those two purities I would choose the latter. But I don't expect python development to follow my preference. > Besides, the semantics are as consistent as anything > else in Python, where the objects being operated on > get to determine the meaning of just about everything. So? Would you argue that the devellopers could just as easily have implemented "a += b" as equivallent to "a = a - b" with half of the core classes and called that just as consistent as choosing it equivallent to "a = a + b" for all core classes because the objects being operated on get to determine the meaning? -- Antoon Pardon From news at bolognini.net Sat May 1 03:36:13 2004 From: news at bolognini.net (Lorenzo Bolognini) Date: Sat, 1 May 2004 09:36:13 +0200 Subject: Web development class References: Message-ID: "Peter Otten" <__peter__ at web.de> ha scritto nel messaggio news:c6vjt3$qu2$02$1 at news.t-online.com... > Have a look at > http://mail.python.org/pipermail/python-list/2004-April/215227.html Thanks for the answer Peter but none of the linked projects is the one I'm looking for which was a dumb simple script 1 page long. Anyway I find XIST interesting.... sure I'll check it out! ;-) Cheers, LOrenzo From tjreedy at udel.edu Thu May 6 10:14:12 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 May 2004 10:14:12 -0400 Subject: classes vs dicts References: Message-ID: "Charlie" wrote in message news:be05f1d.0405060212.43929fe1 at posting.google.com... > Greetings, > > I am pretty new to Python and like it very much, but there is one > thing I can't figure out and I couldn't really find anything in the > docs that addresses this. > > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? You can represent a person by a tuple, dictionary, or class instance. All three ways of representing records are used in various places in the standard library. The 'best way' depends on the specifics of the situation. You can represent a collection of persons -- an address book -- by a list, dictionary, list + index dictionary, dictionary as person class attribute, class derived from dict, or class with dict as per instance attribute. Same comment as to 'best'. > I guess using dictionaries is fastest and easiest, but is this recommended? I would concentrate on easiest to program to get desired functionality. Terry J. Reedy From dave at pythonapocrypha.com Tue May 25 09:17:35 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 25 May 2004 07:17:35 -0600 Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: <00ca01c4425a$a5193900$6500a8c0@YODA> David MacQuigg wrote: > >> Still this is like saying names that start with the letter 'q' are way > >> less common than all other names, so it is OK if we have a special > >> form for functions with such names. > > > >Not at all - that's a flawed analogy because variable names can be pretty > >arbitrary and interchangable. The different types of function calls, method > >invocations, whatever, are neither arbitrary nor interchangable. > > Here is a better analogy than my "no-q" functions. I will use the > term "global method" to mean any method containing a global variable. > We now have "normal methods", "static methods", "global methods", and > a few others. There is no difference in the calling sequence or the > header line between a global method and a normal method. Yet we don't > seem to have any need for a statement like > myMethod = globalmethod(myMethod) Ugh, I'm sorry but this analogy seems as bad as the no-q analogy. That's like saying methods that contain for-loops should be declared differently - but in neither case is the thing that matters to the caller - the interface (both the explict means by which the function is used as well as the explicit or implicit contract and purpose of the function) - affected. Let's move on. > I'm new to Python and object-oriented programming. I make no claim of > language expertise or vast programming experience. Doesn't it give you pause that many other people, both with and without that background, have encouraged you to give the current feature set a chance? As in, use these features for awhile, get some more experience with them, and in time you'll come to understand the 'why' behind them? Again, I'm not asserting that the current language is perfect, just that the way things are might have a purpose and/or the proposal you've come up with has drawbacks worse than what we already have... If nothing else, waiting until you have a lot of programs under your belt will let you argue your point from a position of strength. > offering a perspective on Python from a technical professional > (circuit design engineer) who intends to use it as the basis for a new > design platform, and intends to recommend it to students and other > technical professionsls who could benefit greatly, but don't have time > to learn the language as well as they should. Then what you really ought to do is not cover more advanced topics any sooner than is needed. Really. Nobody taking an intro-to-programming course needs to learn about e.g. classmethods. They just don't need to. In your course pass out a link to a web page of advanced reading for those you want to know more, and leave it at that. Burdening them with tools they won't use anytime soon won't be doing them a favor. Instead, teach them how to find answers to their questions, how to experiment, so that _if_ and when they do come across it then they can go learn it then. > >> What can you do in the current syntax that can't be done more easily in the > >proposed syntax? > > > >Understand my code 6 months from now. Modify the code with less risk. > >Understand the level of intent in someone else's code I'm using. > > OK, here is what I can extract from all this: Having a separate > syntax for static methods is beneficial because it tells the > programmer at a glance that he can call a method from a class without > having an instance of that class at hand. That's part of it, but there's more - a static method is used in different scenarios and for different purposes. They generally aren't interchangeable beasts. > >another thread I suggested you take the time to learn what the 2 or 3 most > >common uses are for each of the features that will be affected, and show both > >the implementation and use in current Python and after your proposed changes. > >Not only will doing this give a clear example to everyone, it'll also show that > >you are at least aware of how the different function/method forms are used > >today in _real programs_ and not contrived examples - after re-reading some of > >your comments I have my doubts. > > I have shown the 4 function/method forms I'm aware of, and how to > translate them to a simpler syntax, in Appendix 1 of Prototypes.doc at > http://ece.arizona.edu/~edatools/Python Have you read that? Yes, but as I pointed out elsewhere, it may help to write about this in some other context than your other proposals (the fact that this is buried in Appendix 1 under a title of "Translating Python Classes to Prototypes" doesn't lend itself to much reader traffic). But, it's better than nothing, so here goes: 1. Bound methods - the calling appears to be identical in either version, but one of the real values of the bound method form is being able to call the bound method _when you don't have the instance variable handy_ (I'm just trying to point out why it's useful). Anyway, the fact that the methods don't have a self variable does make things seem a little magical - with 'self' in the arg list it makes sense to me how self.foo grabs a variable from the current instance. Yes, there is some magic in the current implementation in that the self arg gets passed in, but the alternative is either uglier or more magical, so it seems like a good compromise between explicitness and practicality. 2. Unbound methods - the example uses an unbound method to "bypass" a subclass method - that seems like a really unrealistic example. Inserting the superclass method into the subclass, but with a different name seems equally odd. Thus, the whole argument in favor of the "Python 3" version is unappealing. What's downright frightening, however, is that you can write something like '__self__ = c' and get the same behavior (for many reasons, not the least of which is that two seemingly unrelated statements are completely linked). Wanting to call a superclass method with the current instance is a much more likely example, but with either form of the "Python 3" syntax it's quite unclear that that is what is happening - because it's indistinguishable from the other calls, it's w ay less clear what the code is doing. Thus, both newbies and experts alike will have a more difficult time understanding (and maintaining and modifying) the code. 3. Static methods - your page doesn't list any examples of calling the functions, but I assume that in both cases it's Mammal.show(). Not much to be unified here, although I don't like the fact that the "Python 3" version loses the information that it is a static method (I don't particularly like the fact that for the current version the staticmethod call happens after the method body - I like some of the proposals in the related PEP), but in current Python you actually have two indicators - there's no 'self' parameter. And again, you have the same problem in the calling code - it's not clear what is happening, and yet what is happening is a pretty important piece of info. In the "new" syntax, the call could be to a static method or to a superclass method, but the reader of the code is left wondering which one it is. 4. Class methods - this example just seems broken, but perhaps I'm misreading it. In the Python 3 version, a string is getting passed in to the class method, and the prototype of the *string* is then displayed - makes no sense to me. In any case, class methods are IMO a pretty advanced topic - since a main point of yours is that you want to make OO more accessible to the lay programmer, I don't see how class methods would come up in the discussion at all - they'd be more relevant to a metaclass or descriptor discussion. > I'm also continually adding new examples under the Examples and > Exercises link on that same page. Many of these are contributed by > readers of this thread, including some who would rather not post here. > (Gentle Request: A little less intolerance from some others on this > thread might encourage more contributions from people they really need > to hear from.) Equally gentle request: don't be too hasty in assuming that because people disagree with you, their previous experience has clouded their perceptions or made them forget what it was like to walk the path you're currently on. > As for a real program, it will be a few months before I have anything > sizable. I showed you the statefile example (in response to your > request), but you seemed to be insulted, like you thought I was > talking down to you, or something. Not at all, just realize how your message sounds on the receiving end (whether you intended it to come across this way or not): "Even though I haven't really used these features much, I think they should be changed. Other people say the features have a purpose, and that the purpose becomes clear over time, but I disagree." That, in itself, is hard to take too seriously, although I'm impresed at how many people apparently took the time to think about your suggestion. Best of luck, Dave From jepler at unpythonic.net Sat May 15 10:06:43 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 09:06:43 -0500 Subject: Input Types In-Reply-To: References: Message-ID: <20040515140643.GA2832@unpythonic.net> Here's a function that can do the job. def typed_input(prompt="", convert=int, catch=ValueError, eprompt="Invalid input."): while 1: s = raw_input(prompt) try: return convert(s) except catch: print eprompt Usage: >>> typed_input("Enter an integer: ") Enter an integer: asdf Invalid input Enter an integer: 3 3 >>> typed_input("Enter a number: ", float) Enter a number: Invalid input Enter a number: 3.14 3.1400000000000001 How does it work? 1. The "while 1" loop is repeated until the "return" statement is successfully executed. 2. int(s) and float(s) convert a string argument s to the specified type, or raise the ValueError exception 3. When there is a ValueError exception, the "error prompt" is printed, and the while loop returns to the top to try again. You can also write your own "convert" function to restrict values to a range, etc: >>> def int_0_100(s): ... i = int(s) ... if i < 0 or i > 100: ... raise ValueError # out of range ... return i ... >>> typed_input("Enter a number from 0 to 100: ", int_0_100) Enter a number from 0 to 100: asdf Invalid input. Enter a number from 0 to 100: 101 Invalid input. Enter a number from 0 to 100: 37 37 You can also specify the catch= or eprompt= arguments to change the exception that is caught or the error prompt string. Jeff From sean_berry at cox.net Fri May 14 02:19:16 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 13 May 2004 23:19:16 -0700 Subject: I need newbie help References: <10a83t8qku40d44@corp.supernews.com><9CYoc.126297$Jy3.43222@fed1read03> Message-ID: Sorry for any confusion. I didn't write this page... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708 I was just trying to point out what they were trying to show. "Andrew Bennetts" wrote in message news:mailman.3.1084513865.4157.python-list at python.org... > On Thu, May 13, 2004 at 10:16:01PM -0700, Sean Berry wrote: > [...] > > > > Since Python doesn't have a switch statement, you can make your own. > > In Python you could do something like this though: > > > > selector={ > > x<0 : 'return None', > > 0<=x<1 : 'return 1', > > 1<=x<2 : 'return 2', > > 2<=x<3 : 'return 3', > > 3<=x : 'return None' > > }[a] > > > > if a == 1, it would "return 1". > > You seem to be a little bit confused, which is likely to make a newbie > really confused. > > What is x in your example? Your dictionary's definition depends on multiple > expressions involving it -- you'd only get the result of selector == 'return > 1' when a is 1 if 0 <= x < 1. > > For instance: > > >>> x = 0.5 > >>> { > ... x<0 : 'return None', > ... 0<=x<1 : 'return 1', > ... 1<=x<2 : 'return 2', > ... 2<=x<3 : 'return 3', > ... 3<=x : 'return None' > ... } > {False: 'return None', True: 'return 1'} > > But: > > >>> x = 2 > >>> { > ... x<0 : 'return None', > ... 0<=x<1 : 'return 1', > ... 1<=x<2 : 'return 2', > ... 2<=x<3 : 'return 3', > ... 3<=x : 'return None' > ... } > {False: 'return None', True: 'return 3'} > > So looking up 1 in that dictionary would return whatever string was > associated with the key True (because 1 == True), which is entirely > dependent on the value of x when the dictionary was defined. > > Also, your use of strings containing python statements is misleading -- > retrieving a value from a dictionary doesn't implicitly execute it as a > string of Python source code too. Less confusing values would have been > 'less than 0', 'between 0 and 1', and so on, because at least that is less > likely to confuse a newbie. > > Finally, as someone else pointed out, often the best way to do a switch > statement in Python is not to be clever at all, but instead to just simply > do: > > if x < 0: > return None > elif 0 <= x < 1: > return 1 > elif 1 <= x < 2: > return 2 > elif 2 <= x < 3: > return 3 > else: > return None > > Although that's a very contrived example (what's the point of doing that?) > -- more convincing would be something like: > > if colour == 'red': > r, g, b = 255, 0, 0 > elif colour == 'purple': > r, g, b = 255, 0, 255 > > # and so on ... > > Which I think turns out to be a much better candidate for the dictionary > trick anyway: > > rgbValues = { > 'red': (255, 0, 0), > 'purple': (255, 0, 255), > # ... > } > > r, g, b = rgbValues[colour] > > -Andrew. > > From apardon at forel.vub.ac.be Wed May 26 04:16:08 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 May 2004 08:16:08 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: Op 2004-05-25, Antoon Pardon schreef : > Op 2004-05-25, David MacQuigg schreef : >> On 25 May 2004 10:30:03 GMT, Antoon Pardon >> wrote: >> > 3) Higher order functions. These are functions that > whose arguments and/or return values can be again > functions. > > The typical example is a sorting function that takes > as an argument a function that decides which of two > elements is the smaller. By providing different > functions (one that looks at names or one that > looks at Id number) the same function can be used > to sort people alphabetical or Numerical by Id. > > Now to go a step further. Suppose we have a lot > of functions Fi: Each of these functions is > defined as follows Fi(x) = i + x. Now we > can have an other function S. S is defined as > follows: S(a) = Fa. Now we can use S to add > two numbers. Suppose we want to add 2 and 5. > First we call S(2), this will result in F2. > Then we call F2(5) which will result in 7. > Or more directly we could call S(2)(5). > > Now python allows to define higher order functions. > S would be defined as follows in python: > > def S(i): > > def Fi(x): > > return i + x > > return Fi > Now any normal function can be turned into a higher order function with a related functionality. Supose we have a function with the following signature in python def func(a1, a2, a3): We can then write the higher order function as follows: def Hfunc(a1): def Ifunc(a2, a3): return func(a1, a2, a3) return Ifunc Now transforming a function to a higher order equivallent is called currying and currying is again a higher order function. In python we write it as follows def curry(f): def Hf(a1): def If(*ta): la = (a1,) + ta return apply(f, la) return If return Hf So from now on if we have a function we can turn it into its curried version as follows: Hfunc = curry(func) So now we have all we need for object oriented programming. To illustrate I'll make a stack pseudo class. We start with the assumption that we have the following class. class Bare: pass First approach def Stack(): st = Bare() st.lst = [] return st def Empty(st): return len(st.lst) == 0 def Pop(st): result = st.lst[-1] del st.lst[-1] return result def Push(st, el): st.lst.append(el) stack = Stack() Push(stack, 4) Push(stack, 'hallo') El = Pop(stack) This is a strickt procedural approach. It has the disadvantages that the procedures Empty, Pop and Push aren't very tied to the stack and that we therefore prohibit other structures the use of the same name We can eliminate these disadvantages as follows: Second approach def Stack(): def Empty(st): return len(st.lst) == 0 def Pop(st): result = st.lst[-1] del st.lst[-1] return result def Push(st, el): st.lst.append(el) st = Bare() st.lst = [] st.Empty = Empty st.Pop = Pop st.Push = Push return st stack = Stack() stack.Push(stack, 4) stack.Push(stack, 'hallo') El = stack.Pop(stack) This looks already somewhat object oriented. The problem here is that you are essentially obligated to allways provide the first argument twice. To eliminate this cumbersome repetition we work with applied curried functions as methods. Third approach def Stack(): def Empty(st): return len(st.lst) == 0 def Pop(st): result = st.lst[-1] del st.lst[-1] return result def Push(st, el): st.lst.append(el) st = Bare() st.lst = [] st.Empty = curry(Empty)(st) st.Pop = curry(Pop)(st) st.Push = curry(Push)(st) return st stack = Stack() stack.Push(4) stack.Push('hallo') El = stack.Pop() And we now have standard python method calls. We will just make some cosmetic changes here to have it resemble python class conventions more. Fourth approach def Stack(): def __init__(self): self.lst = [] def Empty(self): return len(self.lst) == 0 def Pop(self): result = self.lst[-1] del self.lst[-1] return result def Push(self, el): self.lst.append(el) self = Bare() __init__(self) self.Empty = curry(Empty)(self) self.Pop = curry(Pop)(self) self.Push = curry(Push)(self) return self stack = Stack() stack.Push(4) stack.Push('hallo') El = stack.Pop() And this is more or less equivallent to: class Stack(): def __init__(self): self.lst = [] def Empty(self): return len(self.lst) == 0 def Pop(self): result = self.lst[-1] del self.lst[-1] return result def Push(self, el): self.lst.append(el) stack = Stack() stack.Push(4) stack.Push('hallo') El = stack.Pop() -- Antoon Pardon From dfaden at iastate.edu Thu May 20 13:55:20 2004 From: dfaden at iastate.edu (David Faden) Date: Thu, 20 May 2004 12:55:20 -0500 Subject: better way of executing expression/statement in C? Message-ID: Hi, Given arbitrary Python source code input by the user, I want to get the result of executing that source as an expression if it is an expression and otherwise execute the source as a statement. Currently, I'm accomplishing this as follows (in a category on NSString), but it seems kludgy to rely on detecting a syntax error. - (PyObject*)executePythonSourceWithGlobals:(PyObject*)globals { const char* source = [self UTF8String]; PyObject* result = PyRun_String(source, Py_eval_input, globals, globals); if (!result && PyErr_ExceptionMatches(PyExc_SyntaxError)) { PyErr_Clear(); result = PyRun_String(source, Py_file_input, globals, globals); } return result; } How would you accomplish this? How does the interpreter do it? Thank you. David AIM: pitulx From aahz at pythoncraft.com Sat May 15 18:50:47 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2004 18:50:47 -0400 Subject: Test error with Python 2.3.4c1 References: Message-ID: In article , Berthold H?llmann wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> In that case, you should check against the CVS version of Python; I >> believe there've been some changes that affect this kind of thing. If >> that fixes your problem, please close the bug report. > >OK, I just checked the latest CVS and test_re succeeds. But should't >this fixed for 2.3.4 as well? Nope. Bugfix releases (see PEP 6) are required to have essentially zero behavioral changes, and IIRC the series of fixes that fixed your bug caused some changes to the way sre operates, so it was a non-starter for the 2.3.x series. Anyway, please close your bug with a note about it being fixed in 2.4 CVS. As for the other issue, I don't have enough time/energy to even understand what the issue is. Given that it's about SAX, I suggest you start a new thread and hopefully someone else will pick it up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From Mike at DeleteThis.Geary.com Mon May 24 12:31:16 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 24 May 2004 09:31:16 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com><5sl4o1-crf.ln1@eskimo.tundraware.com><10avdpe73rnj20d@corp.supernews.com><8a0bb987.0405222327.78ef180e@posting.google.com><10b2dvrfqhmbm5a@corp.supernews.com> Message-ID: <10b48qllaagcr11@corp.supernews.com> > Michael Geary wrote: > > For example, these do exactly the same thing: > > > > import re > > for line in file( 'inputFile' ).readlines(): > > print re.split( '\s+', line.strip() ) > > > > import re > > reWhitespace = re.compile( '\s+' ) > > for line in file( 'inputFile' ).readlines(): > > print reWhitespace.split( line.strip() ) > > > > But for a large file, the second version will be faster because > > the regular expression is compiled only once instead of every > > time through the loop. Terry Reedy wrote: > I am curious whether you have actually timed this or seen others > timings. My impression (from other posts and from reading the > code a year ago) is that the current re implementation caches > compiled re's (recache[hash(restring)] = re.compile(restring)) > just so that the first example will *not* recompile every time thru > the loop. If so, I think one should name an re for pretty much the > same reasons as for anything else: conceptual chunking and reuse > in multiple places. Oh man, is my face red! No, I didn't know about the caching, and I hadn't timed this. One should never make assumptions about performance issues! :-) Also, as Konstantin pointed out, file( 'inputFile' ).readlines() should be just file( 'inputFile' ), and I just noticed that I didn't use raw strings for the regular expressions. '\s+' happens to work, but it would be better to be in the habit of writing r'\s+' instead. This was not my day for posting good code samples! Now that you've shamed me into actually testing the performance, it turns out that precompiling the regular expression does make a difference. Consider these examples: import re, time input = [] for i in xrange( 1000000 ): input.append( '%d abc def ghi jkl mno pqr stu' % i ) start = time.time() for line in input: result = re.split( r'\s+', line ) print time.time() - start import re, time input = [] for i in xrange( 1000000 ): input.append( '%d abc def ghi jkl mno pqr stu' % i ) start = time.time() reWhitespace = re.compile( r'\s+' ) for line in input: result = reWhitespace.split( line ) print time.time() - start On my PIII-1.2GHz system, the first version runs in 27 seconds, and the second version runs in 18 seconds, quite an improvement. I would guess that the hash lookup for the cached regular expression is what's taking the extra time in the first version, but I don't want to assume that's what it is. :-) -Mike From a at a.invalid Tue May 18 17:15:37 2004 From: a at a.invalid (Timo Virkkala) Date: Tue, 18 May 2004 21:15:37 GMT Subject: alternatives to making blocks like { } or other ?? In-Reply-To: References: Message-ID: CYBER wrote: > Is there any other way under python to create blocks ?? > instead of > def sth(x): > return x > could i use something else like > def sth(x): > { > return x > } Not without changing the language a lot. But just try the normal way for a couple of days, you'll get used to it in no time. -- Timo Virkkala From BruceWhoHKL at gawab.com Wed May 12 22:10:58 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Thu, 13 May 2004 10:10:58 +0800 Subject: how to integrate Bdb into vim??? Message-ID: Hi , recently I'm trying to write a vim script to integrate python debugger in to vim so that I can debug python script in vim. But I come across a problem. I need to write a derived class of Bdb, so I must override the user_* methods.but how can I return to vim? When user_* is called , it should return to vim, and when the user 'step' or 'next', it return to the user_* call again, and run. But how to achieve this? It's apparently I need to 'freeze' the Bdb and wait for some input coming from vim ,and then go back to the right place. but we can't make vim functions as callbacks. That's the question. maybe iterator/generator can be used to solve it. But I don't know how. Any one can help me? Any suggestions are appreciated. (BTW, I'm not sure that my former e-mail was posted, so I post it again.) ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-13 From martin at v.loewis.de Tue May 4 16:46:25 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 May 2004 22:46:25 +0200 Subject: problem with fnidl In-Reply-To: References: Message-ID: <4098011b$0$26200$9b622d9e@news.freenet.de> Gelo Ilzi wrote: > I installed fnorb (python corba) on my PC (WinXP). For some unclear reason > fnidl (idl to python interpretator) does nothing. It doesn't produce any > warning, error message. Project skeleton isn't built also. > > Any idea what's wrong? Most likely, you don't have Visual C++ installed, so it can't invoke the C++ preprocessor to process the IDL files. Try using the internal preprocessor. Regards, Martin From dmgass at hotmail.com Thu May 13 03:54:16 2004 From: dmgass at hotmail.com (Dan Gass) Date: 13 May 2004 00:54:16 -0700 Subject: config-py 1.1 released Message-ID: config-py version 1.1 has been released and is available at SourceForge. Highlights of the changes are: 1) License changed from GPL to MIT (less restrictive) 2) Settings available as attributes of configuration instances 3) Allow user exact control of when environment keys are utilized 4) Exception class was added 5) Other (backwards compatible) interface and documentation improvements Module Description ------------------ This python module provides a simple, but extremely flexible and powerful method of controlling python script execution by use of configuration settings stored in user configuration files. This module is a more powerful alternative to the ConfigParser module already available in the standard Python distribution. The standard ConfigParser module parses text based user configuration files and provides access to that information. This module reads python based configuration files and provides access to the python objects contained within. In addition, this module supports hierarchical organization of the settings within the configuration files so that settings may be accessed using keys specified by the user from the command line or by other means. By use of python based configuration files, this module provides a simple solution to most configuration problems but also has the flexibility to solve the most complex configuration issues. Other Important Information --------------------------- License: MIT Project Home Page: http://config-py.sourceforge.net/ Download URL: https://sourceforge.net/projects/config-py/ Author/Maintainer: Dan Gass (dmgass at hotmail.com)

config-py 1.1 - Python based user configuration file accessor module. (13-May-04) From andrew-pythonlist at puzzling.org Thu May 13 07:40:34 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 21:40:34 +1000 Subject: Scope rule pecularities In-Reply-To: References: <2g8ag2F4re0lU1@uni-berlin.de> Message-ID: <20040513114034.GE16275@frobozz> On Thu, May 13, 2004 at 10:41:45AM +0000, Antoon Pardon wrote: > Op 2004-05-13, Andrew Bennetts schreef : > > On Thu, May 13, 2004 at 07:40:45AM +0000, Antoon Pardon wrote: > >> > >> But I don't ask for rebinding, I ask for easy in place copying. > >> > >> Lets name a new operator "@=" Now given variables A and C > >> of the same class I would like to see the following: > >> > >> >>> B = A > >> >>> A @= C > >> >>> A is B > >> True > >> >>> A is C > >> False > >> >>> A == C > >> True > > > > It's already easy: > > > > from copy import copy > > > > b = a > > a = copy(c) > > Sorry, you are wrong. After this you get > > >>> a is b > False Oh, sorry, I misread -- as you can see, I assumed you meant that C was a copy of A, when actually you wanted A to be a copy of C. Now I understand what you mean about an "in-place copy". > >> And maybe if D is of an other class > >> > >> >>> D @= C > >> TypError > > > > Assignments in Python don't care about what the name is currently bound to, > > if anything. > > This is not assignment (as is understood in python). Indeed! But it *looks* like assignment -- it has an equals sign. In fact, it's only one character different to Python's assignment. My point is that the proposed syntax is confusing. > > They just (re)bind the name to an object -- so having an > > assignment to D depend on the type of D's old value would be inconsistent > > with the rest of Python. > > > > Many classes support a convention where you can pass a single argument to > > their constructor to construct a copy, e.g.: > > > > l2 = list(l1) > > > > So your example could become: > > > > d = d.__class__(c) > > No to get the same effect as what I want you need something like this: > > class M: > > def cp_from(self, a): > for key in dir(self): > value = getattr(a,key) > setattr(self,key,value) > > d.cp_from(c) You can do that already, without defining any new methods: d.__dict__.update(c.__dict__) [This won't work for the minority of types that don't have __dict__s on their instances, but it does work for virtually all user-defined classes.] Assuming that d and c have the same set of instance variable names (which I would expect most code following good style would do), I don't see why modifying an existing instance of d to be a copy of c is any better than simply making a copy from scratch with the clearer: d = copy(c) What's the big advantage to mutating an existing instance? -Andrew. From peter at engcorp.com Sat May 1 15:06:41 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 May 2004 15:06:41 -0400 Subject: calling functions at the same time In-Reply-To: <4093de02$0$17252$a1866201@newsreader.visi.com> References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> <4093de02$0$17252$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Peter Hansen wrote: (Someone else wrote this first part, then Grant's reply, then mine) >>>>You can't get greater then 1ms accuracy when measuring a time >>>>on todays machines, and that will be less when measuring time >>>>over a network... >>> >>>Not sure what you mean by "todays machines", but on a >>>Pentium-class machine running Linux, you get approx 1us >>>resolution with calls to time.time(): >> >>Keep in mind the difference between "accuracy" and >>"resolution" (or "precision"). > > I do. > > Not only do you get 1us resolution, you get packet timestamp > _accuracy_ to well under 1ms according to tests I've run > comparing packet timestamps against an oscilloscope trace. [snip other technical details] > As soon as there are other ready tasks, the accuracy of the > measurement quickly deteriorates to tens of millisconds due to > scheduling latencies. The last sentence is really the whole point. The OP needs to be aware that the accuracy *cannot* be *guaranteed* to better than "tens of milliseconds", overall, regardless of the "accuracy" of the clock tick or the resolution of anything... The notes on timeit.py are helpful in this respect, however: taking the shortest result of repeated measurements is a pretty good way to get an "accurate" number, most of the time. The other, higher results represent the interference of all those other tasks which will tend to run as you try to take measurements. -Peter From chetan_hram at hotmail.com Wed May 12 16:59:50 2004 From: chetan_hram at hotmail.com (chetan) Date: Thu, 13 May 2004 02:29:50 +0530 Subject: Chetan Message-ID: hi, I have installed Red Hat Linux 9, and tried to install python2.3 on python2.2 but there was a library installation error, while doing "make install". I wanted to access BerkelyDB4.2 from python but it was not possible. Please can you help me rectify that error. BerkeleyDB4.2 is installed without any errors. regards, chetan -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at privacy.net Tue May 11 08:03:02 2004 From: me at privacy.net (Duncan Booth) Date: 11 May 2004 12:03:02 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: Kirk Job-Sluder wrote in news:slrnca0ub4.1bdc.kirk at eyegor.jobsluder.net: > The above code runs, but is not very good because I'm not that > familiar with exec statements. Anyway I've tried to capture what > "perl -pi -e" actually does which is to execute an arbitrary command > over every line of an arbitrary list of files, editing them in place, > with a temporary backup copy. Your code might have been a bit shorter if you had used the existing facility in Python for editing files in place. The code below is completely untested, so I can all but guarantee it doesn't work, but you get the idea: #!/usr/local/bin/python import getopt,sys,os,re import fileinput #get your command line options #files will be in optlist, args = getopt.getopt(sys.argv[1:],'e:') for line in fileinput.input(args, inplace=1): #execute all of the -e statements. for command in optlist: #warning bad mojo here foo=(command[1] % line.rstrip("\n")) exec(("line=%s" % foo)) #save to the new file print line fileinput.close() From griebel at konzept-is.de Fri May 7 04:36:11 2004 From: griebel at konzept-is.de (Dr. Peer Griebel) Date: Fri, 07 May 2004 10:36:11 +0200 Subject: Bit torrent swap space via python In-Reply-To: <79ad5955.0405051156.20d2e1b@posting.google.com> References: <79ad5955.0405051156.20d2e1b@posting.google.com> Message-ID: <409B4A7B.7000700@konzept-is.de> Julia Goolia wrote: > Hi, > > I noticed that Bit Torrent uses a lot of swap space when downloading > files at a fast speed. This has quite a bad effect on my system. My > applications that are running are constantly getting removed from the > swap space cause Bit Torrent is downloading so much data. Everything > becomes VERY choppy. At least I think that is what is going on. > > My question is... is there a class or function to open a file which > will not do any buffering in the swap space? > > Peace! > julia > Is mmap what you are looking for? Peer From skip at pobox.com Tue May 18 11:51:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 18 May 2004 10:51:38 -0500 Subject: better csv modules and where have object-craft gone? In-Reply-To: <40a98a20@news.highway1.com.au> References: <40a98a20@news.highway1.com.au> Message-ID: <16554.12554.233004.432329@montanaro.dyndns.org> Tim> I have been using object crafts csv module for quite a few Tim> projects, mainly because I found the csv in python in it's current Tim> incarnation is funtionally inferior to object crafts. The object Tim> craft module for instance allowed you build up csv gradually (ie Tim> field at a time rather the python csv module where the writer does Tim> the work a record at a time) which isn't always the way I would Tim> like to work, also I have always had encoding problems (specifcally Tim> it doesn't support unicode as per the docs) everytime I used the Tim> python module where as the object craft one always worked out of Tim> the box. I guess beauty is in the eye of the beholder. The Object Craft folks were key authors of what's in the Python distribution. If you want to write a field at a time, you should be able to subclass the csv.writer class and add writefield() and commit() methods. The first appends to an internal list. The second calls writerow() and clears the list. Something like this (untested) code might work: class FieldWriter(csv.writer): def __init__(self, *args, **kwds): csv.writer.__init__(self, *args, **kwds) self.temp = [] def writefield(self, val): self.temp.append(val) def commit(self): self.writerow(self.temp) self.temp = [] (Be careful. You'll lose partial results if you don't clean up in a __del__ method.) As for lack of Unicode support that's a known issue. I suppose it hasn't been high enough on anyone's list of itches to have attracted any scratching yet. Still, you might be able to get most of the way there with a subclass: class UnicodeWriter(csv.writer): def __init__(self, *args, **kwds): self.encoding = kwds.get('encoding', 'utf-8') if 'encoding' in kwds: del kwds['encoding'] csv.writer.__init__(self, *args, **kwds) def writerow(self, row): for (i,f) in enumerate(row): if isinstance(f, unicode): row[i] = f.encode(self.encoding) I'm almost certain that reading data in multibyte encodings won't work though, as the low-level reader is byte-oriented instead of character-oriented. Patches are welcome to resolve that deficiency. Skip From tjreedy at udel.edu Fri May 21 12:45:46 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 12:45:46 -0400 Subject: hash comments in interactive shell References: <40AD00B2.2020401@neggie.net> <40AD44DA.5060100@neggie.net> Message-ID: "John Belmonte" wrote in message news:40AD44DA.5060100 at neggie.net... > I'd really like to make the real interpreter act like the emulator... If you mean that literally, and are not familiar with how to contribute to Python development, there is a page at python.org to read, and more help here with further questions. tjr From heikowu at ceosg.de Thu May 6 10:42:50 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 6 May 2004 16:42:50 +0200 Subject: Web programming ... In-Reply-To: <200405061638.29494.heikowu@ceosg.de> References: <200405061638.29494.heikowu@ceosg.de> Message-ID: <200405061642.50248.heikowu@ceosg.de> Am Donnerstag, 6. Mai 2004 16:38 schrieb Heiko Wundram: > [snip] > (http://sourceforge.net/projects/CheesyPy). > [snip] Whoops, I misspelled the project name at sourceforge. The URL should've been: http://sourceforge.net/projects/cheesypy btw., if anybody is using this package and can't contact me, the eMail-Address stated in that package has expired (as I no longer work there), and you can now contact me at heikowu at ceosg.de... I'll upload a new version of the package with updated contact information soon. Heiko. From kevryan0701 at yahoo.com Thu May 20 23:23:05 2004 From: kevryan0701 at yahoo.com (Kevin T. Ryan) Date: Thu, 20 May 2004 23:23:05 -0400 Subject: Help w/ HTMLParser lib Message-ID: <40ad7619$0$3114$61fed72c@news.rcn.com> Hi all - I'm somewhat new to python (about 1 year), and I'm trying to write a program that opens a file like object w/ urllib.urlopen, and then parse the data by passing it to a class that subclasses HTMLParser.HTMLParser. On the web page, however, there is javascript - and I think that is causing an error in parsing the data. Here's the error: Traceback (most recent call last): File "", line 1, in ? File "html_helper.py", line 30, in parse_data p.feed(data) File "//usr/lib/python2.2/HTMLParser.py", line 108, in feed self.goahead(0) File "//usr/lib/python2.2/HTMLParser.py", line 150, in goahead k = self.parse_endtag(i) File "//usr/lib/python2.2/HTMLParser.py", line 329, in parse_endtag self.error("bad end tag: %s" % `rawdata[i:j]`) File "//usr/lib/python2.2/HTMLParser.py", line 115, in error raise HTMLParseError(message, self.getpos()) HTMLParser.HTMLParseError: bad end tag: "", at line 411, column 7 I've tried to use a try/except clause both w/in my class and w/in a function that wraps the class for easy access, but to no avail. The code works on other websites, so I know that it's not *completely* off. Any help would be greatly appreciated! TIA :) Kevin From mark at prothon.org Tue May 25 00:43:12 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 21:43:12 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: Roger Binns wrote: > In addition to all the excellent notes from Paul, I would recommend > you consult with someone familiar with the locale and encoding > issues for Hebrew, Arabic and various oriental languages such > as Japanese, Korean, Vietnamese and Tibetan. Bonus points for > Tamil :-) I sure hope you are kidding. If not you are scaring me away from doing anything. I want to do the best thing. I want someone who knows what's best and that I can trust to help out and tell me what to do. I want to develop Prothon, not become an expert on glyphs and international character coding. > Since you are doing new language design, I also think there would > be great value in forcing things so that you do not have > strings embedded in the program, and they have to come from > external resource files. This also gives you the opportunity to > deal with string interpolation issues and get them right. > (It also means that "Hello, World" remains one line, but also > requires an external file with the message, or some other > mechanism). Do you mean for the interpreter or some enabling tool for the Prothon programs? Doing this for the interpreter is on the to-do list. Thanks for all the tips. I'd like for you and Paul to help out with Prothon in this area if you could. At least let me bounce the plans off you two as I go. From pit.grinja at gmx.de Thu May 20 09:28:18 2004 From: pit.grinja at gmx.de (Piet) Date: 20 May 2004 06:28:18 -0700 Subject: wxPython: Fit() works on wxPanel, but not on surrounding wxFrame Message-ID: <39cbe663.0405200528.7182e07c@posting.google.com> Hello, I am still struggling with a dynamic dialog box. I have created a dialog box that will show a variable number of controls depending on a selection made in a ComboBox also present in the frame. The dialog box is not derived from wxDialog, but from a wxFrame. The dialog is initialized as follows: class myDialog(wxFrame): def __init__(self,parent,title): wxFrame.__init__(self,parent,-1, title, style=wxDEFAULT_FRAME_STYLE) self.panel = wxPanel(self,-1) The position of the controls on the wxPanel inside the frame is controlled by sizers, which are initialized as follows: self.MasterSizer=wxBoxSizer(wxVERTICAL) self.panel.SetSizer(self.MasterSizer) self.panel.SetAutoLayout(True) self.MasterSizer.Fit(self.panel) self.panel.Fit() self.Fit() To ensure that the size of the window and its layout always take into account the number of the controls, every function that will change the number of controls ends with the following threelines: self.MasterSizer.RecalcSizes() self.panel.Fit() self.Fit() For some reason, only the wxPanel changes its size as expected and fits nicely around the controls placed on it. The surrounding wxFrame is always (except at initialization time) slightly larger than the panel, resulting in an ugly, dark grey border on the right and at the bottom of the frame. How is that possible? Thanks in advance for your help Piet From tkpmep at hotmail.com Wed May 12 16:30:21 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 12 May 2004 13:30:21 -0700 Subject: Printing formatted strings from a dictionary Message-ID: I want to print "1 spam 4 you" using a formatted string that gets its inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, I write >>> x="%('n1')d %('s1')s %('n2')d you" >>> x % d Traceback (most recent call last): File "", line 1, in -toplevel- x % d KeyError: "'n1'" >>> However, I get what I want if I edit x to remove the quotes around n1, s1 and n2 and write >>> x="%(n1)d %(s1)s %(n2)d you" >>> x % d '1 spam 4 you' The syntax that works seems to run counter to the way dictionaries work: >>> d['n1'] 1 >>> d[n1] Traceback (most recent call last): File "", line 1, in -toplevel- d[n1] NameError: name 'n1' is not defined What is the error in my logic? Thomas Philips From Chris.Hornberger at blackrock.com Wed May 12 08:49:03 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 08:49:03 -0400 Subject: How to batch download files from web page? Message-ID: That's actually pretty easy. Download the list, parse it up to find the links/file names (turning them into links if you have to), shove them up a list. Begin pop'ing from the list and download. you *could* thread that out so you can have a few downloads going at once, but I wouldn't go beyond 5 or 6, tops. Upon successful completion, toss the link away. If you fail, append it to the list for a retry. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of sj Sent: Wednesday, May 12, 2004 1:25 AM To: python-list at python.org Subject: How to batch download files from web page? I wish to download hundreds of files from the University of Iowa sound archive. Doing it manually would be a daunting task especially since the files are each a few mega bytes long. Is there a standard way of using Python for such a task? I have a fair amount of programming experiance but very little of it relates to networks. For those who are intrested the University of Iowa's sound archive may be found at http://theremin.music.uiowa.edu/MIS.html Thanks in advance Steven Jones -- http://mail.python.org/mailman/listinfo/python-list From tim.one at comcast.net Thu May 27 02:55:24 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 27 May 2004 02:55:24 -0400 Subject: why learn Message-ID: [mr_vocab] >> hey i finished working through alot of python stuff and no a fair bit >> bout it >> >> now what can i do with it??? [Tim] > Follow your bliss: in your case, it looks like you'd really enjoy writing > a program to post the same question 100 times. It's a lot easier to write > a program for that than to stay up all night doing it by hand . Oops! My apologies! That wasn't you. A particularly nasty piece of spam wedged my ISP, and your message was immediately before it: every time I downloaded mail, I got your message again, and then the connection died while trying to transfer the ill-formed spam. Anyway, following your bliss remains sincere if cryptic advice. What are you interested in? What do you love? If you're not using Python for your job (and sometimes even if you are ...), those are the questions to answer first. Python will then fit in or won't. You can use Python for anything a computer has ever been used for, and for a boundless number of things nobody has thought of yet. What do you care about? From eadorio at yahoo.com Mon May 3 07:30:39 2004 From: eadorio at yahoo.com (Ernie) Date: 3 May 2004 04:30:39 -0700 Subject: Embedded comments in Python? Message-ID: <5b42ae4.0405030330.5bba90f5@posting.google.com> Hi, Whats the legal way in Python to embed comments in Python code? Example: def foo(a <:int>, b <:float>): <:array> return [a, b] Want the CPython interpreter to ignore the <:int>, <:float> and <:array>(this one can be written as #array). Using triple quoted strings would be longer and is invalid syntax. This would be extremely useful for those who write tools for processing Python scripts. In C/C++, this would be no problem with /* */. Regards, Ernie From rogerb at rogerbinns.com Tue May 4 01:34:14 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 3 May 2004 22:34:14 -0700 Subject: Kill a thread in Python References: Message-ID: C. Barnes wrote: > However, if your code hangs at a lower level than > Python, then the > thread will not actually be killed until the next > Python statement is > executed. That is the usual case for me. My threads are blocked in calls to read, accept or Queue.get(). > Consider bugging the Python folks, until they give us > a thread kill > method. The code has already been written: > > http://mail.python.org/pipermail/python-list/2003-February/148999.html Looking through that patch I couldn't tell if it could terminate a thread that was in native code. It seemed to cause the kill to happen in the next bit of Python bytecode interpretted. Incidentally Java does have a thread kill method although it is strongly recommended against using. Roger From balaji at email.arizona.edu Fri May 21 17:40:13 2004 From: balaji at email.arizona.edu (Balaji) Date: 21 May 2004 14:40:13 -0700 Subject: TypeError: unsubscriptable object. Message-ID: <494182a9.0405211340.49873a72@posting.google.com> Hello Everybody... I have a problem.. This is the code... -------------------------------------- class Stack: def __init__(self,expr): self.stackP=[] self.stackF=1 self.a = {} # self.stackManagement(expr) if not self.a.has_key('rhs'): self.a['rhs'] = 0 # self.a['rhs'] += self.popP()*self.popF() def pushP(self,obj): self.stackP.append(obj) def pushF(self,obj): stackF=stackF*obj return stackF def popP(self): rval=0 rval=self.stackP.pop() return rval def popF(self,obj): stackF/=obj return stackF def peekP(self): rval=0 rval= self.stackP[-1] return rval def peekF(self): rval=0 rval= self.stackF[-1] return rval def stackManagement(self,expr): #Determine the next symbol if expr.__class__==E: self.pushP(expr.operator) self.stackManagement(expr.left) self.stackManagement(expr.right) else: self.pushP(expr) if len(self.stackP) > 1: s = self.peekP() prev = self.stackP[-2] if prev in ('*','+','/','-'): if prev in ('*','/'): self.pushF(self.peekF()*s) else:#stackP[-3] must be an operator. top=self.popP() mid =self.popP() op=self.popP() if op == '*': if top.__class__==V: self.a += self.popF(self.stackF) self.stackManagement(0) else: self.popF(self.stackF) self.stackManagement(mid*top) if op == '+': if top.__class__==V: self.a+= self.peekF() self.stackManagement(0) else: self.stackManagement(mid+top) if op == '-': if top.__class__==V: self.a -= self.peekF() self.stackManagement(0) else: self.stackManagement(mid-top) if op == '/': if top.__class__==V: self.a /= self.popF(self.stackF)/(mid**2) self.stackManagement(0) else: self.popF(self.stackF) self.stackManagement(top/mid) else: self.a['rhs'] += self.popP(self.stackP)*self.popF(self.stackF) and I'm giveing the following calls... --------------------------- from expression import * from generation import* (x,y,z) = (V(),V(),V()) # making instances of Variable class e1=x+y+z s=Stack(e1) s.stackManagement(e1) ---------------------------------------------- I'm getting the following error TypeError: unsubscriptable object... Traceback (most recent call last): File "", line 1, in ? File "generation.py", line 175, in stackManagement self.stackManagement(expr.left) File "generation.py", line 176, in stackManagement self.stackManagement(expr.right) File "generation.py", line 199, in stackManagement self.a+= self.peekF() File "generation.py", line 168, in peekF rval= self.stackF[-1] ------------------------------------- I 'm at my wit ends.. Can anyone help... Thx in advance From htx1 at gmx.de Thu May 6 10:02:33 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Thu, 06 May 2004 16:02:33 +0200 Subject: classes vs dicts In-Reply-To: <7id65haegq.fsf@enark.csis.hku.hk> References: <7id65haegq.fsf@enark.csis.hku.hk> Message-ID: Isaac To wrote: >>>>>>"Charlie" == Charlie writes: > Charlie> Greetings, I am pretty new to Python and like it very much, but > Charlie> there is one thing I can't figure out and I couldn't really > Charlie> find anything in the docs that addresses this. > > Charlie> Say I want to write an address book program, what is the best > Charlie> way to define a person (and the like): create a class (as I > Charlie> would do in Java) or use a dictionary? I guess using > Charlie> dictionaries is fastest and easiest, but is this recommended? > > > Python is about making the complexity where it worth. If you cannot see > that a class will help, the safe choice is to do it with a dict. Later, if I don't think so. If you don't want to define set... and get ... methods, you can still misuse a class in this way: class Person (object): pass somePerson = Person () somePerson.name = "his name" somePerson.address = "her address" instead of somePerson = {} somePerson ["name"] = "his name" somePerson ["address"] = "her address" The first alternative is easier to read and even safer: If you need to extend the capabilities of the class, you can still redefine the behaviour of the data fields using descriptors. Greetings, Holger From ramen at lackingtalent.com Thu May 6 14:29:45 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 06 May 2004 18:29:45 -0000 Subject: MySQL vrs SQLite References: Message-ID: Sorry, a few minor corrections... In article , Dave Benjamin wrote: > First of all, a minor nit: the word you want here is "supposed", not > "suppose". =) This typo occurs in the documentation on the web site, so my nit was most likely misdirected. > Your claims about types in database being a feature remind me of MySQL's s/types/typelessness/ -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From garry at sage.att.com Fri May 14 13:54:41 2004 From: garry at sage.att.com (Garry Hodgson) Date: Fri, 14 May 2004 17:54:41 GMT Subject: how to run an arbitrary function with timeout? In-Reply-To: References: Message-ID: <2004051413541084557280@k2.sage.att.com> "Tim Peters" wrote: > Best I can guess, you're expecting something that can't happen, but I'm not > sure exactly what. ok, let me rephrase my question. i would like a function RunWithTimeout( func, args, timeout ) i would like it to invoke the function func on arguments args. if timeout seconds elapse before func(args) returns, i would like it to raise an exception. if func(args) returns before timeout seconds, i would like it return the result. can anyone help? thanks ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From peter at engcorp.com Mon May 3 11:34:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 11:34:03 -0400 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: <5b-dnVJ33JJj_gvdRVn-hQ@powergate.ca> References: <0MudnVoTELDrxAvdRVn-gw@powergate.ca> <5b-dnVJ33JJj_gvdRVn-hQ@powergate.ca> Message-ID: <3JydnQN_1uZs-AvdRVn-ig@powergate.ca> Peter Hansen wrote: > Okay, in spite of installing everything that I should have, > I didn't have a glut32.dll on my machine. I take the first part of that back. Turns out I never did install GLUT on this machine (obvious now) and it was the previous machine where I had the whole shebang running. If my memory weren't so bad I would have known and followed the detailed and excellent (thanks Mike! :-) instructions like a good boy. -Peter From sean_berry at cox.net Thu May 27 15:08:36 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 27 May 2004 12:08:36 -0700 Subject: CGI newb... redirect page References: Message-ID: "Sean Berry" wrote in message news:Ayqtc.49$VI2.1 at fed1read02... > Hi there. I am relativly new to Python CGI and need a question answered. > > I have made custom 404 error pages and have them in various web directories. > > I have not been able to figure out a way to have apache use a file not > within it's own > home directory, so I was going to have a .py file in cgi-bin forward the > user on to the > correct error page. > > So I have say, > /usr/www/client1/not-found.shtml > and... > /usr/www/client2/not-found.shtml > > I found that cgi.print_environ() gave me the SERVER_NAME, which is what I > want. > But, this is part of a long html formatted string that cgi.print_environ() > returns. Okay. I found that usung os.environ yielded the results I was looking for. > > Is there something builtin to deal with these name, value pairs as a > dictionary? > I looked throught the docs, but did not see this functionality. > > Also, when I do extract this info... how do I actually do a redirect to a > certain page > But, I still don't know how to forward, or redirect a page. Please help. > Example. > User goes to www.client1.com/page_not_on_server.html > The apache conf file sends the redirect to /cgi-bin/redirect.py > Redirect.py extracts the requesting server, client1.com, then > redirects them to www.client1.com/not-found.shtml. > > Thanks for your help. > > From grey at despair.dmiyu.org Thu May 6 18:56:03 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 06 May 2004 22:56:03 GMT Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> Message-ID: On 2004-05-06, Graham Dumpleton wrote: > I then type ^Ke and it will pipe the whole contents of the file being edited > through "expand" which will turn all tabs into appropriate number of > spaces. Typing ^Ku does the opposite. > You could run the "expand" program outside of vi as well as part of a shell > script and do all your files at the same time. Couldn't they just also just add a global %s/\t/ /g to the loading of .py files and be done with it? :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From nasa at no-wucking-furries-mate.com Sat May 1 04:07:02 2004 From: nasa at no-wucking-furries-mate.com (Enrichment A. Cozy) Date: Sat, 01 May 2004 01:07:02 -0700 Subject: Save up to 70% on programs, Python. Message-ID: <011001c42f53$4f541cd6$0870e83f@no-wucking-furries-mate.com> Well well well! Everything you see I owe to spaghetti. Searching for not expensive high-quality software? Our site might be just what you need. http://isoteles.dbsoft.biz We offer Software to download or it can be shipped to you on CD. http://cric.hotsoft.biz We are able to ship worldwide. Happiness does not lie in happiness, but in the achievement of it. Better to ask twice than to lose your way once. No wife can endure a gambling husband unless he is a steady winner. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eric_brunel at despammed.com Fri May 7 04:07:18 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 07 May 2004 10:07:18 +0200 Subject: How to change tkinter GUI look-and-feel? References: Message-ID: Jonathon McKitrick wrote: > I saw some screenshots of mayavi. Is there any way we can set tkinter to > use the motif (or some other toolkit under Unix) rather than the default? > > jm Motif *is* the default look for tk/Tkinter on Unix. I also saw some screenshots of Mayavi, and I also noticed the NextStep look they had for their tk widgets. I don't exactly know how they did that; I know there is a very old branch of tk named tkstep that had this look, but it has been unsupported for years. Or maybe they hacked the current Tkinter to support the new "tile" package for tk which allows to apply themes to tk widgets? Maybe one of the MayaVi people would like to enlighten us? Anyway, downloading Mayavi sources and using your own Tkinter should not show this look for the widgets, but the more "standard" Motif look. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From NOSPAM at easyconnect.fr Sat May 15 05:17:52 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Sat, 15 May 2004 11:17:52 +0200 Subject: NIC adress of incoming socket. References: <40a4f772$0$2280$afc38c87@news.easynet.fr> Message-ID: <40a5e12e$0$2277$afc38c87@news.easynet.fr> "Peter Hansen" a ?crit dans le message de news:naWdnRu54vmoBTjdRVn-hw at powergate.ca... > RosalieM wrote: > > > How can i know the nic adress from an incoming socket ? > > I can easily know the ip adress and port number but how do i have some > > information about arp level ? > > In addition to Andreas' answer: I'm not even sure the problem > has a well-defined solution in general. Isn't it possible > that individual packets in the data stream (assuming this > is TCP, for example) can be routed through different > networks (and, therefore, different NICs) on some machines? > > If you want to limit this to the simple case of one NIC > per machine, then you still need to resort to platform-specific > things like parsing the output of some external command > to match up IP address and "NIC address" (which is also > not necessarily well-defined, but I assume you mean Ethernet > address there). > > -Peter I saw in dhcpd config for bootp that you give the adress of the nic. How can i be sure that in my lan it is the right computer (my dhcp server) that answers to my client and not another compromised machine ? Can i ask python some information from ethernet level in an ip connection? From premshree_python at yahoo.co.in Sat May 29 13:04:35 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sat, 29 May 2004 18:04:35 +0100 (BST) Subject: PyAC 0.0.2 Message-ID: <20040529170435.70884.qmail@web8306.mail.in.yahoo.com> Hello, Python Album Creator 0.0.2 is out. This version supports user templates, which means users can use their own "skins" with PyAC. Details at http://www.livejournal.com/community/pyac/1736.html Download PyAC 0.0.2 from http://sourceforge.net/project/showfiles.php?group_id=106998&package_id=115396 Thanks, Premshree ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From fredrik at pythonware.com Mon May 24 13:54:52 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 May 2004 19:54:52 +0200 Subject: Specify start and length, beside start and end, in slices References: Message-ID: Noam Raphael wrote: > I have to write: > picture[s2i(picture[10:14]):s2i(picture[10:14])+4] > I think this is nicer (and quicker): > picture[s2i(picture[10:>4]):>4] that's spelled picture = Image.open(file) picture.getpixel((0, 0)) From moughanj at tcd.ie Sun May 23 09:18:54 2004 From: moughanj at tcd.ie (James Moughan) Date: 23 May 2004 06:18:54 -0700 Subject: Unification of Methods and Functions References: <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> Message-ID: <16752bcc.0405230518.2023328a@posting.google.com> David MacQuigg wrote in message news:... > On 22 May 2004 11:50:18 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >David MacQuigg wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... > >> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> >David MacQuigg wrote: > > >> I like your example, but not as a *substitute* for Animals_2. It's > >> just too complex for non-CIS students at this point in the course. I > >> think I understand your concerns about Animals_2. I think the best > >> way to deal with those concerns is not by complicating the example, or > >> by taking out everything that could lead to problems, but rather by > >> pointing out the problems, and showing subsequent examples that fix > >> those problems, even at the expense of more complexity. > >> > >> If you have a simple all-in-one alternative to Animals_2, show me. > >> > > > >Again, clearly I have not communicated myself well - I mean a > >*completely* different example to the entire Animals approach. The > >difficulty with writing a good Animals-type example comes from the > >things which it is trying to do, which aren't especially well > >expressed by a class-heirarchy. > > What I am trying to do in Animals_2 is provide the simplest, most > learnable example of Python OOP, which has at least one of every basic > structure the students will encounter in a real program. So I include > bound, unbound, and static methods, but not metaclasses or > descriptors. > > Creating a good example like this is turning out to be more of a > challenge than I expected. I'm fairly happy with Animals_2, but I > appreciate the "maintainability" problems you have pointed out, and > have added footnotes accordingly. The examples in Learning Python are > too spread out in little pieces, and of course, no attention to the > issues you are concerned about. If you know of another place I can > look for a good all-in-one teaching example, I am interested. > Just for the sake of example, this is one of the programs which I always write while learning a language, written in a way I'd use to demonstrate OO; all it does is read in a wordlist, then print out synonyms for user-inputed words. Handy for crosswords. ;-) First in a data/tool centric style, which could be one of the earlier examples: def addItem(dict, key, elem): if dict.has_key(key): dict[key].append(elem) else: dict[key] = [elem] def sortWord(word): word = map(str.lower, word) word.sort() return ''.join(word) def main(): multi_dict = {} for line in open("wordlist.txt").readlines(): line = line.strip() addItem(multi_dict, sortWord(line), line) while True: word = sortWord(raw_input('Enter a word to find synonyms')) if multi_dict.has_key(word): print multi_dict[word] #lis = multi_dict[word] #lis.append('blah') <- error!! else: print 'No synonyms in the worlist.' main() Not a bad solution, but inflexible. Also a program which repeats the pattern in the commented-out lines will cause problems. So, we really want to encapsulate the data in a class; class Multi_dict: def __init__(self): self._dict = {} def add(self, key, elem): if self._dict.has_key(key): self._dict[key].append(elem) else: self._dict[key] = [elem] def get(self, key): if self._dict.has_key(key): return list(self._dict[key]) return [] def sortWord(word): word = map(str.lower, word) word.sort() return ''.join(word) def main(): multi = Multi_dict() for line in open("wordlist.txt").readlines(): line = line.strip() multi.add(sortWord(line), line) while True: word = sortWord(raw_input('Enter a word to find synonyms: ')) syns = multi.get(word) if len(syns) > 0: print syns else: print 'Sorry, no synonyms' main() This is a generalised solution to making a multi-entry dictionary. However, we still need to call sortWord, which is a shame; someone might try using two different functions to hash the elements, and it makes our code sloppier. However, if we put it into a class sortWord doesn't really need a self attribute; so we make it a static method. We also extend the Multi_dict class to avoid replicating the code. class Multi_dict: def __init__(self): self._dict = {} def add(self, key, elem): if self._dict.has_key(key): self._dict[key].append(elem) else: self._dict[key] = [elem] def get(self, key): if self._dict.has_key(key): return list(self._dict[key]) return [] class Thesaurus(Multi_dict): def __init__(self): Multi_dict.__init__(self) def sortWord(word): word = map(str.lower, word) word.sort() return ''.join(word) sortWord = staticmethod(sortWord) def add(self, elem): Multi_dict.add(self, self.sortWord(elem), elem) def get(self, elem): return Multi_dict.get(self, self.sortWord(elem)) def main(): theo = Thesaurus() for line in open("wordlist.txt").readlines(): line = line.strip() theo.add(line) while True: word = raw_input('Enter a word to find synonyms: ') syns = theo.get(word) if len(syns) > 0: print syns else: print 'Sorry, no synonyms' main() Exercises for students: (i.e. stuff I was too lazy to do) 1) Modify the original program to terminate on an empty input line 2) Extend Multi_dict to create a class which stores only one example of each item. (Class heirarchy.) I think this shows everything you want in simple way, with the exception of class-level data - you can show that by moving _dict to class level, demonstrating a system which pools all of the words entered into any Thesaurus, and point out the advantages/disadvantes of this - there may be examples where this would be just what you want. You could pick an example from an area which your students are familiar with to make whings more concrete. > >Why not just take one of your earlier program examples, show the > >students what it looks like when object-oriented, then extend the > >class(es)? > > > >As I've mentioned, I don't like my example *at all* for your teaching > >purposes, and I'm not suggesting you use it. It was simply to > >illustrate that there is another method of doing things, and what the > >original problems were. (A good solution to the Animals 'problem' > >would be simple, it just wouldn't demonstrate any of the things you > >want to show.) > > Then it wouldn't be a good solution. What I want to show is at least > one of every structure needed in a real program. > > I've made your example one of the exercises. It solves a particular > problem, and it is worth showing. > > >> We also need to make sure we include *all* children of Reptile in the > >> new numReptiles function. > >> > >> class Reptile(Animal): > >> -numReptiles = 0 > >> def numReptiles(): > >> return ( Reptile._numReptiles + > >> Snake.numSnakes() + Lizard.numLizards() ) > >> > >> Oops. We forgot Geckos !! > >> > >> To avoid these errors in programming, we may need a function that > >> automatically searches for subclasses, and calls their num functions. > >> I'm not sure how to do this without making it excessively complex. > >> Suggestions will be appreciated. > >> > >> -- Dave > > > >Hmm, I think perhaps I like your original example better than this. > >:-\ It's a bit like treating a cut throat with a tourniquet. > > > >Searching the subclasses will AFAIK still require some kind of > >metaprogramming, which is not too suitable for a 4-hour beginner > >course on OO. > > Most likely, we will not cover the solutions to the maintainability > problems, but we will mention them so students are aware. Electronic > design engineers are good at structured, hierarchical, robust design, > so I won't have to spend a lot of time on encapsulation, modularity, > maintainability, etc. They are well aware of the need for protection > circuits on all inputs. Pointing out the problems in a simplified > program example should be sufficient. > > -- Dave From has.temp2 at virgin.net Fri May 7 13:05:01 2004 From: has.temp2 at virgin.net (has) Date: 7 May 2004 10:05:01 -0700 Subject: Web programming ... References: <585c0de9.0405070102.47a481a5@posting.google.com> Message-ID: <69cbbef2.0405070905.439553a4@posting.google.com> remi at cherrypy.org (Remi Delon) wrote in message news:<585c0de9.0405070102.47a481a5 at posting.google.com>... > I see 3 common ways of dynamically generating HTML (or any other type > of text). Let's say we have a variable called "name" that contains > "world". The 3 common ways are: > (1) Embedding HTML in python: return "Hello, > %s (2) Embedding python in HTML (templating language): > Hello, $name$ (or some other notation > depending on the templating language). I would also put things like > XSLT in that category. > (3) The "programmatic" approach: return HTML(BODY("Hello, %s" > % world)) (or some other notation) There's a fourth option: compile your HTML template into a Python object model that can be manipulated programmatically. IMO this is by far the best approach for template-based rendering: it's extremely simple yet powerful, highly portable (not being bound to any particular web framework) and completely separates presentation logic from markup (other approaches typically separate only model logic). See PyMeld, Nevow.Renderer and my own HTMLTemplate (you can find various scripts using HTMLTemplate around my site). HTH From jfranz at neurokode.com Wed May 12 20:00:51 2004 From: jfranz at neurokode.com (Jon Franz) Date: Wed, 12 May 2004 20:00:51 -0400 Subject: Real-time graphs References: <20040512152247.68328.qmail@web40001.mail.yahoo.com> Message-ID: <01fc01c4387d$5b275bb0$5c01a8c0@letterbox1> > Does anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? Yes, but with Jython. My biggest client-project is a real-time monitoring system in Jython with many graphs. I previously used JFreeChart, but found it's API to be rather cumbersome - I spent more of my development time dealing with the API details and extra classes then getting actual application logic done. JFreeChart is very powerful, and the abstraction only makes it more so, but the # of lines it takes to create a simple graph got in the way after awhile. Recently, I've migrated the application to using JetChart from Jinsight (www.jinsight.com) - a commercial alternative. I've found JetChart to be easier to use; it also seems to use less memory and cpu time than JFreeChart for my purposes. Your mileage may vary, just my 2 cents. ~Jon Franz NeuroKode Labs, Makers of PDO From dieter at handshake.de Tue May 4 15:31:49 2004 From: dieter at handshake.de (Dieter Maurer) Date: 04 May 2004 21:31:49 +0200 Subject: PEP 328 update References: Message-ID: Aahz writes on Sun, 2 May 2004 15:20:32 -0400: > One area where feedback is > particularly desired is on the frequency of relative imports inside > packages in current code, both in absolute terms and as a percentage of > all imports. All my local module/subpackage references inside a package use relative imports. I never followed the style guide with respect to absolute import paths because this had made my packages less relocatable. Zope makes essential use of local imports for its "Products" magic: It supports several (configurable) locations where extensions products can come from. Any such product should be importable through "from Products import product". It achieves this by extending its main "Products" "__path__" attribute with the additional locations. This might be unaffected by PEP 328. Dieter From irmen at -nospam-remove-this-xs4all.nl Sat May 29 07:44:30 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 29 May 2004 13:44:30 +0200 Subject: python crash In-Reply-To: <40b87620_1@news.iprimus.com.au> References: <40b87620_1@news.iprimus.com.au> Message-ID: <40b8779f$0$37789$e4fe514c@news.xs4all.nl> whydoineedaname wrote: > for like the last week the python shell keeps crashing and wont load when i > try to open it and also when i tried to run some simple aps it crashes > > does anyone know how to fix this??? http://www.catb.org/~esr/faqs/smart-questions.html#beprecise From skip at pobox.com Sun May 2 13:25:50 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 May 2004 12:25:50 -0500 Subject: [OT] does the charset lie? In-Reply-To: <40952451.3020106@python.org> References: <16533.8123.5800.539196@montanaro.dyndns.org> <40952451.3020106@python.org> Message-ID: <16533.12062.56470.647993@montanaro.dyndns.org> >> ... >> ’ >> is the charset correct or should it have been utf-8? David> The charset is correct. "&" "#" "8" etc. are all in iso-8859-1. I realized that about five minutes after posting. The Content-Type header is just for the purposes of HTTP. OTOH, this means if I need the raw content of the page (after expanding any entities), I need to so something like (assuming the raw bytes are already in data): data = unicode(data, "iso-8859-1").encode("utf-8") data = map_entities_to_utf_8(data) data = unicode(data, "utf-8") Skip From __peter__ at web.de Fri May 14 02:53:30 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 May 2004 08:53:30 +0200 Subject: Speed up properties?! References: Message-ID: Dr. Peer Griebel wrote: > I have a class with some properties. I would like to verify that only > valid values are assigned to the properties using assert. Therefore I > code setters and getters and use property() to convert these to have a > real property. > > Since the verification is only performed in __debug__ runs the > property() is quite a lot of overhead. I tried to circumvent it. This > is my result so far: > > > class C(object): > def __init__(self): > self._x = 5 > if not __debug__: > self.x = property(self._x, self._x) > > def getX(self): > return self._x > > def setX(self, v): > assert 0 <= v <= 5 > self._x = v > > if __debug__: > x = property(getX, setX) > > o = C() > def test(): > o.x > > if __name__=='__main__': > from timeit import Timer > t = Timer("test()", "from __main__ import test") > print t.timeit() > > > > As you can see, in non __debug__ runs the accesses of the x property do > not result in calls to getX or setX. There I can get a speedup of 2! > But to be honest: I don't like this aproach. So is there some better, > cleaner way? class C(object): def __init__(self): self.setX(5) def setX(self, x): if not 0 <= x <= 5: raise ValueError self.x = x # for speed comparison only: y = property(lambda s: s.x) o = C() With the above, my timings show an even greater speed difference: $ timeit.py -s'from propspeed import o' 'o.x' 1000000 loops, best of 3: 0.235 usec per loop $ timeit.py -s'from propspeed import o' 'o.y' 1000000 loops, best of 3: 1.04 usec per loop Special debug code is dangerous because it can hide errors in the final version. So, if speed is that important and read access paramount, go for the asymmetric solution and use o.x for read access and o.setX() - always checked - for write access. However, my guess is that in most cases you will hardly feel any impact on the overall speed of your program, and in that case I'd recommend an x property - again with the value check preserved in the non-debug version. If you then encounter a performance problem, you probably can pin it down to some inner loop, and replacing o.x with o._x (only) there should be painless. Peter From __peter__ at web.de Wed May 26 05:04:29 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 11:04:29 +0200 Subject: alter / modify a list as well as iterate on its items / objects References: Message-ID: Derek Basch wrote: > Can anyone point me towards an article or explain > how to properly alter a list as well as iterate > on its items? For example: > > input: > > word = ["albert", "likes", "surfing!"] > > for word in sentence: > word += "foo" > > result: > > word = ["albertfoo", "likesfoo", "surfingfoo"] Note that the solutions presented so far do *not* modify the list in place. This is important if you keep references to the list elswhere. For example: >>> backup = sample = ["alpha", "beta", "gamma"] >>> sample = map(lambda x: x + ".suffix", sample) >>> sample is backup False >>> sample = [x + ".suffix" for x in sample] >>> sample is backup False Here are two ways to achieve inplace modification: >>> backup = sample = ["alpha", "beta", "gamma"] >>> for i, x in enumerate(sample): ... sample[i] = x + ".suffix" ... >>> sample is backup True >>> backup = sample = ["alpha", "beta", "gamma"] >>> sample[:] = [x + ".suffix" for x in sample] >>> sample is backup True >>> Here the [:] slice on the left makes the difference. Peter From davidf at sjsoft.com Mon May 31 13:06:44 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 31 May 2004 19:06:44 +0200 Subject: mod_python confusion In-Reply-To: <153fa67.0405281046.331b1b19@posting.google.com> References: <153fa67.0405281046.331b1b19@posting.google.com> Message-ID: Kylotan wrote: > I thought mod_python would be the answer to my CGI performance issue, > but I can't seem to make much sense out of it. All the examples are > too trivial to be of much use. > > Given that I have an application consisting of several CGI scripts, > what is the simplest way to go about converting it to run on > mod_python, not using the CGI-handler which is allegedly slow and > buggy? Everything seems to suggest a major rewrite because I not only > need to shift from printing everything to calling req.write or > whatever, but I may also need to sort out some sort of dispatching > mechanism mapping URLs to functions if I use mod_python directly. Basically the main performance gains from using mod_python are that you are calling functions in an already loaded program, rather than running a separate script each time (and the interpreter as well). So it generally does require a redesign. But if you refactor your code step by step this is usually achievable. > PSP > doesn't work on my system as 3.1.2 gives me errors and the Win32 > installer for 3.1.3 fails at the last step (finding the Apache > directory in the registry or something). > There is a new win32 installer at http://davidf.sjsoft.com/files/mod_python-3.1.3-1.win32-py2.3.exe which should fix the issue (ask here or email me or see the mod_python list for more information) David From eriksp at attbi.nospam.com Wed May 26 18:02:06 2004 From: eriksp at attbi.nospam.com (EAS) Date: Wed, 26 May 2004 22:02:06 GMT Subject: Current drive and directory References: <40b50a15$1_1@127.0.0.1> Message-ID: And also, when I actually run the program, I have trouble using notepad on files: MS-DOS Prompt 'Q' to Quit C:\Documents and Settings\Erik\Desktop>cd \windows\system32 C:\Documents and Settings\Erik\Desktop>notepad calc.py It opens up notepad, but syas that it can't find the file. I know it's in there, and I know that's the exact name. From ajw140NO at SPAM.york.ac.uk Mon May 3 19:10:36 2004 From: ajw140NO at SPAM.york.ac.uk (Andrew Wilkinson) Date: Tue, 04 May 2004 00:10:36 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 3) References: <109deb75jo28v6c@corp.supernews.com> Message-ID: Cameron Laird wrote: > PyLinda makes distributed computing pretty (but slow--slower than > technically required?) > http://www-users.cs.york.ac.uk/~aw/pylinda I'm glad you think it's pretty! It might be slow at the moment but it'll get faster. I'd rather it worked and was slow, than was broken and fast :-) I certainly know that my Mandelbrot fractal generator is horrendously slow... but it does get quicker the more computers you add, which is a start! If anyone out there has taken a look at it and has any suggestions then I'm all ears. I'm currently trying to think of a good way to profile it for bottle necks. Andrew (PyLinda 0.2 can be found at http://www-users.cs.york.ac.uk/~aw/pylinda) -- Quiet! You'll miss the humorous conclusion From brian at sweetapp.com Thu May 6 09:44:49 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 06 May 2004 15:44:49 +0200 Subject: How to get Hostname using SimpleXMLRPCServer In-Reply-To: References: Message-ID: <409A4151.7010105@sweetapp.com> Golawala, Moiz M (GE Infrastructure) wrote: > I have multiple xmlrpc clients talking to my SimpleXMLRPCServer. When a method > on my server is invoked, I would like to know the hostname of the client that > has invoked the method. Does anybody know how to get the client host name from > the xmlrpc request call to the SimpleXMLRPCServer. Any help is > appreciated. Sorry I don't have time to actually write any example code for you, but you might want to look at the BaseHTTPServer documentation. SimpleXMLRPCRequestHandler is a subclass of BaseHTTPServer.BaseHTTPRequestHandler, which has a client_address instance variable and an address_string() method. Let me know if you need any other help (and sorry for ignoring your post yesterday). Cheers, Brian From timothy.williams at nvl.army.mil Tue May 11 11:32:52 2004 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 11 May 2004 08:32:52 -0700 Subject: How to update window after wxGrid is updated? Message-ID: Hi. I'm starting to learn wxPython and for an exercise I'm writing a simple CSV file viewer. I just read in the CSV file and create a wx.Grid with the data. I'm using Python 2.3.2 with wxPython 2.4.2.4. Everything runs fine under linux, but when I try the same code on a Win XP machine, I have a window, but the frame the grid is in isn't seen until I do a minimize/maximize on the window. Besides that, it seems to run fine. I tried to do a self.Refresh(True, self.grid.GetRect()), but that didn't help. Here is the code: #!/bin/env python """ Python script to display CSV file in a table using wxPython """ import os, sys, csv import wx, wx.grid class MyFrame(wx.Frame): def __init__(self, parent, ID, title, size=(200,200)): wx.Frame.__init__(self, parent, ID, title, (-1,-1),size) self.CreateStatusBar() self.dirname=os.getcwd() #create the file menu filemenu=wx.Menu() filemenu.Append(wx.ID_OPEN, '&Open', 'Open CSV File') filemenu.Append(wx.ID_EXIT, 'E&xit', 'Exit the program') #create the menubar for the frame and add the menu to it menuBar=wx.MenuBar() menuBar.Append(filemenu, '&File') self.SetMenuBar(menuBar) #set up menu events wx.EVT_MENU(self, wx.ID_OPEN, self.OnOpen) wx.EVT_MENU(self, wx.ID_EXIT, self.Exit) self.Show(True) return def OnOpen(self, event): dlg=wx.FileDialog(self, 'Choose a file', self.dirname, '', 'CSV files (*.csv)|*.csv|All files (*.*)|*.*', wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.dirname=dlg.GetDirectory() self.filename=os.path.join(self.dirname,dlg.GetFilename()) self.file=file(self.filename, 'r') csvfile=csv.reader(self.file) #grab a sample and see if there is a header sample=self.file.read(8192) self.file.seek(0) if csv.Sniffer().has_header(sample): colnames=csvfile.next() else: row=csvfile.next() colnames=[] for i in len(row): colnames.append('col%d' % i) self.file.seek(0) if getattr(self, 'grid', 0): self.grid.Destroy() self.grid=wx.grid.Grid(self, -1) self.grid.CreateGrid(0, len(colnames)) #fill in headings for i in range(len(colnames)): self.grid.SetColLabelValue(i, colnames[i]) #fill in rows r=0 for row in csvfile: self.grid.AppendRows(1) for i in range(len(row)): try: self.grid.SetCellValue(r, i, row[i]) except: self.grid.AppendCols(1, True) print r, i, len(row), row[i] r += 1 self.file.close() self.grid.AutoSizeColumns(True) self.Refresh(True, self.grid.GetRect()) def Exit(self, event): if getattr(self, 'file',0): self.file.close() self.Close(True) class csv_view(wx.App): def OnInit(self): self.frame=MyFrame(None, -1, 'CSV viewer', size=(800,500)) self.SetTopWindow(self.frame) return True if __name__ == '__main__': app=csv_view() app.MainLoop() ########################## Thanks for any help. From connellybarnes at yahoo.com Wed May 19 23:16:39 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Wed, 19 May 2004 20:16:39 -0700 (PDT) Subject: How to Build Python 2.3.3 C/C++ Extensions in Windows Using Mingw32 Message-ID: <20040520031639.34608.qmail@web14526.mail.yahoo.com> Normally, one uses the following procedure to build and install a C/C++ extension: python setup.py build --compiler=your_compiler python setup.py install For Python 2.3.3 on Windows, with the Mingw (Minimalist GNU) compiler, the following steps must be taken: 1. Find your Mingw bin directory. Copy gcc.exe to cc.exe. 2. Get PExports from either of: http://sebsauvage.net/python/pexports-0.42h.zip http://starship.python.net/crew/kernr/mingw32/pexports-0.42h.zip Extract pexports.exe to your Mingw bin directory. 3. Find pythonxx.dll. It should be in your main Python directory. Do the following: pexports python23.dll > python23.def dlltool --dllname python23.dll --def python23.def --output-lib libpython23.a 4. Copy libpythonxx.a to \python\libs. 5. Patch distutils. Locate \python\lib\distutils\msvccompiler.py, open it, and find the following lines (around line 211): if len (self.__paths) == 0: raise DistutilsPlatformError, \ ("Python was built with version %s of Visual Studio, " "and extensions need to be built with the same " "version of the compiler, but it isn't installed." % self.__version) Delete these. 6. Move back to the directory of your extension. Do the following: python setup.py build --compiler=mingw32 python setup.py install Ideally, only step 6 should be required to install an extension. I submitted the patch for step 5 to python.sourceforge.net. Steps 2-4 can be avoided if the libpythonxx.a file is distributed with Python. I'll email the Python folks and ask them to do this. Step 1 can probably be avoided with another patch. This document is based on http://sebsauvage.net/python/mingw.html, which was written for Mingw + Python 2.2. Thanks, Connelly Barnes PS: To test this process, try compiling myspell-python, a spell checking library for Python. See http://oregonstate.edu/~barnesc/myspell-python-1.01.tar.gz __________________________________ Do you Yahoo!? Yahoo! Domains ? Claim yours for only $14.70/year http://smallbusiness.promotions.yahoo.com/offer From rodelrod at hotmail.com Fri May 28 09:47:19 2004 From: rodelrod at hotmail.com (Rodrigo Daunaravicius) Date: Fri, 28 May 2004 15:47:19 +0200 Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> <40b72a41$0$128$3a628fcd@reader3.nntp.hccnet.nl> <1epn0wa5bqb0r$.heo8w4umjuxm$.dlg@40tude.net> Message-ID: <1a5g050esz2nh.1b1krf6e4dcoj$.dlg@40tude.net> On 28 May 2004 13:19:59 GMT, Duncan Booth wrote: > Rodrigo Daunaravicius wrote in > news:1epn0wa5bqb0r$.heo8w4umjuxm$.dlg at 40tude.net: > >> I couldn't find in the docs what >> is the meaning of the asterisk in zip(*d), though. Nothing to do with C >> pointers, I guess? > > Python Reference Manual, section 5.3.4 Calls: > > If the syntax "*expression" appears in the function call, "expression" must > evaluate to a sequence. Elements from this sequence are treated as if they > were additional positional arguments; if there are postional arguments > x1,...,xN , and "expression" evaluates to a sequence y1,...,yM, this is > equivalent to a call with M+N positional arguments x1,...,xN,y1,...,yM. Got it. I was looking in the wrong places. '*' is not the easiest string to conduct a search on, if it's not referred to as an 'asterisk' somewhere on the text. Thanks, Duncan! Rodrigo Daunaravicius From max at alcyone.com Mon May 24 13:06:14 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 10:06:14 -0700 Subject: Solving the Einstein's Riddle in Python References: Message-ID: <40B22B86.152586E4@alcyone.com> Juha Haataja wrote: > I managed to implement a Python code for solving the > so-called Einstein's Riddle, ... Note that this riddle actually has nothing to do with Einstein. -- __ 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 mind is not a vessel to be filled but a fire to be kindled. -- Plutarch From donn at drizzle.com Sat May 22 13:53:07 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 22 May 2004 17:53:07 -0000 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> Message-ID: <1085248385.210031@yasure> Quoth Arthur : ... | I think I am perfectly capable of making sense of the explanation | that uses the unambigous words heterogenous and homogenous in the | context of this discussion. | | But the ambiguous word in the previous sentence, IMO, is | "explanation". Because in the end - I am repeating myself - I find, | with emphasis given these words - a tautolofgy parading as an | explanation. If repetition works for you, let's go back and give it the works. You first announced this conclusion in a followup to Shalabh Chaturvedi. Here is the account of homogeneity in that post: Chaturvedi: I believe it is conceptual homogeneity and not type homogeneity that characterises the difference between lists and tuples. Consider use of tuples such as (hostname, port) or (firstname, lastname, middleinitial) or (x_coordinate, y_coordinate). In all cases you *know* what the first element means, what the second element means etc. It is usually not useful to find a value since the different values mean different things. You might rather do this something like - if host_port[1] == 80:... Can you quote _both paragraphs_ of the above and point out the circularity in his explanation? I don't know if homogeneity is the most useful term to get at the distinction as I understand it, but evidently that's how Guido tried to explain it, so that's where we start. It can take some explaining. We could try to think of better ways to approach it - maybe bring in the notion of a tuple as a "product" of its elements - but the parties to that discussion would have to 1) understand the distinction, and 2) not be satisfied with the way it's currently explained. No sign of anyone in that corner yet. Donn Cave, donn at drizzle.com From zunbeltz at wm.lc.ehu.es.XXX Mon May 31 07:53:31 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 31 May 2004 13:53:31 +0200 Subject: exceptions Message-ID: Hi, I've the following problem with try/exception. I've a try block that will raise some exceptions. I want the program to ignore this exceptions completely. Is it possible? Thanks in advance Zunbeltz -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From cs993442 at cs.yorku.ca Wed May 19 12:13:06 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Wed, 19 May 2004 12:13:06 -0400 Subject: Socket sample? Message-ID: <40AB8792.1030505@cs.yorku.ca> I'm a newcomer to socket programming... I need to use a server socket which should be able to handle more than one connection at a time. I've read the HOWTO, but I'm still a bit confused about some of the more intimate details. I've also seen a few pieces of sample code scattered here and there, but nothing substantial. Does anyone know of some sample code that handles multiple connections (either by using select() or forking/threading processes)? Thanks very much! --Daniel From jgardner at jonathangardner.net Fri May 7 12:31:34 2004 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 7 May 2004 09:31:34 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <69cbbef2.0404281050.4dc3380e@posting.google.com> <6cc20cea.0405012255.5e352d27@posting.google.com> <69cbbef2.0405021021.7202e995@posting.google.com> Message-ID: <6cc20cea.0405070831.28cb43eb@posting.google.com> has.temp2 at virgin.net (has) wrote in message news:<69cbbef2.0405021021.7202e995 at posting.google.com>... > > Also, it kind of renders the question, "What kind of object is this?" > > meaningless. There are no /kinds/ anymore, at least not built into the > > language. > > Yep. In its purest form, a proto-OO language would have only a single > 'type' - object - and no 'classes' at all. While folk who are used to > relying on type/class information to make their programs work may > freak a bit at the thought of this, languages like Python and Ruby > have already demonstrated that 'duck typing' can work well. (Again, > it's mostly just a matter of the developer having a bit of discipline > in the first place than relying on the compiler to pick up their slop > after the event. I have spent some time thinking about this and looking at my own code. Isn't it currently discouraged to use "type" to classify objects, and then depend on the type returned? Instead, we should look at the actual interface to see if it implements what we need rather than trying to force it to descend from a particular class. Shared class data is trivial to implement in a classless system, as you demonstrated. In fact, so is typing - just have an attribute called "__class__" and methods for determining if a particular class is in the inheritance tree of this object's class. We can even go as far as to implement a system of calling the class's methods or attributes if they are not present in the object itself. (Looks familiar? Isn't this the way Python works right now?) Because implementing the current Python object system in classless objects is so easy to do, it is apparent that classless objects are a superset (IE, contain all the features of and perhaps some more) of classful objects. Therefore, if Python were to approach a classless object system, it would be enhancing its featureset while being able to simultaneously maintain backwards compatibility. (At least, theoretically. I know that the internals of the python interpreter and run time engine depend heavily on objects behaving the way that they do.) The question then becomes: Which is more programmer-friendly: classful or classless programming? The only practical limitation is that with classes, you can stuff all the shared attributes and method into a neat package. However, with classless, whenever you copy an object, you would have to implement the behavior of copying all of the available attributes and methods. How to share that data between multiple copied instances and the original in an efficient manner is non-trivial. From greg at cosc.canterbury.ac.nz Thu May 6 23:59:20 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 07 May 2004 15:59:20 +1200 Subject: Unification of Methods and Functions In-Reply-To: <3sgl90pcsl8s7n4q65v0rnefirrog0clk1@4ax.com> References: <16752bcc.0405050817.4ca77017@posting.google.com> <1083822394.7883@yasure> <3sgl90pcsl8s7n4q65v0rnefirrog0clk1@4ax.com> Message-ID: <2g0fsrF33p4cU1@uni-berlin.de> David MacQuigg wrote: > Static methods > are necessary because it is a very natural thing to write a method in > a class that needs to work without being bound to any particular > instance. I beg to differ. It might seem natural to someone who's been exposed to C++ or Java, but I don't think it's a priori a natural thing at all. In Python, a function defined inside a class is a method. If you want a function to be a method, you put it inside a class. If you don't want it to be a method, you don't put it inside a class. It's as simple as that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From spam at pky2k.de Mon May 24 13:00:02 2004 From: spam at pky2k.de (Philipp Kruse) Date: Mon, 24 May 2004 19:00:02 +0200 Subject: py2exe setup script problem In-Reply-To: References: <2hchapFbelulU1@uni-berlin.de> Message-ID: <2heo0tFbiqgvU1@uni-berlin.de> From: Larry Bates Date: 24.05.2004 17:37 ------------------------------------------------------------ > What do you expect to happen? If program creates > output, you need a console window to display it > (unless you use GUI interface). Without console > output has no where to go. I actually use this > to my advantage on some lights-out applications > that write all their output to log files. I _do_ use a GUI interface. Let me be more precise as I obviously failed to clear up some things. If I use the console = [] attribute, the console window is created and the GUI is started as intended, just as when I execute the .py-File. However, using windows = [], doesn't show any signs of a running programm other than the process running in the task-list which I have to shut down manually. HTH Philipp From jjl at pobox.com Sat May 29 07:23:46 2004 From: jjl at pobox.com (John J. Lee) Date: 29 May 2004 12:23:46 +0100 Subject: jython 2 cpython bridge References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> <87lljdiiyn.fsf@pobox.com> Message-ID: <87lljbeat9.fsf@pobox.com> Steve Menard writes: [...] > Besides I intend to take JPype beyonf Python->Java integration, and > choice is always good :) Especially when the closest alternative is unmaintained! I've certainly wanted something like this in the past. Good luck with your project. John From bobmon at bloomu.edu Fri May 7 18:57:56 2004 From: bobmon at bloomu.edu (Robert Montante) Date: Fri, 07 May 2004 18:57:56 -0400 Subject: VIM and tab to space migration In-Reply-To: References: Message-ID: <409C1474.6020903@bloomu.edu> >> If you are starting with a file that already contains tabs *and* spaces, >> I'd say you have already called upon you the gods of disaster. > >> [snipped] > > But I haven't. I did what you suggested, opened a file using ONLY tabs for indentation and VIM stilled inserted spaces when it pressed the tab yet. > Umm, are you aware of vim configuration files? On Unix the per-user file is ".vimrc" and the global file is $VIM/vimrc ($VIM being vim's installation directory); on Windows the file is %VIM/_vimrc (vim installed in %VIM folder). Choose the appropriate config. file, and add commands to force the tab behavior you want. For example: :set tabstop=4 " Force tabs to be displayed/expanded to 4 spaces (instead of default 8). :set softtabstop=4 " Make Vim treat key as 4 spaces, but respect hard Tabs. : " I don't think this one will do what you want. :set expandtab " Turn Tab keypresses into spaces. Sounds like this is happening to you. " You can still insert real Tabs as [Ctrl]-V [Tab]. :set noexpandtab " Leave Tab keys as real tabs (ASCII 9 character). :1,$retab! " Convert all tabs to space or ASCII-9 (per "expandtab"), " on lines 1_to_end-of-file. :set shiftwidth=4 " When auto-indenting, indent by this much. " (Use spaces/tabs per "expandtab".) :help tabstop " Find out more about this stuff. :help vimrc " Find out more about .vimrc/_vimrc :-) I think it would be really hard to get Vim to guess whether tabs or spaces are being used in each file (unless you're willing to add a "vim" line to the end of each file), but it's really fairly easy to get vim to force each file into whichever convention you want, as soon as it's edited --- just add the "retab" command to the .vimrc file, and it'll convert automatically. (Oh yes, you can also do all the above commands "manually" from the command line, but once you get the ones you want, it's most convenient to put them in .vimrc) HTH, -bob,mon. From qxz_77 at yahoo.com Wed May 26 12:41:59 2004 From: qxz_77 at yahoo.com (Q X) Date: 26 May 2004 09:41:59 -0700 Subject: creating .exe file Message-ID: <3f0686ff.0405260841.6deba711@posting.google.com> Hello everyone, I am wondering what kind of tools are available to wrap python scripts into just 1 .exe file (with no other files) in windows. I also want the .exe file to be able to use command line arguments ie. pythonprogram.exe -classpath d:/temp -file c:/hi.text Also, is this possible to do this free ie. without a commercial compiler like Visual Studios? Help is greatly appreciated. Thanks!!!! From mailinglist at ltsai.com Sun May 30 08:02:22 2004 From: mailinglist at ltsai.com (Tsai Li Ming) Date: Sun, 30 May 2004 20:02:22 +0800 Subject: Redirect stdout & stderr (similar to a daemon) Message-ID: <40b9cd69@news.starhub.net.sg> Dear all, I have a problem with a redirecting stdout and stderr. I am a top level module and has no control over the imported modules that are making system calls such as os.system or popen2.* . I have tried the simplest method of capturing stdout, stderr via: saveout = sys.stdout sys.stdout = file_obj print 1 # works os.system('w') # Doesn't work sys.stdout = saveout print 1 # Restored ------------------------------------------------ Therefore, I changed to the following method, similar to a daemon. However, I couldn't find a way to restore back stdout and stderr. import os import sys stdin = '/dev/null' stdout = '/tmp/out.txt' stderr = stdout # Doesn't work saveout = sys.stdout si = file(stdin, 'r') so = file(stdout, 'a+') se = file(stderr, 'a+', 0) # Redirect standard file descriptors. os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # Gets written to /tmp/out.txt os.system('no_such_command') os.system('w') # How to do restoration of stdout and stderr os.system('w') print "Hello there" Many thanks Liming From richie at entrian.com Fri May 28 06:04:51 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 28 May 2004 11:04:51 +0100 Subject: CreateProcess / redirect output In-Reply-To: References: Message-ID: <2l2eb093lo86hbuchcuv3r3ilsame456vm@4ax.com> [Achim] > I try to start a process on windows using win32process.CreateProcess [...] > I think I'm not the only one which needs to get the output of an external > process on windows. Unless you have a specific reason for using CreateProcess, you can use os.popen*() - see http://www.python.org/doc/current/lib/os-newstreams.html If you really do need to use CreateProcess, this might help: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/creating_a_child_process_with_redirected_input_and_output.asp -- Richie Hindle richie at entrian.com From jepler at unpythonic.net Mon May 31 10:48:40 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 31 May 2004 09:48:40 -0500 Subject: [].index In-Reply-To: References: Message-ID: <20040531144840.GB19206@unpythonic.net> Using your test case: >>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] >>> foo = ['b', 'e', 'e'] I'd define a function to do the difficult part: (note that in Python 2.3, "s in t" returns True if s is a substring of t. In earlier versions, "s in t" worked only when s was a length-1 string) >>> def match(substring, candidates): ... """Return the candidate which contains substring""" ... for c in candidates: ... if substring in c: return c Then, the list comprehension becomes simple: >>> [match(c, data) for c in foo] ['bbb', 'eee', 'eee'] Even if you want to write this as a single list comprehension, why not >>> [iy for ix in foo for iy in data if ix in iy] ['bbb', 'eee', 'eee'] ... though if some item in foo doesn't correspond to any items in data, you just get a different-length output than input, not an exception (as for your code) or a None in the resulting list (in my first example) Personally, I'll take the approach that uses a function. The pure-listocmp version I wrote might as well say >>> [fee fie foe fum i smell the blood of an englishman] as far as my eyes are concerned. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tzot at sil-tec.gr Mon May 31 18:03:43 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 01 Jun 2004 01:03:43 +0300 Subject: getting mimetype of a file References: Message-ID: <4qanb0tlakc4na7rd5nbnh8f4n0d4mrcu1@4ax.com> On Mon, 31 May 2004 19:58:10 GMT, rumours say that Ryan Paul might have written: >> is there any way to determine the mimetype of a file using ruby? [snip] >=P just realized I sent this to the wrong list. as long as I'm here... how >is it done in python? The mimetypes.py module in the standard library is your friend. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From has.temp2 at virgin.net Sun May 2 06:22:22 2004 From: has.temp2 at virgin.net (has) Date: 2 May 2004 03:22:22 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> Message-ID: <69cbbef2.0405020222.6024b162@posting.google.com> s " wrote in message news:... > Quoting from a previous post quoting by someone else: > > Modules are an encapsulation mechanism, just like class instances, so > > I'd say the large and obvious overlap counts as unnecessary > > I don't see this. 'Class instance' is an abstract concept, not a > particular object. Please forgive my linguistic sloppies. How about if I say 'an object of type "instance"'; does that sound clearer? Regarding the remainder of your post, your argument seems to be that Python has got all this stuff [that you describe], therefore all this stuff is needed. Have you tried the sorts of systems I've been describing for comparison? Because I've worked with both types of system, so what I describe is anything but fuzzy theorising: these systems already exist and there's nothing to stop anyone else from trying them out themselves _before_ trying to critique my arguments. So I may I respectfully suggest that yourself and others do just this. Because then you can argue from a position of strength, having weighed the pros and cons of both approaches and formulated your arguments based on that, rather than out of some religious obligation to defend the orthodoxy from any kind of perceived attack, regardless of whether or not you even understand what this "attack" actually is. Which is what these and other arguments, for all their seeming depth, really boil down to in the end. I'm sorry if this sounds personal; it isn't really. As an outsider who's spent years looking in, I've had plenty of time to observe the best and worst of programming culture in action, and it's the subtle* but strong undercurrent of blind reactionary conservatism that runs through much of it that I find most frustrating. I'm genuinely happy to see my arguments taken apart by folk who understand them better than me. Many are naive and simplistic and others are completely wrong; I honestly look forward to having my preconceptions challenged and my prejudices shattered. It's the feeling I sometimes get that I'm being rebuffed merely for questioning the religious orthodoxy; that my position is percieved as a threat because I won't meekly accept everything I'm told as an obvious truth. This is what I'm unhappy about. So please, give me confidence that I'm being taken apart by an expert who wants to set me right, not by some frightened partisan who only wants to defend their faith. Impress me. Make me admire your arguments. Give me something to _really_ think about. I honestly don't think it's too much to ask. Regards, has -- * slashdot excepted ;) From hust_zxq524 at 263.net Thu May 13 03:42:26 2004 From: hust_zxq524 at 263.net (Frank Zheng) Date: Thu, 13 May 2004 15:42:26 +0800 Subject: one problem about smtplib.py Message-ID: I wrote some code to test "smtplib", but i met a problem when i call the "login(user,pass)" of the "SMTP" object. here are the codes: >>> s = smtplib.SMTP() >>> s.set_debuglevel(1) >>> s.connect('smtp.263.net') connect: ('smtp.263.net', 25) connect: ('smtp.263.net', 25) reply: '220 Welcome to coremail System(With Anti-Spam) 2.1 for 263(040326)\r\n' reply: retcode (220); Msg: Welcome to coremail System(With Anti-Spam) 2.1 for 263(040326) connect: Welcome to coremail System(With Anti-Spam) 2.1 for 263(040326) (220, 'Welcome to coremail System(With Anti-Spam) 2.1 for 263(040326)') >>> s.login('Frank','*****') send: 'ehlo pc11.FutureDialChina.FutureDialChina.com\r\n' reply: '250-smtp.263.net\r\n' reply: '250-PIPELINING\r\n' reply: '250-SIZE 30720000\r\n' reply: '250-ETRN\r\n' reply: '250-AUTH LOGIN\r\n' # should be "250-AUTH PLAIN" reply: '250-AUTH=LOGIN\r\n' reply: '250-XVERP\r\n' reply: '250 8BITMIME\r\n' reply: retcode (250); Msg: smtp.263.net PIPELINING SIZE 30720000 ETRN AUTH LOGIN AUTH=LOGIN XVERP 8BITMIME AuthMethod: None Traceback (most recent call last): File "", line 1, in ? File "D:\tools\Python22\lib\smtplib.py", line 540, in login raise SMTPException("No suitable authentication method found.") SMTPException: No suitable authentication method found. I read the "login" of "smtplib" , I found it has two authentication method one is "PLAIN", the other is "CRAM-MD5", but the server's reply here didn't chose one of these two choices. I tested several mail-servers in China, they all just support "AUTH LOGIN". I found the Outlook use "AUTH LOGIN" and make it as standard. So I think smtplib maybe need do some changes, or someone has already did this work. Thanks Frank From bram at nospam.sara.nl Wed May 19 05:23:11 2004 From: bram at nospam.sara.nl (Bram Stolk) Date: Wed, 19 May 2004 11:23:11 +0200 Subject: thread safe datastructures other than Queue? Message-ID: <20040519112311.6eece274@pistache.sara.nl> Hello, Python features the Queue.Queue object that provides thread-safe access. What if I want thread access to other types of datastructures? Would I need to pair e.g. each list, Set or hashmap with its own threading.Semaphore() object? Or is there an easier way to have thread-safe access to datastructures? Thanks, Bram Stolk -- ------------------------------------------------------------------------------ Bram Stolk, VR Engineer. SARA Academic Computing Services Amsterdam, PO Box 94613, 1090 GP AMSTERDAM email: bram at nospam.sara.nl Phone +31-20-5923059 Fax +31-20-6683167 "Software is math. Math is not patentable." OR "Software is literature. Literature is not patentable." -- slashdot comment ------------------------------------------------------------------------------ From eriksp at attbi.nospam.com Wed May 26 06:00:45 2004 From: eriksp at attbi.nospam.com (EAS) Date: Wed, 26 May 2004 10:00:45 GMT Subject: Command Prompt (again) Message-ID: 2 days ago, I used the following script to get a command prompt on my system: import os os.system('cmd.exe') However, yesterday, when I tried to use it again, it did nothing but return "-1" to the screen. Anyone know what happened and how to fix it? From torsten.marek at student.uni-tuebingen.de Fri May 7 13:16:13 2004 From: torsten.marek at student.uni-tuebingen.de (Torsten Marek) Date: Fri, 07 May 2004 19:16:13 +0200 Subject: ANN: A new wiki for PyQt and PyKDE Message-ID: If have the pleasure to announce that we created a wiki for GUI development with PyQt and PyKDE at http://www.diotavelli.net/PyQtWiki Everybody who searches for information about GUI creation with Python will find links to tutorials, howtos and sample code. If you never heard about PyKDE and/or PyQt, the time might be great, because PyKDE 3.11 with support for KDE 3.2.x is in its beta stage right now and will be released soon. Even more, we ask you for your contributions to the wiki. We are searching for tutorials, documentation, (online) books, existing applications, development tricks, sample code, GUI design articles etc., so please participate. About PyQt: PyQt contains the Python bindings to the Qt C++ GUI toolkit developed by Trolltech. With it, you can easily create complex multi platform GUI programs using RAD technologies. PyQt supports Linux and various flavours of Unix, MacOS X and Windows under a variety of licenses including the GPL and a commercial license. For licensing and prices, please look at the homepage of PyQt. With PyQt, you have all the benefits of the Qt toolkit, including the Qt Designer, SQL support and native widget look on Windows and MacOS X without the drawbacks of the C++ API like the moc and long compilation times. PyQt is written by Phil Thompson at Riverbank Computing, Ltd.. About PyKDE: Based on PyQt, PyKDE provides Python interfaces to the KDE C++ API. It allows tight integration of your application into the KDE desktop environment and makes it indistinguishable from "native" C++ programs. You can not only use the more advanced KDE widgets, but also the state-of-the-art KDE technologies like KParts (the component model - why not make your own web browser with KHTML), KIO and KFile (use webdav, samba, fish and many more protocols like your filesystem), DCOP and the printing libraries (KDEPrint), combined with the productivity of Python and the well-known Qt tools. PyKDE is currently maintained by Jim Bublitz, early versions were written by Phil Thompson. From dmq at gain.com Thu May 13 11:15:57 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 13 May 2004 08:15:57 -0700 Subject: list comprehension References: Message-ID: On Mon, 10 May 2004 12:32:20 +1200, Guy Robinson wrote: >Hello, > >Trying to change a string(x,y values) such as : > >s = "114320,69808 114272,69920 113568,71600 113328,72272" > >into (x,-y): > >out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" > >I tried this: > >print [(a[0],-a[1] for a in x.split(',')) for x in e] > >But it doesn't work. Can anyone suggest why or suggest an alternative >way? The text strings are significantly bigger than this so performance >is important. Seems like this is a very common problem, needing to process a substring within a long list of strings. I like the way Ruby handles these problems. Maybe a future version of Python could do this: print s.split(' ').map().split(',').reflecty().join(' ') You would need to define the reflecty() function, but the others should be standard. Depending on how much variation you expect in the input data, reflecty() could do whatever checking is necessry to avoid the problems other posters have mentioned. Assuming the inputs are valid string representations of numbers (i.e. no double minuses, etc.), a simple definition could be: def reflecty(): x,y = __self__ # a two-string list if y[0] == '-': return [ x, y[1:] ] else: return [ x, '-' + y ] The above syntax is neither Ruby nor Python, but the idea of handling complex sequences of string operations step-by-step, left-to-right was inspired by Ruby. See http://userlinux.com/cgi-bin/wiki.pl?RubyPython for a comparison of Ruby and Python string operations. -- Dave From paddy3118 at netscape.net Wed May 26 12:24:14 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 26 May 2004 17:24:14 +0100 Subject: Why a class when there will only be one instance? In-Reply-To: References: <40B3E861.29B033D5@shaw.ca> Message-ID: Ryan Paul wrote: > On Tue, 25 May 2004 21:20:02 -0400, Roy Smith wrote: > > >>Ryan Paul wrote: >> >>>defining a class may be useful if you plan on making more instances down >>>the line. It's a good OO strategy. I do understand your dislike of 'self'. >>>It does seem like clutter. In my code, I shorten it to 's'. >> >>Please don't do that. While it's true that the first parameter of a >>class method can be named anything, the use of "self" is so >>overwhelmingly ubiquitous it might as well be a standard. Using >>anything else is just going to make your code more difficult for anybody >>else to read and understand. >> >>Typing is cheap. Thinking is expensive. And, yes Aahz, you can quote >>me on that :-) > > > I dont conform to a bad standard just because it's a standard. If I did, I > would be using java instead of a dynamic language like python. If other > people dont like it, thats too bad- they dont have to use my code. > It's your code but might I suggest that you then be consistent in your naming convention to aid re-use? - Pad. From skip at pobox.com Wed May 19 09:15:08 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 May 2004 08:15:08 -0500 Subject: CSV: minimalquoting and skipinitialspace, In-Reply-To: <40ac2eba.12454921@news.versatel.de> References: <40ac2eba.12454921@news.versatel.de> Message-ID: <16555.24028.742031.432958@montanaro.dyndns.org> Martin> Proposal: Martin> QUOTE_MINIMAL Martin> Instructs writer objects to only quote those fields which Martin> contain the current delimiter or begin with the current Martin> quotechar or start with a [blank | white space character] if the Martin> dialect specifies skipinitialspace=False. Martin> What do you think? It's an idea with merit. Can you post a feature request to the Python project on SF? Even better would be a patch that implements the idea. ;-) Skip From peter at engcorp.com Sat May 29 21:23:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 May 2004 21:23:09 -0400 Subject: pywin32 201.1 Windows98SE Problem? In-Reply-To: References: Message-ID: Bob Chapman wrote: > On two different Windows 98SE Systems, I have attempted to upgrade working [...] > >__import_pywin32_system_module__ > > raise ImportError, "Can not locate " + filename > >exceptions.ImportError: Can not locate pywintypes23.dll > > On checking, the NEW 'pywintypes23.dll' IS in c:\windows\system > > > 77824 May 28 11:10 c:\windows\system\pywintypes23.dll > > If this file is copied to C:\Windows then Pythonwin starts without the error > messages and appears to work. What happens if you run Python from the command line and type "import pywintypes"? In other words, is this a problem with the Python installation or a problem with the pywin32 installation? You should learn the answer as a result... -Peter From jacek.generowicz at cern.ch Fri May 7 03:32:07 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 May 2004 09:32:07 +0200 Subject: Private identifiers - naming References: <930ba99a.0405060600.17e076bc@posting.google.com> <409a6791$0$31686$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Richard Taylor writes: > So the point of a 'private' variable is to indicate to the user of a class > that the author of the class did not intend it to be accessed directly. > Personally I tend to do this by appending a single '_' to method or > identifier names. FWIW, "me too". From della at toglimi.linux.it Tue May 25 11:52:06 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Tue, 25 May 2004 15:52:06 GMT Subject: Update with pickle In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Is it possible to use the pickle module to update an object instead of > creating a new instance? I don't get what you want to do. Can you explain yourself better? What do you mean by "updating" an object? -- Ciao, Matteo From tor.iver.wilhelmsen at broadpark.no Sat May 29 15:41:26 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 29 May 2004 21:41:26 +0200 Subject: Python with TestDirector References: Message-ID: "Chuck" writes: > What's the relationship - Is TestDirector written in Python? I strongly doubt it - at least the TestDirector 7.6 we use where I work runs as an ActiveX application in MSIE, and most of those are written using Visual Studio and its selection of programming languages. From ak at silmarill.org Wed May 26 12:26:24 2004 From: ak at silmarill.org (AK) Date: 26 May 2004 09:26:24 -0700 Subject: Problem with curses: screen is blanked on second refresh Message-ID: <7fdc73c1.0405260826.1a1565b7@posting.google.com> Hi, I have a medium sized app that I'm transferring to use curses. What happens is very very strange.. I am at my wits' ends. I worked with it all day yesterday and couldn't figure it out. Today morning I thought about it and still nothing. I hope that some curses expert can figure out what's wrong from my description. I'm very new to curses so I am not sure I know which details are crucial, so please answer me if you need more details. I have a function that uses win.addnstr() calls to add strings to the win (which is passed by curses.wrapper). First time the function is called, it works just fine. Second time it makes the screen blank and the only things that show up are single digits that are updated by another thread. The x coord given to the addnstr() is always 0. That thread should print a line with elapsed time, full time, and a short string of text; it should print on the bottom line on screen. First time it's called it does just that; all other times it prints only the digits of the elapsed time that are different from what was already there, and it blanks the rest of the line; and it prints it on *top* line of screen. If I call win.clear() at the top of the main redraw function, it works fine. Full screen is updated and shown. The only problem is that it flickers while updating. It flickers once but it's annoying enough - I hope to only update spots on screen that really changed. If I call win.redrawwin() instead of win.clear(), the lines that changed are updated and shown, but *all other lines are blanked*. And if I call neither win.clear() nor redrawwin(), the whole screen is blanked on second redraw, and as I said only single digits changing show up at the top of screen instead of bottom. Things I tried: I passed the same string 'TEST', to all lines. They show up fine on first refresh, then disappear. So this is not about the strings I pass. I have other threads updating the screen, but even if I disable all of them, I get the same strange behaviour. Hope you can advise me.. thanks From dkgunter at lbl.gov Sun May 2 13:59:11 2004 From: dkgunter at lbl.gov (Dan Gunter) Date: Sun, 02 May 2004 10:59:11 -0700 Subject: Efficient string concatenation methods In-Reply-To: References: Message-ID: <409536EF.5020109@lbl.gov> Oliver Crow wrote: > As a realtive python newb, but an old hack in general, I've been > interested in the impact of having string objects (and other > primitives) be immutable. It seems to me that string concatenation is > a rather common operation, and in Python having immutable strings > results in a performance gotcha for anyone not aware of the impact of > doing lots of concatenation in the obvious way. > > I found several sources with advice for how to do concatenation in a > pythonic way (e.g. ref#1), but I hadn't seen any measurements or > comparisons. So, I put together a little test case and ran it through > for six different methods. Here's the results, and my conclusions: > > http://www.skymind.com/~ocrow/python_string/ > > I'd be happy to hear if anyone else has done similar tests and if > there are any other good candidate methods that I missed. > > ref #1: http://manatee.mojam.com/~skip/python/fastpython.html#stringcat > > Oliver Thanks for the nice benchmark. I think you should mention one important detail though: binary-to-decimal-string conversions like `num` are relatively expensive! If you generate these strings ahead of time (e.g. put them in a global list), you get a 20%-30% speedup across the board. def method6a(): out_str = ''.join([NUMS[num] for num in xrange(loop_count)]) ps_stats() return out_str loop_count = 500000 NUMS = [`n` for n in xrange(0,loop_count)] ... -Dan -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3415 bytes Desc: S/MIME Cryptographic Signature URL: From moughanj at tcd.ie Sat May 8 10:07:09 2004 From: moughanj at tcd.ie (James Moughan) Date: 8 May 2004 07:07:09 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> Message-ID: <16752bcc.0405080607.4bb18276@posting.google.com> David MacQuigg wrote in message news:<4a9o90pbu122npgf4m2hrgg04g2j0ic6ka at 4ax.com>... > On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: > > > > >Let me give an example: > > > >def getLength(s): return s.length > > > >class Foo: > > length = 5 > > > >Foo.getLength = getLength > > > >foo = Foo() > >print length(foo), foo.length() > > The last two function calls don't work. There is no such function > named 'length' and foo.length is an integer, not a function. Ooops, let me re-write it how I meant it :) def getLength(s): return s.length class Foo: length = 5 Foo.getLength = getLength foo = Foo() print getLength(foo), Foo.getLength(foo), foo.getLength() Obviously I meant getLength, not length, on the last line. > The example in the proposed syntax would be the same, except there > would be no 'self' in the function definition, and there would be no > magic first argument 'foo' in the last call. foo isn't a 'magic argument'; I'm calling a function with a parameter, which happens to be an object. This is normal. The example stresses that methods are functions which just happen to be attached to a class. > Also, if you are calling > a function that has an instance variable ( .length ) and no instance > has been set by a prior binding, you would need to set __self__ > manually. > __self__ = foo; print FooLen() ???!!!??? This is what I was talking about in my first post, global variables which change depending on where you are in the code... as I understand what you're saying, __self__ will have to be set, then reset when a method is called from within a method and the exits. And __self__ could presumably be changed halfway through a method, too. I'm sorry, I don't see this as being more explicit or simpler. > > This is rarely needed. Normally a call to an unbound function would > be in a context where __self__ is already set. From the Animals_2.py > example: cat1.talk() calls Cat.talk() which calls Mammal.talk() > __self__ is set to cat1 on the first call, and it is not changed by > the call to the unbound function Mammal.talk() > > >A method in a class in Python is just like a global function; for a > >global function to operate on an object, it must take it as an > >argument. The prototype syntax would appear to break the above > >example. > > Global functions have no instance variables, so there is no need for a > special first argument. A Python method requires a special first > argument (even if it is not used). But the first argument isn't terribly 'special'; it tells the method what it's working on, just like any other argument. It's only 'special' characteristic is that there's some syntactic sugar to convert foo.getLength() into Foo.getLength(foo). > >> The difference in the proposed syntax is that it doesn't need the > >> staticmethod wrapper to tell the interpreter -- don't expect a special > >> first argument. In the new syntax all functions/methods will have the > >> same calling sequence. > > > >If a method doesn't operate on the data from an object then as a rule > >it should be global. There are exceptions, but they generally don't > >occur in Python so much as a in 'true oo' language like Java. > > The placement of a function at the module level or in a class should > be determined by the nature of the function, not any syntax problems. > If the function has characteristics unique to a class, it ought to be > included with that class. The Mammal.show() function, for example, > provides a display of characteristics unique to mammals, so we put it > in class Mammal. We could have written a general-purpose Inventory() > function to recursively walk an arbitrary class hierarchy and print > the number of instances of each class. That general function would be > best placed at the global level, outside of any one class. > Mammal.show() shows characteristics to do with Mammals, *but not specifically Mammal*. There really is a difference between a class and it's subclasses. The general-purpose inventory solution would be a better solution. It doesn't require repetition, it's hard (impossible?) to break and it's generic, allowing it to be used beyond this single class heirarchy. If the inventory function would be best placed outside a class, why do you think it's a good idea to put something with exactly the same functionality inside your classes? > >> I've looked at a few introductions to Python, and in my opinion > >> Learning Python, 2nd ed, by Mark Lutz and David Ascher is the best. > >> It strikes a good balance between the minimal presentation that > >> tersely covers the essentials for an experienced programmer vs the > >> long, windy introductions that put you to sleep with analogies to car > >> parts and other "objects". Lutz takes 95 pages to cover OOP. I think > >> I could do a little better, maybe 70 pages, but that may be just my > >> ego :>) > >> > >> When you say ten pages, you must be making some very different > >> assumptions about the students or their prior background, or the > >> desired level of proficiency. The least I can imagine is about 30 > >> pages, if we include exercises and examples. And that 30 assumes we > >> get rid of all the unneccesary complexity (static methods, lambdas, > >> etc.) that currently fills the pages of Learning Python. > >> > > > >I'm assuming they alreay know the general structures of programming in > >Python, and that you can then just show them how to package data and > >methods into a class with a clear example, by rewriting a program > >you've shown them before. After that it's mainly a question of > >explaining why you should do it, which is probably rather more > >important than how. > > *Why* is not an issue with my students. They will have plenty of > examples in our circuit design program to look at. If anyone ever > asks "Why OOP", I'll just have them look at the Qt Toolkit, which will > be the basis of our user interface. Enormous complexity, packaged in > a very easy-to-use set of objects. > Well, I don't know your course so I guess I shouldn't comment on what you're doing. :) > I need to show them *how* to undestand the OOP structures in that > program, and do it in the most efficient way. The chapter on > Prototypes at http://ece.arizona.edu/~edatools/Python/ is my best > effort so far. I've got the basic explanation down to 10 pages. I > expect this to expand to about 30 with examples and exercises. That > will be about four hours of additional work, including lecture, > reading, and practice. > > >I've never met anyone who had difficulty in understanding anything > >about the syntax of OO other than the class/object distinction. It's > >fundamentally very simple once you have a basis in all the other > >programming techniques. > > I guess you haven't met anyone learning C++. :>) > Lol, not who hadn't taken up Java beforehand, no. C++ does a wonderful job of obscuring a simple language behind crazy syntax. > >Unless you're talking about the entire programming course, 70 pages is > >waaay too much - your students just will not read them, regardless of > >how brilliant they are. > > Learning Python, 2nd ed. by Mark Lutz and David Ascher is generally > considered the best introductory text on Python. 96 pages on OOP. > Books are always kind of strange, because a book must have a certain number of pages and cover a certain range of content at a certain technical level. For the level and range of the ORA Learning books, that is going to mean a bit of padding for a simple language like Python. If I see Learning Python in a bookshop then I'll take a look, though. Regardless, I stand by what I said before - students generally will not read 70 pages on a single topic, especially when it's a relatively minor part of the course. > [snip a few paragraphs where we agree !! :>) ] > >Learning to program is about 5% how to do something, and 95% when and > >why you should do it. You seem to be focusing almost exclusively on > >how, which I suspect is why we're all so upset :) you get that way > >when you have to fix the code which eventually results. > > The OOP presentations I've seen that focus as much as 50% on *why* > generally leave me bored and frustrated. I feel like screaming -- > Stop talking about car parts and show me some nice code examples. If > it's useful, I'm motivated. Good style is a separate issue, also best > taught with good examples (and some bad for contrast). > I'm not talking about car parts. I'm talking about explaining modularity, complexity, side-effects, classes as data structures etc. (It's hilarious to see what happens when people get taught by car-part style metaphors; they take them completely literally. I've seen someone writing the classic vending machine example write a 'Can' class, subclass it to get 'CokeCan', 'PepsiCan'... and then create ten of each to represent the machines' stock. That was after three years of university, too...) > > > >OK: "The whole idea of having these structures in any program is > >wrong." > > > >Firstly, the program uses a class hierarchy as a data structure. That > >isn't what class heirarchies are designed for, and not how they should > >be used IMO. But it's what any bright student will pick up from the > >example. > > The classes contain both data and functions. The data is specific to > each class. I even show an example of where the two-class first > example forced us to put some data at an inappropriate level, but with > a four class hierarchy, we can put each data item right where it > belongs. > The data is not specific to the class. It's specific to the class and it's subclasses. Subclasses should be dependent on the superclass, and generally not the other way around. > > Nothing in the Bovine class can affect anything in a Cat. Feline and > Bovine are independent branches below Mammal. Adding a Mouse class > anywhere other than in the chain Cat - Feline - Mammal - Animal cannot > affect Cat. Could you give a specific example? > Say someone adds a mouse class but doesn't call the constructor for Mammal. The data produced by mammal and therefore cat is now incorrect, as instances of mouse are not included in your count. In a real example, anything might be hanging on that variable - so e.g. someone adds some mouse instances and the program crashes with an array index out of bounds (or whatever the Pythonic equivalent is :) ) , or maybe we just get bad user output. This type of behaviour is damn-near impossible to debug in a complex program, because you didn't change anything which could have caused it. It's caused by what you didn't do. > I'm not sure what you mean by "side effects" here. The show() > function at each level is completely independent of the show() > function at another level. > But the inventory data isn't independent. It's affected by classes somewhere else in the heirarchy. Worse, it's done implicitly. >Chaining them together results in a > sequence of calls, and a sequence of outputs that is exactly what we > want. The nice thing about separating the total "show" functionality > into parts specific to each class is that when we add a class in the > middle, as I did with Feline, inserted between Mammal and Cat, it is > real easy to change the Cat class to accomodate the insertion. > > Python has a 'super' function to facilitate this kind of chaining. > Michele Simionato's 'prototype.py' module makes 'super' even easier to > use. Instead of having Cat.show() call Mammal.show() I can now just > say super.show() and it will automatically call the show() function > from whatever class is the current parent. Then when I add a Feline > class between Mammal and Cat, I don't even need to change the > internals of Cat. That's fine - providing you're not using a class heirarchy to store data. It's not the act of calling a method in a super-class which is a bad idea, it's the way you are making *the numbers outputted* from cat dependent of actions taken *or not taken* in another class *completely outside cat's scope*. > > >> What I'm looking for is not clever re-structuring, but just a > >> straightforward translation, and some comments along the way -- oh > >> yes, that is a little awkward having to use a staticmethod here. Wow, > >> you mean staticmethods aren't fundamentally necessary, just a bandaid > >> to make up for Python's deficiencies? That was my reaction when I > >> first saw Prothon. > > > >Static methods are more like a band-aid to make up for the > >deficiencies of OOP. Python isn't a pure OO language, and doesn't > >suffer the need for them badly. > > In one syntax we need special "static methods" to handle calls where a > specific instance is not available, or not appropriate. In another > syntax we can do the same thing with one universal function form. > > -- Dave From __peter__ at web.de Mon May 10 13:49:15 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 May 2004 19:49:15 +0200 Subject: function causing core dump References: Message-ID: Xaver Hinterhuber wrote: > Hello pythonistas, > > I build a function with the following code segment: > > codeObject = new.code( > 0, # argcount > 0, # nlocals > 0, # stacksize > 0, # flags > codeString, # code > (), # consts > (), # names > (), # varnames > 'content', # filename > 'content', # name > 3, # first line number > codeString # lnotab > ) > f = new.function(codeObject, dict, 'f') > f() > > Everything runs fine, until the function is called with f(). > When python tries to execute f(), the core dump happens. > I don't have any clue why python core dumps. > The codeString is nothing complex, its a one-liner. > Could you plz give me some tips what I have to do? > > With kind regards > Xaver Hinterhuber The easiest approach is probably to start with an attribute set known to be good: >>> def f(): pass ... >>> code = f.func_code >>> names = dir(code) >>> names.sort() >>> for name in names: ... if not name.startswith("_"): ... print "%s=%r" % (name, getattr(code, name)) ... co_argcount=0 co_cellvars=() co_code='d\x00\x00S' co_consts=(None,) co_filename='' co_firstlineno=1 co_flags=67 co_freevars=() co_lnotab='' co_name='f' co_names=() co_nlocals=0 co_stacksize=1 co_varnames=() >>> and change the values until you get a core dump - again. Peter From ajsiegel at optonline.com Sun May 23 22:33:40 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 24 May 2004 02:33:40 GMT Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> Message-ID: <7dn2b0l2qe9srf6r0a33032l8jbvtfuf73@4ax.com> On Sun, 23 May 2004 23:30:37 GMT, Arthur wrote: >http://mail.python.org/pipermail/python-dev/2003-March/033964.html > >Qutoeth Guido: > >"Tuples are for heterogeneous data, list are for homogeneous data." > With the next epicycle needed to save the phenonenon perhaps being to suggest that I am distorting his meaning by quoting him percisely. But the truth is I am open to intepretations. Though I suspect I've heard the range, by now. Art From jcalcarez at mapua.edu.ph Thu May 6 22:59:13 2004 From: jcalcarez at mapua.edu.ph (Joel C. Alcarez) Date: Fri, 7 May 2004 10:59:13 +0800 Subject: VPython and 3D Visualization Message-ID: <2072938A1774F148B9726799FEA906BD03369F@mail.mapua.edu.ph> An HTML attachment was scrubbed... URL: From sross at connectmail.carleton.ca Fri May 14 12:38:42 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 14 May 2004 12:38:42 -0400 Subject: beginner's question References: Message-ID: "Hadi" wrote in message news:c82kae$auh$1 at lust.ihug.co.nz... > Sean, > file-1 contains about 500 lines. > > Also when I run the below script, I am getting following error in the > command line: > > File "", line 1 > python test.py > > SyntaxError: syntax error > > Any suggestion about this? > > Thanks again. > hadi [snip] > > # open the source and destination files > > src = file("file1/path") # open for reading > > dst = file("file2/path", 'w') # open for writing [snip] Well, I'm not sure. Here, I've made a test file called "words.txt" in the same directory where I'm running the program. The file contains: our, list, of , words, but, some, are, not, in, the, lexicon all on one line. so for src I do src = file("words.txt") And for dst I create an "output.txt" file dst = file("output.txt", 'w') The rest of the program is unmodified, except for the change from str(w in lexicon) to "%s "%(w in lexicon). When I run the program I receive no errors, and the output.txt file contains: True True True True False False False False False False False So, it appears to work fine over the data (and the manner in which it was stored) for which it was written. Your data (in file-1) is not stored in the same way so you'll need to augment the code to handle those differences. To get more detailed help it would be a good idea to post the code you have written, give a sample of what file-1 contains, and give an example of what you want file-2 to look like. Oh, and there's nothing wrong with helping beginners (a lot of us read this group hoping to do so), it's just that sometimes it is *more* helpful to show you how to learn how to do things on your own, rather than giving you the answers directly. So, when I apologized in that post to Peter, most of that apology would have been directed towards you - I did you a disservice by not allowing you to learn how to learn. It may not always seem that way, when you just want the answers, but it's true, nevertheless. Sean From me at privacy.net Wed May 26 03:50:07 2004 From: me at privacy.net (Duncan Booth) Date: 26 May 2004 07:50:07 GMT Subject: Cleaner idiom for text processing? References: Message-ID: Peter Otten <__peter__ at web.de> wrote in news:c91got$vpi$00$1 at news.t- online.com: > Yet another way to create the dictionary: > >>>> import itertools >>>> nv = iter("foo 1 bar 2 baz 3\n".split()) >>>> dict(itertools.izip(nv, nv)) > {'baz': '3', 'foo': '1', 'bar': '2'} >>>> You can also do that without using itertools: >>> nv = iter("foo 1 bar 2 baz 3\n".split()) >>> dict(zip(nv,nv)) {'baz': '3', 'foo': '1', 'bar': '2'} >>> However, I'm not sure I trust either of these solutions. I know that intuitively it would seem that both zip and izip should act in this way, but is the order of consuming the inputs actually guaranteed anywhere? From rogerb at rogerbinns.com Mon May 24 17:26:43 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 24 May 2004 14:26:43 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: Mark Hahn wrote: > Is there any dynamic language that already does this right for us to steal > from or is this new territory? I know for sure that I don't want to steal > Java's streams. I remember hating them with a passion. Java's bytes being signed also caused no end of annoyance for me. In our protocol marshalling code (thankfully mostly auto generated) there was lots of code just to turn the signed bytes back into unsigned bytes. (I also *very* strongly agree with Paul.) Roger From tim.one at comcast.net Tue May 11 13:10:15 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 11 May 2004 13:10:15 -0400 Subject: OT: Idea for Python T-shirt In-Reply-To: Message-ID: [Peter Hansen] >>> If you plan to try selling them, note that in North America it's >>> generally "nybble", by analogy with "byte". Nibble is the British >>> English spelling. [Heiko Wundram] >> I guess he refers to the other meaning of nibble (from >> dictionary.com): >> >> 1. A very small quantity, especially of food; a morsel. [Peter Hansen] > Then I _really_ don't get it. s/b/p/g From ville at spammers.com Sat May 15 05:29:38 2004 From: ville at spammers.com (Ville Vainio) Date: 15 May 2004 12:29:38 +0300 Subject: RELEASED Python 2.3.4, release candidate 1 References: Message-ID: >>>>> "Chris" == Hornberger, Chris writes: Chris> Point being, if the developers of Python (and Perl and Chris> .... so on) spent so much time and energy creating Chris> something cross platform, it should be used thusly. I'm not Languages (and to a lesser extent, libraries) have a long tradition of being cross platform. Applications don't. Chris> saying it's "evil" not to do so, I'm saying that if you Chris> NEED platform-specific tools (which, let's be honest, Chris> happens WAY more frequently on Windows), then use a Chris> platform-specific tool. I don't see the logic here. Platform specific tool isn't necessarily superior on the platform. It's just restricted to the platform. Chris> RAD/GUI tool than VB (your opinions vary, I'm sure). Nor is Chris> there a better "server side" scripting tool than Perl (I Chris> like Python better, but that's just me). Java does a So you think Python is better, but then praise that perl as superior, because someone else might think so? This is c.l.py, I would guess most people here think Python is superior for "server side" scripting. Chris> Any mechanic or tradesman will tell you, 1/2 the job is Chris> knowing which "right tool for the job" is right. The analogy of "right tool for the job" is more usable for choosing the correct libraries or even algorithms than choosing the language. Choosing the language is about choosing the right toolbox. The Python toolbox has all the tools. If you need to do something platform specific, you just add some extra tools to the tidy compartments of the box, not throw away the whole box and search for another toolbox, which has much less tools, is messy anw whatnot, with the sole virtue of being cross platform. Briefly: "right tool for the job" analogy is severely abused in contexts in which it doesn't apply. -- Ville Vainio http://tinyurl.com/2prnb From claird at lairds.com Thu May 20 09:24:08 2004 From: claird at lairds.com (Cameron Laird) Date: Thu, 20 May 2004 13:24:08 -0000 Subject: GTK or TKinter (or what else?) References: Message-ID: <10apcbongdh7gc3@corp.supernews.com> In article ,

wrote: >Marco Terzuoli wrote: >> Hi, >> I use python under linux and would like to create some GUI applications. I >> have seen that Python can be used together woth some different graphic >> libraries and would like to have a suggestion about which one to use. >> I feel like GTK is better documented bud would not like to create programs >> which are not fully portable. Moreover, I know you can use wxWindows as >> well... I have tried it in my C program and didn't like the way events were >> handled. Are there any differences in Python? >> Thanks >> Marco > >I would definitely recommend GTK. >It has huge support being it now >and it's supported on windows now also. >I've some example apps here: >http://www.pixelbeat.org/talks/pygtk/ > >P?draig. I've seen two follow-ups so far, one each expressing enthusiasm for PyGTK and PyQt. I know that still other experienced developers favor wxPython, and Tkinter, and ... I recommend to Mr. Terzuoli that he detail his question even more precisely; I recommend to those advising him that they contribute to the Wikis at and . These questions come up soooooo often. -- Cameron Laird Business: http://www.Phaseit.net From fredrik at pythonware.com Wed May 26 16:25:40 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 22:25:40 +0200 Subject: Changing file names References: Message-ID: Thomas Philips wrote: > The function glob in module glob will give me a list of all the > subdirectories, and by looping over this list and repeatedly calling > glob, I can create lists of files within each directory, which are > easily edited to create lists of new filenames. > > How then can I change the existing filenames to these new filenames? > What python functions should I be using, and what modules are they > contained in? os.rename(oldname, newname) found under "files and directories" in the library reference: http://docs.python.org/lib/os-file-dir.html From me at privacy.net Thu May 20 11:41:03 2004 From: me at privacy.net (Duncan Booth) Date: 20 May 2004 15:41:03 GMT Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: Roy Smith wrote in news:roy- 66AA16.10525820052004 at reader2.panix.com: > Just in the last few days has yet another one > called Pythong been mentioned, although details are still a bit sketchy > on that :-) Pythong with braces. What a mental image. :-) From rechapman at hotmail.com Sun May 30 01:14:20 2004 From: rechapman at hotmail.com (Bob Chapman) Date: Sun, 30 May 2004 00:14:20 -0500 Subject: pywin32 201.1 Windows98SE Problem? References: Message-ID: "Peter Hansen" wrote in message news:U42dnSBf9v3jqiTdRVn-hg at powergate.ca... > Bob Chapman wrote: > > > On two different Windows 98SE Systems, I have attempted to upgrade working > [...] > > >__import_pywin32_system_module__ > > > raise ImportError, "Can not locate " + filename > > >exceptions.ImportError: Can not locate pywintypes23.dll > > > > On checking, the NEW 'pywintypes23.dll' IS in c:\windows\system > > > > > 77824 May 28 11:10 c:\windows\system\pywintypes23.dll > > > > If this file is copied to C:\Windows then Pythonwin starts without the error > > messages and appears to work. > > What happens if you run Python from the command line and type > "import pywintypes"? In other words, is this a problem with > the Python installation or a problem with the pywin32 installation? > You should learn the answer as a result... > > -Peter Thanks for the suggestion. Will try tomorrow when I have access to one of the two systems. -- From guy.flowers at Machineworks.com Mon May 17 06:12:32 2004 From: guy.flowers at Machineworks.com (Guy) Date: 17 May 2004 03:12:32 -0700 Subject: readline timeout, or end char or something. Message-ID: Ok this is might take some exsplaining as this is just example code, I have a telnet server which I've created, its ment to be a a process queue control thing. One of the things I think that would be really useful is to be able to use the server as a sort of cmd prompt remote control. I use the same sort of code below I can write a cmd to the popen2 cmd but when reading them it reads but then hangs on the readline there isn't a end of output char, the only way to stop the hanging is to exit the process What I need is a timeout or something, any help would be good. The first example won't work, it hangs, but it is what I want to do. The second example works but its not what I want to do. I saw a couple of things when I search for a timeout, none of which I found to work, select which I use sometimes won't work with this, and the normal blank output which usally works won't. Example 1 - This what I want to do keep the input open but read the output without it hanging. from popen2 import popen2 output, input = popen2("cmd.exe") input.write("dir\n") while 1: outline = output.readline() if (outline!=""): print outline else: break self.input.write("dir\n") while 1: outline = output.readline() if (outline!=""): print outline else: break self.input.write("exit\n") Example 2 - Not what I want to do, but this won't hang. from popen2 import popen2 output, input = popen2("cmd.exe") input.write("dir\n") input.write("exit\n") while 1: outline = output.readline() if (outline!=""): print outline else: break TIA Guy From babs at sntteam.org Wed May 26 08:05:24 2004 From: babs at sntteam.org (BaBS) Date: Wed, 26 May 2004 14:05:24 +0200 Subject: Bad interpreter References: Message-ID: Le Wed, 26 May 2004 07:51:42 -0400, Peter Hansen a ?crit?: > It's either that or /usr/bin/python2.3 doesn't really exist. > If you type "/usr/bin/python2.3" at the prompt, does the > interpreter come up properly? If it does, try creating a > new file without using an editor. Type the commands below > at the Linux $ prompt: > > $ cat >test.py > #!/usr/bin/python2.2 > print 'works' > (hit Ctrl-D here to close the file) > $ chmod +x test.py > $ ./test.py > works > > If you don't get the final output, but still get the "bad > interpreter" thing, yet if the interpreter works properly > when you execute it directly, then I have no idea and will > be quite interested to learn the final solution. > > -Peter /usr/bin/python2.3 exists, it starts perfectly, when i use a alias mysoft="/usr/bin/python2.3 /path/to/my_script" it works perfectly too ... i got a small script ... it's work perfectly too ... with the chmod +x and the ./script ... I'm lost, i've no idea :) -- Damien ++ I've lost my mind ... But it's on a backup tape ... ... somewhere ... From moughanj at tcd.ie Thu May 20 02:26:38 2004 From: moughanj at tcd.ie (James Moughan) Date: 19 May 2004 23:26:38 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> Message-ID: <16752bcc.0405192226.27b4a93b@posting.google.com> > >David MacQuigg wrote in message news:... > >> On Mon, 17 May 2004 16:40:00 +1200, Greg Ewing > >> wrote: > >> > >> >David MacQuigg wrote: > >> >> James has been telling me it is terribly wrong to keep data as > >> >> attributes of classes > >> > > [snip] > >> > >> This makes a lot more sense than a total ban on data in classes. > >> > > > >Just to clarify, once again - I was not suggesting a ban on data in > >classes - I was objecting to the specific way in which the data was > >being passed around and used in the class heirarchy. > > You have some good ideas, but you have been making extreme statements > and over-generalizing. > """ > 5/17/04: > OK: "The whole idea of having these structures in any program is > wrong." > > Firstly, the program uses a class hierarchy as a data structure. That > isn't what class heirarchies are designed for, and not how they should > be used IMO. But it's what any bright student will pick up from the > example. > """ > > We could avoid a lot of non-productive discussion if you were more > careful with these statements. Instead of the above, you could say: > """ > Generally, its not a good idea to store *changeable* data in the class > itself. The Animals_2 program has variables like _numAnimals, which > change when any instances of subclasses are created. If this were a > much bigger program with hundreds of classes being implemented by many > different programmers, one of those programmers might forget to add a > call to the parent's __init__, and all counts of classes above the new > class would be wrong. > """ This wouldn't quite be my position, though. It doesn't hurt to have changable data in a class; it's a question of what happens when you loose the locality of that data, especially in terms of debugging effort. Quite likely I have not always communicated myself to you perfectly. I see how someone could ignore the word heirarchy in the above quote and loose most of the meaning, which was that data should generally not be distributed throughout the class heirarchy as if it were a data structure. However, I had thought by now that I had made it clear that I do not regard it as "terribly wrong to keep data as attributes of classes"; 2004-05-10: "...you should think carefully before using classes to store data" "2004-05-10": "we want to keep the data stored in each class local to that class. So, Mammal can store the number of Mammals, if that turns out to be a good solution..." So I am not sure why you would misrepresent my position so thoroughly. > > Then we could have a productive discussion on whether, in this case, > _numAnimals is OK. I would argue yes, but I understand your point > about the possibility of new, incorrectly written classes causing a > problem. > > The reasons I would argue yes are: > 1) This is a very simple hierarchy, even if it grows to a hundred > classes. > 2) The incrementing of the _num... variables is a simple and standard > part of every __init__ in this hierarchy. A programmer who would > ignore that, is a programmer who would completely mess up modification > of a more complex program involving automatic generation of classes. > 3) This is not a database or transaction processing system that needs > to stay online for days at a time, and is vulnerable to out-of-sync > problems arising from interupted sessions, etc. > 4) This is an example for students who are new to OOP. I would rather > keep the example simple, and point out how it might be improved, than > burden the students with all the details of a production-quality > program. > And I would have argued no; 1) I'm not sure why this example is simpler than any other singly-inherited heirarchy. IMO the way it works makes it more complex than most I've seen. 2) If there's one thing you can rely on, it's people making mistakes, especially the simple ones. Making a program easy to debug in the face of simple mistakes is IMO an extremely good idea. 3) That's not especially relevant to what I've been talking about, that is, programmer error and debugging. 4) Whatever you teach students the first time round takes a long, long time to leave their heads, if it ever does. Picking practically and theoretically sound examples would not be hard. These do not have to be complex at all, just simple examples of typical uses of class heirarchies. > I've made your program, Animals_JM.py at > http://ece.arizona.edu/~edatools/Python/Exercises/ the next example > *after* Animals_2. The topic of techniques to make a program robust > and maintainable is worth a whole chapter, but it would be a > distraction in the introductory chapter. > > I would still like to see a way to gain the benefits of both Animals_2 > and Animals_JM in one program. My attempts to follow up on > suggestions in this discussion have only added complexity, not > improved the program. > > -- Dave Simple method - choose a different example. However, you do not appear to be open to this suggestion. From nid_oizo at yahoo.com_remove_the_ Fri May 14 14:47:06 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 14 May 2004 14:47:06 -0400 Subject: Pickling array.array In-Reply-To: References: <3p5pc.78949$FH5.1782405@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > For those interested in the same problem, the only solution I've found > is to encapsulate the array instead of derive from it. It sucks a bit, > since all methods need to be implemented to redirect to array.array, but > at least it's working. I'm still wondering how to do it with derivation... Here's a complete solution (if anyone knows a simpler solution...): import array as arr class array: def __init__(self, typecode, initializer=None): self.arr = arr.array(typecode, initializer) def __getstate__(self): return {'buffer': self.arr.tostring(), 'typecode': self.arr.typecode} def __setstate__(self, dict): self.arr = arr.array(dict['typecode']) self.arr.fromstring(dict['buffer']) def __getattr__(self, name): if name == 'arr': return self.arr return self.arr.__getattribute__(name) def __setattr__(self, name, value): if name == 'arr': self.__dict__['arr'] = value else: self.arr.__setattr__(name, value) From do at linux.darktower.net Sun May 2 10:03:48 2004 From: do at linux.darktower.net (Dominique Orban) Date: Sun, 02 May 2004 14:03:48 GMT Subject: silent raw_input for passwords References: Message-ID: On 2004-05-01, Dan Bishop wrote: > Stephen Boulet wrote in message news:... >> I need a password for a script and I would like to not have it stored in a >> file or shown in a terminal. >> >> "passphrase = raw_input()" still lets you see the input on the screen. Is >> there a way to have it be hidden? It's my gpg passphrase, so I don't want >> it anywhere except in my head. > > There's probably an easier way, but you can use: > > def input_password(echo=True): > chars = [] > while True: > newChar = getch() > if newChar in '\r\n': > break > elif newChar in '\b\x7F': > if chars: > del chars[-1] > sys.stdout.write('\b') > else: > chars.append(newChar) > if echo: > sys.stdout.write('*') > return ''.join(chars) How is this different from getpass.getpass() ? From peufeu at free.fr Thu May 27 14:07:23 2004 From: peufeu at free.fr (PF) Date: Thu, 27 May 2004 20:07:23 +0200 Subject: Server/OS/Dev environment References: Message-ID: I have started with SkunkWeb and it's incredibly powerful. The template language is great, it has a lot of useful modules, and it doesn't get in the way when I want to use other packages. The way it cuts things in components and modules makes it really easy to reuse your code bits. Plus, it's very very fast. My PC generates 200 KB of html in about 60 milliseconds, all of it being dynamic. On the downside, documentation is scarce, but what there is is well done. Zope is impossible to use. MySQL kinda sucks. No transactions... what can you do with a database with no transactions... no foreign keys... no integrity constraints... no "insert or update"... it has AMATEUR written all over it... I like postgresql much better. plsql sucks but stored procedures are faster than making a pile of requests. Anyway, have fun ! From duncan at enthought.com Mon May 3 18:41:34 2004 From: duncan at enthought.com (duncan) Date: Mon, 3 May 2004 17:41:34 -0500 Subject: Strategies for backwards compatibility when using pickle? Message-ID: <001401c4315f$c9632a70$9601a8c0@rimmer> I am working on an application that currently uses a simple pickle to save a project to disk. Every time we make a significant change to our object model we tell our beta users to delete all of their old projects. Does anyone have any advice on how to balance the conflicting interests of the developers who want to keep evolving the object model and users who need stable project persistance? It has been suggested that there may be a way to override pickle to deal with an evolving object model but it would be nice to hear from others who have tried to handle this problem. Thanks Duncan From kpdere2968 at mcihispeed.net Wed May 12 14:40:03 2004 From: kpdere2968 at mcihispeed.net (Ken Dere) Date: Wed, 12 May 2004 14:40:03 -0400 Subject: problem running wxPython demo.py Message-ID: I am running Suse 9.0 with python 2.3-52 and python-wxGTK 2.4.1.2-43. Everything has been installed from the CD distribution and should work together. when trying to run the demo, I get: ken at linux1:/usr/share/doc/packages/python-wxGTK/demo> python demo.py Traceback (most recent call last): File "demo.py", line 3, in ? import Main File "/usr/share/doc/packages/python-wxGTK/demo/Main.py", line 16, in ? import wx # This module uses the new wx namespace File "/usr/lib/python2.3/site-packages/wx/__init__.py", line 45, in ? from wxPython import wx File "/usr/lib/python2.3/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: /usr/lib/python2.3/site-packages/wxPython/wxc.so: symbol _ZNK8wxRegion15ConvertToBitmapEv, version WXGTK_2.4 not defined in file libwx_gtk-2.4.so.0 with link time reference looking through google groups has turned up anything similar. any help is appreciated. Ken -- Ken D. From Chris.Hornberger at blackrock.com Wed May 12 13:03:35 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 13:03:35 -0400 Subject: zlib and gzip Message-ID: Silly questions first: Is it just a matter of 72 column-bounding to make it email-compliant? (keep in mind I haven't run your sample code yet, I'm sitting here perusing while on a conference call - meetings suck!!!) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Greg Bakken Sent: Wednesday, May 12, 2004 12:57 PM To: python-list at python.org Subject: zlib and gzip I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg -- http://mail.python.org/mailman/listinfo/python-list From aweil at mail.ru Tue May 11 23:26:36 2004 From: aweil at mail.ru (alejandro david weil) Date: Wed, 12 May 2004 00:26:36 -0300 Subject: Problem with module variables / module deallocation . . . Message-ID: <200405120026.36923.aweil@mail.ru> Hello! I got the next problem and didn't see any reference to the behaviour that produces it, look: If we have a module like: --- mod.py --------------->8------ testvar2 = 15 def testfunc(): print testvar2 --- mod.py --------------->8------ And if we make: --- test1.py --------------->8------ import sys import mod f = mod.testfunc f() del mod del sys.modules['mod'] print 'after module dereferencing..' f() --- test1.py --------------->8------ or : --- test2.py --------------->8------ import sys def testloco(): import mod return mod.testfunc f = testloco() f() del sys.modules['mod'] print 'after module dereferencing..' f() --- test2.py --------------->8------ The last f() prints None. YES, i know, that usually you are not removing imports you made. I'm getting that problem when using pyhton's encodings/codecs modules. C codecs module, keeps a reference to a function in encodings pakage called search_function, and after getting that function, the module is auto deallocated (except from sys.modules). The application where we are using it, embeeds python and after my module ends, it "cleans up" sys.modules dictionary (not in a clean way it seems), and I can't continue using encodings later, because, when I make 'something'.encode('some encoding'), it searchs using that registered search function that has problems accessing (invalid) data. The problem is like this: --- enc_test.py --------------->8------ import sys def testencoding(): status = name in sys.modules.keys() print 'is encodings loaded? ', status return status def get_sf(): import encodings return encodings.search_function f = get_sf() del sys.modules['encodings'] #this line is articial, but.. print 'after module dereferencing..' 'bye'.encode('chau') --- enc_test.py --------------->8------ One way to workaround this problem is that codecs keeps a reference to encodings module. There's no way that the function keeps a reference to the module, to prevent the module's variable destruction? Well. That's all. david PS: Is this the right mailing list for this kind of posts? -- + There is no dark side of the moon really. Matter of fact it's all dark. From pegges at boulder.net Sun May 30 16:51:55 2004 From: pegges at boulder.net (tallpaul) Date: Sun, 30 May 2004 14:51:55 -0600 Subject: dbi.operation-error: blank in LOGIN Message-ID: <0K6dnU9Ws9n81CfdRVn-hw@csd.net> I'm trying to run the following on an xp box. import dbi, odbc try: s = odbc.odbc('DSN/username/userpassword') cur = s.cursor() cur.execute('select * from tablename') print cur.description for tup in cur.description: print tup[0], print while 1: rec = cur.fetchmany(10) if not rec: break print rec except NameError,e: print 'error ', e, 'undefined' Which comes back with the error message dbi.operation-error: blank in LOGIN Any suggestions would be greatly appreciated. p From ahaas at airmail.net Wed May 26 15:07:06 2004 From: ahaas at airmail.net (Art Haas) Date: Wed, 26 May 2004 14:07:06 -0500 Subject: ANNOUNCE: Fourteenth releaes of PythonCAD now available Message-ID: <20040526190706.GV2632@artsapartment.org> I'm pleased to announce the fourteenth 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 Python 2.3. 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 interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The fourteenth release builds on the undo/redo work added in the previous release. The undo/redo abilities of the program in regards to entity addition and removal have been made more significantly more robust. Also, the ability to undo or redo entity splitting, moving, mirroring have been both added and enhanced. The ability to undo or redo entity transfers between image layers is now available. Changing the various entity properties now has more undo and redo features. Future releases will continue to enhance and extend the undo and redo functions in PythonCAD. A number of significant bugs have been resolved in this release as well. A file save bug unfortunately introduced in the previous release is fixed. Drawing tangent lines around circle and arc entities had several bugs that have now been fixed, and a problem with storing and retrieving the angled construction lines in the drawing have been address. Numerous other smaller bugs are also fixed in this release, as well as various code enhancements that have been added. The 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 daniel.dittmar at sap.com Tue May 11 10:35:16 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 11 May 2004 16:35:16 +0200 Subject: General Ledger/Accounting Libraries References: Message-ID: Andreas Pauley wrote: > Our company is currently evaluating Python as a language for writing > financial/accounting type software (among others). > > What libraries or packages are available in this domain for use? There's GNU Enterprise (http://www.gnuenterprise.org/). Daniel From ajsiegel at optonline.com Fri May 21 21:07:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 22 May 2004 01:07:05 GMT Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> Message-ID: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> On Fri, 21 May 2004 13:30:23 -0700, Shalabh Chaturvedi wrote: >I believe it is conceptual homogeneity and not type homogeneity that >characterises the difference between lists and tuples. "conceptual homogeneneity" defined - as far as I see it - by reference to whether a rational Python programmer would group the objects together in a list. A perfect tautology. Which always seems to me to create more confusion, than clarification. Art From marklists at mceahern.com Thu May 27 09:21:48 2004 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 27 May 2004 08:21:48 -0500 Subject: How to list all functions in an imported module? In-Reply-To: <889cbba0.0405270506.3cd91d26@posting.google.com> References: <889cbba0.0405270506.3cd91d26@posting.google.com> Message-ID: <1085664108.16940.56.camel@dev.internal> On Thu, 2004-05-27 at 08:06, Kamilche wrote: > I can't figure out how to list all functions from an imported module. > I searched Google, but all the answers I found didn't work. Did > something change in Python 2.2, perhaps there's a new method of doing > it? Try the inspect module. // m From bluczkie at andrew.cmu.edu Tue May 11 13:26:48 2004 From: bluczkie at andrew.cmu.edu (Brian L.) Date: 11 May 2004 10:26:48 -0700 Subject: Ideas about optional filter on for loop statements Message-ID: After following the discussion on Generator expressions on python-dev for the last few weeks, and finally getting used to list comprehensions as opposed to map/filter, it occurred to me that the for loop statement lacks the filtering feature when compared to the listcomp/genexp. For instance, (real code) for x in range(10): if x%2 is 0: print x Could be reduced to: (fake code) for x in range(10) if x%2 is 0: print x Which is comparable to iterating and printing the elements of the listcomp: [x for x in range(10) if x%2 is 0] or the genexp: (this syntax isn't real yet, but I'd imagine this to be fairly accurate based on python-dev) (x for x in range(10) if x%2 is 0) Note the perfect consistency between all three iterator usages. This change would not break any compatibility that I can think of, but would improve self-consistency within python. Furthermore, if listcomps and genexps are a direction that python is moving in, then it would probably make sense that the for loop statement has an optional filtering clause as well. The strongest argument I can think of against it is that for loop statements should be reserved for iteration only, and that they shouldn't have functional features (for instance, the for loop can not and will not ever have 'map' like semantics, so why should it have filter?). I don't think, however that this is a problem, and considering the number of times that I've written loops in the following patterns: for x in l: if x is None: continue ... or for x in l: if x is not None: ... I think that a more pythonic syntax may be in order. for x in l if x is not None: ... is certainly cleaner and easier to read. This clause should of course be optional Thoughts? If this receives enough positive attention on comp.lang.python, then I'll write it up and submit a PEP. Brian From dd55 at cornell.edu Mon May 3 09:27:09 2004 From: dd55 at cornell.edu (Darren Dale) Date: Mon, 3 May 2004 09:27:09 -0400 Subject: changing directories from within the shell Message-ID: I am sure this has been covered in the documentation, but I havent found it. Could anyone tell me how to change directories from within the python shell? Thanks From matthewleslie at hotmail.com Thu May 13 17:57:31 2004 From: matthewleslie at hotmail.com (Matt Leslie) Date: Thu, 13 May 2004 16:57:31 -0500 Subject: Stackless python and microthreads Message-ID: Hi, I'm trying to use microthreads under stackless python, since they sound like exactly what I am after, but I am having very little success. I've got a fresh install of python 2.3.3 from python.org, then downloaded the binary python2.3 release of stackless python from www.stackless.com. This contained three files: python23.dll, python23.lib, python23.exp I searched for the original versions of these files, and copied: stackless python23.dll over c:\winnt\system32\python23.dll stackless python23.lib over C:\Program Files\python2.3\libs\python23.lib Since I believe .exp files are associated with .lib files. I put the .exp file in the same place as the lib. There was no existing file with this name on my file system. I then downloaded the microthreads package from http://willware.net:8080/uthread.py I then ran python, type 'import uthread' and immediately got the following error. --------------------------------------- Python 2.3.3 Stackless 3.0 040407 (#51, Apr 7 2004, 19:28:46) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import uthread.py Traceback (most recent call last): File "", line 1, in ? File "uthread.py", line 35, in ? import continuation, sys, traceback, bisect, time, StringIO ImportError: No module named continuation Has anyone run into this before? Can someone tell me where to find this continuation module? Thanks, Matt From JBrouwers at ProphICy.com Wed May 12 16:14:48 2004 From: JBrouwers at ProphICy.com (Jean Brouwers) Date: Wed, 12 May 2004 13:14:48 -0700 Subject: __slots__ vs __dict__ Message-ID: <120520041314481389%JBrouwers@ProphICy.com> Classes using __slots__ seem to be quite a bit smaller and faster to instantiate than regular Python classes using __dict__. Below are the results for the __slots__ and __dict__ version of a specific class with 16 attributes. Each line in the tables shows the number of instances created so far, the total memory usage in Bytes, the CPU time in secs, the average size per instance in Bytes and the average CPU time per instance in micseconds. Instances of this particular class with __slots__ are almost 6x smaller and nearly 3x faster to create than intances of the __dict__ version. Results for other classes will vary, obviously. Comments? /Jean Brouwers ProphICy Semiconductor, Inc. PS) The tests were run on a dual 2.4 GHz Xeon system with RedHat 8.0 and Python 2.3.2. The test script is attached but keep in mind that it only has been tested on Linux. It will not work elsewhere due to the implementation of the memory() function. testing __slots__ version ... 4096 insts so far: 3.0e+05 B 0.030 sec 73.0 B/i 7.3 usec/i 8192 insts so far: 8.8e+05 B 0.070 sec 107.5 B/i 8.5 usec/i 16384 insts so far: 1.5e+06 B 0.150 sec 92.2 B/i 9.2 usec/i 32768 insts so far: 3.3e+06 B 0.280 sec 101.0 B/i 8.5 usec/i 65536 insts so far: 6.6e+06 B 0.560 sec 101.2 B/i 8.5 usec/i 131072 insts so far: 1.4e+07 B 1.200 sec 103.4 B/i 9.2 usec/i 262144 insts so far: 2.7e+07 B 2.480 sec 103.4 B/i 9.5 usec/i 524288 insts so far: 5.5e+07 B 5.630 sec 104.0 B/i 10.7 usec/i 1048576 insts so far: 1.1e+08 B 13.980 sec 104.0 B/i 13.3 usec/i 1050000 insts total: 1.1e+08 B 14.000 sec 103.9 B/i 13.3 usec/i testing __dict__ version ... 4096 insts so far: 2.4e+06 B 0.050 sec 595.0 B/i 12.2 usec/i 8192 insts so far: 4.6e+06 B 0.090 sec 564.5 B/i 11.0 usec/i 16384 insts so far: 9.5e+06 B 0.180 sec 581.8 B/i 11.0 usec/i 32768 insts so far: 1.9e+07 B 0.370 sec 582.2 B/i 11.3 usec/i 65536 insts so far: 3.8e+07 B 0.830 sec 582.6 B/i 12.7 usec/i 131072 insts so far: 7.6e+07 B 1.760 sec 582.7 B/i 13.4 usec/i 262144 insts so far: 1.5e+08 B 4.510 sec 582.8 B/i 17.2 usec/i 524288 insts so far: 3.1e+08 B 12.820 sec 582.8 B/i 24.5 usec/i 1048576 insts so far: 6.1e+08 B 38.370 sec 583.1 B/i 36.6 usec/i 1050000 insts total: 6.1e+08 B 38.380 sec 583.1 B/i 36.6 usec/i -------------------------------slots.py-------------------------------


from time import clock as time_clock
def cputime(since=0.0):
    '''Return CPU in secs.
    '''
    return time_clock() - since


import os
_proc_status = '/proc/%d/status' % os.getpid()  # Linux only
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
          'KB': 1024.0, 'MB': 1024.0*1024.0}

def _VmB(VmKey):
    global _scale
    try: # get the /proc//status pseudo file
        t = open(_proc_status)
        v = [v for v in t.readlines() if v.startswith(VmKey)]
        t.close()
         # convert Vm value to bytes
        if len(v) == 1:
           t = v[0].split()  # e.g. 'VmRSS:  9999  kB'
           if len(t) == 3:  ## and t[0] == VmKey:
               return float(t[1]) * _scale.get(t[2], 0.0)
    except:
        pass
    return 0.0

def memory(since=0.0):
    '''Return process memory usage in bytes.
    '''
    return _VmB('VmSize:') - since

def stacksize(since=0.0):
    '''Return process stack size in bytes.
    '''
    return _VmB('VmStk:') - since



def slots(**kwds):
    '''Return the slots names as sequence.
    '''
    return tuple(kwds.keys())

 # __slots__ version
class SlotsClass(object):
    __slots__ = slots(_attr1= False,
                      _attr2= None,
                      _attr3= None,
                      _attr4= None,
                      _attr5= None,
                      _attr6= None,
                      _attr7= 0,
                      _attr8= None,
                      _attr9= None,
                      _attr10=None,
                      _attr11=None,
                      _attr12=None,
                      _attr13=None,
                      _attr14=None,
                      _attr15=None,
                      _attr16=None)

    def __init__(self, tuple4, parent):
        self._attr1 = False
        self._attr2 = None
        self._attr3 = None
        self._attr4 = None
        self._attr5 = None
        self._attr6 = None
        if parent:
            self._attr7  = parent._attr7 + 1
            self._attr8  = parent._attr8
            self._attr9  = parent._attr9
            self._attr10 = parent
            self._attr11 = parent._attr11
            self._attr12 = parent._attr12
        else:
            self._attr7  = 0
            self._attr8  = None
            self._attr9  = None
            self._attr10 = None
            self._attr11 = self
            self._attr12 = None
        self._attr13, self._attr14, self._attr15, self._attr16 = tuple4


 # __dict__ version
class DictClass(object):
    _attr1 = None
    _attr2 = None
    _attr3 = None
    _attr4 = None
    _attr5 = None
    _attr6 = None
    _attr7  = 0 
    _attr8  = None
    _attr9  = None
    _attr10 = None
    _attr11 = None
    _attr12 = None
    _attr13 = None
    _attr14 = None
    _attr15 = None
    _attr16 = None

    def __init__(self, tuple4, parent):
        if parent:
            self._attr7  = parent._attr7 + 1
            self._attr8  = parent._attr8
            self._attr9  = parent._attr9
            self._attr10 = parent
            self._attr11 = parent._attr11
            self._attr12 = parent._attr12
        else:
            self._attr11 = self
        self._attr13, self._attr14, self._attr15, self._attr16 = tuple4


if __name__ == '__main__':

    import sys

    def report(txt, n, b0, c0):
        c = cputime(c0);
        b = memory(b0)
        print "%8d insts %s: %8.1e B %7.3f sec %6.1f B/i %6.1f usec/i" \
               % (n, txt, b, c, b/n, 1.0e6*c/n)

    if not sys.platform.startswith('linux'):
        raise NotImplementedError, "%r not supported" % sys.platform

    if 'dict' in sys.argv[1:]:
        print 'testing __dict__ version ...'
        testClass = DictClass
    else:
        print 'testing __slots__ version ...'
        testClass = SlotsClass

    t4 = ('', 0, 0, [])
    b0 = memory()
    c0 = cputime()
    p = testClass(t4, None)
    n, m = 1, 4096
     # generate 1+ M instances
    while n < 1050000:  # 1048576:
        p = testClass(t4, p)
        n += 1
        if n >= m:  # occasionally print stats
            m += m
            report('so far', n, b0, c0)
    report(' total', n, b0, c0)

From noemail at noemail4u.com Wed May 19 09:06:50 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Wed, 19 May 2004 13:06:50 GMT Subject: unique number generator References: Message-ID: <5da2b26991d290ff30a502d392812f4b@news.teranews.com> On Wed, 19 May 2004 18:36:40 +0800, "Joe Wong" wrote: > I need to implement a unique number generator that 1 or more processes on same or different machines will make use of it. Is there any library / project available already for this? Yes. Google for GUID (globally unique identifier) algorithm or UUID (universally unique algorithm): "http://www.google.com/search?q=GUID+algorithm", "http://www.google.com/search?q=UUID+algorithm". If you need to use one, instead of implement one, and you're running on Windows machines with Mark Hammond's win32 extensions, you can do it easily: import pywintypes guid = pywintypes.CreateGuid() have_a_nice_day(guid) --dang From deetsNOSPAM at web.de Wed May 5 17:04:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 05 May 2004 23:04:08 +0200 Subject: Bit torrent swap space via python References: <79ad5955.0405051156.20d2e1b@posting.google.com> Message-ID: Julia Goolia wrote: > My question is... is there a class or function to open a file which > will not do any buffering in the swap space? Nope - thats a system thingy. applications request memory, and get it - if there isn't enough physical, the swapspace grows. It might be possible for kernel level code to prevent the memory beenig swappable, but that clearly is beyond pythons capabilities. -- Regards, Diez B. Roggisch From me at privacy.net Thu May 6 13:05:18 2004 From: me at privacy.net (Alejandro =?iso-8859-1?Q?L=F3pez-Valencia?=) Date: 6 May 2004 17:05:18 GMT Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <40992866$0$12738$636a15ce@news.free.fr> <2fuqv0F2ig0mU1@uni-berlin.de> Message-ID: <2fv9idF2p2lfU1@uni-berlin.de> On 2004-05-06, Brian Quinlan wrote in : >> If you are starting with a file that already contains tabs *and* spaces, >> I'd say you have already called upon you the gods of disaster. > > [snipped] > > But I haven't. I did what you suggested, opened a file using ONLY tabs > for indentation and VIM stilled inserted spaces when it pressed the tab yet. > Because that's what it is supposed to do. If you want to edit a tab indented file, you make sure that expandtab is set (it is in the example I gave) and type the ex command ':h retab! 4', assuming your file was created with a hardware tab setting (ts) of 4. Now, your file uses only spaces and indention settings will work. There are other alternatives to what you want to do, type the ex command ":h 'tabstop'" in a Vim session and you'll get the whole story. As far as I know, only X/Emacs with python-mode.el has the kind of mind-reading you want. And still you'll have to hand-hold it a bit. I would suggest you explore JEdit and Jext. Both are Java-based editors and at least Jext has an embedded Jython interpreter (there, desperately trying to keep this post on topic ;-). Perhaps these editors already know how to do what you want.i I don't know them well enough to say anything about them. > >> Then you experience of the world is very limited :-) I am aware of only >> some very expensive commercial editors/IDEs that can do such thing in a >> general way. > > Like PythonWin (free) or Eric3 (free)? I did say "general way", didn't I? As in the way you can setup Visual SlickEdit or CodeWright to do it for you. Hmm... I shouldn't have deleted the words "dedicated IDEs" when writing that paragraph, as that covers idle, PythonWin, Eric, and a few other editors (written in Python + some GUI API, and using tabnanny.py or tokenizer.py behind the scenes). Cheers, Alejo -- Alejandro L?pez-Valencia qenqhy ng rgo qbg arg qbg pb http://dradul.tripod.com/ The limits of my language are the limits of my world. (L. Wittgenstein) From __peter__ at web.de Fri May 7 04:39:57 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 May 2004 10:39:57 +0200 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: Larry Bates wrote: > I use type() quite a lot. I poked around and couldn't > find where it was being deprecated. I did see that > types module is slated for deprecation. Maybe I > overlooked it? > > I use: > > class foo: > _stringtype=type('') > _tupletype=type(()) > _listtype=type([]) > > def __init__(self, variable): > if type(variable) == _stringtype: > self.variable=variable # check for string type > if type(variable) in (_listtype, tupletype): > self.variable=str(variable) # check for list/tuple I would change that to def __init__(self, v): self.variable = str(v) The fact that str() is a function hides what is really going on, so I'll make it explicit: def __init__(self, v): self.variable = v.__str__() In general everything that differs from class to class should be delegated to the class that needs the special behaviour. Of course for classes that aren't under your control it may sometimes be more practical to special-case them with isinstance() checks than to subclass. Peter From jaepstein_63 at yahoo.com Tue May 11 15:30:22 2004 From: jaepstein_63 at yahoo.com (Jonathan Epstein) Date: 11 May 2004 12:30:22 -0700 Subject: scraping display to obtain all on-screen text using OCR Message-ID: <27e4d2e8.0405111130.7081968e@posting.google.com> I would like to perform a more classical type of "screen scraping" than what most people now associate with this term. I only want to find all the text on the current screen, and obtain associated screen coordinates. This probably must be done using OCR. This need only run on Windows. A fairly-pure Python solution would be ideal because most of the software which would use this functionality is also written in Python. The ideal output would consist of a list of tuples, where each tuple consists of ("string found", a, b, c, d) where the latter four constitute a bounding rectangle associated with the text that was found. It might also be handy to throw in some font information. Thanks in advance for any pointers. Jonathan From bart_nessux at hotmail.com Thu May 20 11:47:59 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 20 May 2004 11:47:59 -0400 Subject: Documentation/Info on this sign In-Reply-To: <7p4rc.33428$hH.684873@bgtnsc04-news.ops.worldnet.att.net> References: <7p4rc.33428$hH.684873@bgtnsc04-news.ops.worldnet.att.net> Message-ID: wes weston wrote: > Bart Nessux wrote: > >> Could someone point me to documentation on this (and similar) signs >> used in Python: >> >> += >> >> Usage would be: >> >> x = += len(y) >> >> Literally, that's "variable x equals >> 'funky-symbol-that-I-want-to-learn-about' the length of variable y" >> >> Thank you, >> >> Bart > > > Bart, see http://docs.python.org/ref/augassign.html > wes > Thanks Wes! From jcarlson at uci.edu Thu May 20 01:12:32 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 19 May 2004 22:12:32 -0700 Subject: Scope rule pecularities In-Reply-To: References: Message-ID: >>As you mentioned later, in C, you can use *a = 1 to modify a single >>instance of 'a'. However, immutables in Python never do the *a = 1 >>assignment. Mutables do so, > > I am not sure what you mean to say that mutables 'do the *a=1 assignment'. > This does not strike me as a useful viewpoint for understanding Python. If you read Antoon's post, he mentions that in C you can have multiple integer pointers pointing to the same memory location, and changing the contents of that one memory location (*a = 1) changes the "value" of other names. As you state, since Python only ever rebinds names on assignments, the only even near equivalent would be using something like 'a[0] = 1' or even 'a.p = 1' (for some mutable mapping or settable attribute respectively), and claim that many names can all reference the same 'a'. I agree it is not terribly useful for understanding Python, unless one has background with C or C++, which seems to be the case with Antoon. >>which is why the final line of... >> m = n = [] > > At this point, m is n, not merely m == n. Both names are bound to one and > the same object. Indeed, I should have used 'is'. >>For immutables, on modification, a new instance of the immutable is >>created, the value being set accordingly. > > Since immutable objects cannot be modified, I am not sure what you are > saying. In any case, What I should have said is "On any /attempted/ mutation of an immutable via the (+-/*|&^%)= (and any other that I have forgotten, if any) operators, a new object is created with the appropriate modifications, leaving all previously bound names bound to the original immutable, but changing the binding of the current name to the new immutable. This is in stark contrast with a mutable mutation, which will modify and return the original object (via the __i***__ instance methods), leave all previously bound names bound to the mutable." [snip good example] >>Now that we've gotten to the point, __iadd__ and friends, we know we >>disagree. If you feel terribly strongly about it, post a bug report or >>feature requrest to SF. > > No, please do not burden the volunteer developers with false bug reports or > useless feature requests. The semantics of += and family were debated when > added a few years ago and will not change for the foreseeable future. Keep > repeated debate and explanation of such things to c.l.p. I had no problem with the semantics in the first place. I was just offering a place where the poster could go and get a definitive "go home, the semantics are not changing". Thank you for giving him the definitive answer here, saves someone some time on SF. >> I would venture a guess that within a week it >>will be closed with a message stating, "yeah, we like it the way it is". > > Or it might hang around a couple of years while people focus on real > problems. Sorry about that. > About dictionaries: keys must be hashable (have __hash__ method); > mutability is not directly involved (and there is indeed no direct test for > such). It would have been possible to key dictionaries by object id, and > one can do so for user classes with def __hash__(s): return id(s). But for > fairly obvious reasons, builtins are hashed and keyed by value. Perhaps > less obviously, this can be true even across types. > [snip good example] I agree, it also provides a very convenient method for looking up values in a dictionary when you no longer have access to the key originally used. My favorite example of this is... >>> a = b = 1.0 >>> a is b True >>> d = {a:'hello'} >>> b = (b + 1) - 1 >>> a is b False >>> d[b] 'hello' The problem with mutable keys for dictionaries is that the only real solution either involves keeping an 'immutable copy' of the original item for hash-by-value (which Antoon offers in another leaf of this thread), or keeping a pointer to the mutable key. The first has various issues, an the second requires that you must have the original object itself in order to access the value again, which kind of defeats one of the functional reasons for a dictionary structure. - Josiah From Chris.Barker at noaa.gov Thu May 13 14:21:30 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Thu, 13 May 2004 11:21:30 -0700 Subject: Can I use dist-utils to install a sub-package? Message-ID: <40A3BCAA.3000905@noaa.gov> HI all, I'd like to be able to use distutils to install a package within the wxPython package: wx.lib.MyPackage I want to be able to do this so folks can upgrade a package of mine that is in the wxPython library, without changing it's location. In looking through the distutils docs, it looks like I cannot specify a sub-package location for my package, It will only put it in site-packages, not site-packages.wx.lib Is there a way to do this? thanks, -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From mark at prothon.org Mon May 24 14:28:26 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 11:28:26 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: "Paul Prescod" wrote > I can understand why you might be afraid to tackle all of Unicode for > version 1.0. Don't bother. All you need to do today to avoid the dead > end is DO NOT ALLOW BINARY DATA IN STRINGS. Have a binary data type. > Have a character string type. Give them a common "prototype" if you > wish. Let them share methods. But keep them separate in your code. The > result of reading a file is a binary data string. The result of parsing > an XML file is a character string. These are as different as the bits > that represent an integer in a particular file format and a logical integer. This is very timely. I would like to resolve issues like this by July and that deadline is coming up very fast. We have had discussions on the Prothon mailing list about how to handle Unicode properly but no one pointed this out. It makes perfect sense to me. Is there any dynamic language that already does this right for us to steal from or is this new territory? I know for sure that I don't want to steal Java's streams. I remember hating them with a passion. From nhodgson at bigpond.net.au Sat May 22 18:59:28 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 22 May 2004 22:59:28 GMT Subject: SciTE editor question References: Message-ID: Brent W. Hughes: > buffers=5 > > It didn't work. You will need to restart SciTE after setting buffers for the change to take effect. Neil From michele.simionato at poste.it Sun May 16 00:41:22 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 May 2004 21:41:22 -0700 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> Message-ID: <95aa1afa.0405152041.2169cb39@posting.google.com> Valentino Volonghi aka Dialtone wrote in message news:<87oeopl44w.fsf at vercingetorix.caesar.org>... > Hi Michele :). > > If all you need is s-expr you maybe can look at Nevow (pronounced > 'nuevo'), which is the new web toolkit built on top of twisted.web. > > It has a template syntax that is similar to ZPT. > > And it has stan which is an s-expr-like syntax. > > Here is a little helloworld example: > > docFactory = rend.stan( > T.html[ > T.head[ > T.title['Hello'], > ], > T.body[ > T.p['Welcome to the wonderful world of Nevow!'], > ], > ] > ) Interesting. But I have to check which facilities it provides to manipulate s-expressions; if I was in a pervers mood, I could even generate nevow s- expressions from Scheme ;) Michele From tjreedy at udel.edu Fri May 21 14:38:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 14:38:26 -0400 Subject: Pyrex - The speed of Python with the clarity of C? References: <40AE2C4E.CE1CE6C0@shaw.ca> Message-ID: "Peter Hansen" wrote in message news:juidnTjQubr1szPd4p2dnA at powergate.ca... > SeeBelow at SeeBelow.Nut wrote: > > Am I wrong about this? Perhaps I don't understand how Pyrex works. > > Look at the primes.pyx example. There's a link just below it > (above the Language Details section) showing the C code it is > compiled to (and which is in turn compiled to machine code). True, > there are many calls to the Python/C interface APIs, but there is > also "pure" C code in there. In particular, lines 5-15 of the Python code, the 'guts' of the algorithm, are compiled to pure C with no interface calls. TJR From grante at visi.com Fri May 21 13:39:10 2004 From: grante at visi.com (Grant Edwards) Date: 21 May 2004 17:39:10 GMT Subject: terminological obscurity References: Message-ID: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> In article , Michael Chermside wrote: >> All tuple methods are also list methods, and most list methods >> are also tuple methods; among those that are NOT also tuple >> methods, there are exactly two ('count' and 'index') that do >> not involve mutation. Is there any special reason why they >> AREN'T also tuple methods? > > Yes. Both make sense only if you consider a tuple as a homogeneous > sequence of items, and that's not what Guido intended it to be > used for. I'm sure I'm being dim, but I don't understand what homogeneity has to do with it. For example, why shouldn't index() find an object in a non-homogeneous sequence? Either the object is in the sequence or it's not. If it is, there is an index that corresponds to it. The relationship (a,b,c,d,e)[3] is d is true regardless of the types of a,b,c and e. I can maybe see why not supporting sort() or reduce() on a non-homogeneous sequence makes sense if one was of the opinion that it should be illegal to use a binary operator on two objects whose types differ, but I don't see why either count() or index() should have anything to do with homogeneity, since it pretty much has to be OK to use "is" or "==" on objects of differing types. -- Grant Edwards grante Yow! Am I accompanied by at a PARENT or GUARDIAN? visi.com From opengeometry at yahoo.ca Thu May 20 01:20:26 2004 From: opengeometry at yahoo.ca (William Park) Date: 20 May 2004 05:20:26 GMT Subject: News Posting Script with Emailing Ability References: <40ac36d4$1_1@nntp2.nac.net> Message-ID: <2h2tgoF8ivgbU1@uni-berlin.de> In Jonathan M. Rose wrote: > I am looking for a script that I can sit on an HTML server (Linux, > Apache, PHP/Perl/Python/Etc.) that will allow me to do the following things: > > 1) Post news articles that consists of (i) a title and (ii) a body. Any newsreader that allows you to "postpone" posting should work here. Just create the file (using Python, for example), and let it handle posting. I use Tin. But, for posting, you can post using Telnet or script equivalent. > 2) Show the last X posts (or, better yet, just the last X titles) on a > home page. Write a script. > 3) Show all posts on a "news" page. Another script. > 4) When a news article is posted, email the news article (with the title > being the email subject and the news body being the email body) to a > single address (which will be a Mailman email list address). Use To: ... in your posting, or mail the "file" directly which should same step as posting. > 5) Preferably not require the use of a db server. > 6) Preferably allow changing or deleting news posts if errors were made > in the wording or otherwise. This is dependent on news server on individual site. Some servers honour delete and some don't (ie. Google). > 7) I do not need nor want the ability for users to "reply" to the news > articles. If you post something, then it's in the public domain. You can't control whether others reply or follow up. If you don't any followup, then don't post. > > Does anyone know of anything like this? If not, how about simple news > posting tools that I could remake to include the emailing functionality? Simple script would do. > > A tool similar to what I want is located at > http://newswriter2005.sourceforge.net/. This one, however, doesn't > allow email of news articles. > > Also - what is the proper newsgroup for asking about server-side html > scripts? alt.html.server-side would be perfect, but it seems to be dead > (at least on the news server I use). > > Thank you for your time in advance. > > -Jon -- William Park, Open Geometry Consulting, Linux solution/training/migration, Thin-client From pinard at iro.umontreal.ca Wed May 12 10:48:07 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 12 May 2004 10:48:07 -0400 Subject: getting the index while iterating through a list In-Reply-To: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> References: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> Message-ID: <20040512144807.GB24639@alcyon.progiciels-bpi.ca> [Fernando Rodr?guez] > While iterating through a list I'd like to know not just the current element, > but also its index. Is there a better way than this: > i = 0 > newList = [] > for element in aList: > newList.append((i, element)) > i += 1 > Is there a more elegant way of doing this with for? And with map()? Hi, Fernando. You may write something like: newList = [] for i, element in enumerate(aList): newList.append((i, element)) or even simpler: newList = list(enumerate(aList)) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From loic at yermat.net1.nerim.net Tue May 18 13:46:47 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Tue, 18 May 2004 19:46:47 +0200 Subject: Python compilers? In-Reply-To: <30260531.0405180848.42e2919d@posting.google.com> References: <30260531.0405180848.42e2919d@posting.google.com> Message-ID: simo a ?crit : [...] > I thought Pyrex was a hybrid of C and Python (like Jython/Java) not > actually a Python-to-C convertor? And Pysco is just a different VM > isn't it? Pyrex is python plus access to C structures and type declarations. But then the current implementation create intermediary C files. Psyco is not a different VM, it's like the JIT of java. It's a Just In Time compilers, ie it runs over the CPythonVM. > [...] -- Yermat From grante at visi.com Sat May 15 13:23:00 2004 From: grante at visi.com (Grant Edwards) Date: 15 May 2004 17:23:00 GMT Subject: book on wxPython? References: <40a5a851$0$8512$a18e6209@newsreader.visi.com> Message-ID: <40a651f4$0$17265$a1866201@newsreader.visi.com> In article , Roger Binns wrote: > Ok, now add printing, drag and drop and comboboxes. No thanks. I don't do printing or drag and drop. Or comboboxes now that I think about it. My needs are fairly simple, and Tkinter would suffice nicely, except that the non-native look and feel seems to confuse Windows users. > You'll find you can't or you have to use external libraries > with Tkinter. Moot. [For me.] > The price you pay for wxPython's flexibility and functionality > is that you have to be a little more specific in telling it > what you want to do. I know. I'm paying the price, I feel like I don't get any benefits. >> Another example: When you create a widget you have to tell it >> who its parent is. > > Note that this is true of all gui toolkits at some point. You > have a containment hierarchy and have to specify it. Eg a > button is inside a text widget is inside a frame. > >> Then in a separate operation, you have to tell the parent >> about the child. > > That is news to this programmer who has been doing > wxPython for 3 years! What are all the calls that look like parent.AddWindow(child,...)? > I don't know where you got that from, but it simply isn't > true. Call GetParent() and GetChildren() and you will find > that all the information is correctly managed automatically. > >> For a final example, in a previous thread I already went on >> and on about the integer widget and event IDs and separate >> "linking" functions used to connect handlers, events, and >> widgets. That seems much lower-level than just passing the >> callable when you create the widget or letting the widget >> object have attributes or get/set methods that can be used to >> set up the callable for an event. > > That just happens to mirror how the insides work. I don't think that's a good excuse for what appears (to me) to be a fragile API. The purpose of an API is to hide how the insides work. > It isn't too much effort to make a higher level wrapper that > does what you want, but in all the years that wxPython has > been available few programmers have thought it would improve > their productivity, quality or other code attributes. One > example you have already seen of someone who thought it would > is Wax. Like I said, I think Wax is a vast improvement. I'd like to help out with Wax, but I'm having a tough time finding basic documentation on wxPython so that I can figure out why some of the Wax classes don't behave as intended. >> Sizers, for example, appear to be an afterthought, and you >> have to sort of stick them onto your widgets manually. That >> functionality is part of the fundamental design of other GUI >> toolkits and just happens automatically. > > Generally the problem is that people don't understand that > there are three seperate hierarchives when dealing with GUIs. > There is the classes of the various controls, there is the > instance hierarchy and there is the layout hierarchy. Thank you! Where do I find the documentation that explains things like that? Teasing it out of people on Usenet is obviously a waste of everybody's time. All I can find is documentaiton on the class hierarchy. I've looked at demo source code, but am having a tough time figuring out why things are written certain ways. > For some gui toolkits the last two are combined. For all the ones I've used in the past, the last two are combined. Your posting is the first place I've seen it explained explicitly that the control and layout hierarchy are separate in wxPython. That probably explains most of my confusion over the parent/child linkage. Not being aware that there are two separate hierachies involved where I'm used to one, it looks like there's a lot of odd redundancy involved in setting up things. > If you have a clean sheet original implementation then you can > make that work well as it imposes some constraints on the > controls to keep the two hierarchies the same. wxWidgets > doesn't have the luxury of a clean sheet design (it has to > work with the existing widgets of the underlying platform). That's true. > In general you should view wxWidgets/Python as a pragmatic > approach to getting a fairly high common appearance and > functionality across multiple platforms. Sometimes the warts > of underneath show through, but if you used the actual > underlying toolkit you would be exposed to them anyway. I guess those warts must be from some of the "underneaths" I've never worked with. > Some other people or companies decided to do a clean slate > thing and implement everything themselves, a good example > being Trolltech and Qt. That is really hard to maintain. Tk > also did this. You can see more of a consistency and less > quirks in their resulting APIs. I agree (obviously). > The good news is that Python does make it easy to put wrappers > around wrappers. Most wxPython programmers haven't felt it > necessary, but if you do the groundwork is already laid. And I'm trying to find information to help me work on that. -- Grant Edwards grante Yow! All right, you at degenerates! I want this visi.com place evacuated in 20 seconds! From bdesth.quelquechose at free.quelquepart.fr Sat May 1 06:21:59 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 01 May 2004 12:21:59 +0200 Subject: Embedding OCaml within Python In-Reply-To: References: <37aad18.0404280019.500e2841@posting.google.com> Message-ID: <409373c0$0$20745$626a14ce@news.free.fr> Jakub Fast wrote: > Max Powers wrote: > >> The situation is this; I've got a large legacy program that is written >> in ocaml, within which there's a parser. I'd like to be able to call >> that parser from my python program > > > Doesn't the O'Caml compiler translate the code into C first? > AFAIK, no, it's a stand-alone native code compiler. From dygimailNo at SPAMpoczta.fm Fri May 14 11:45:00 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 14 May 2004 15:45:00 GMT Subject: Loop and the list References: Message-ID: Tjarko de Jong wrote in news:r8m9a0lv6ggj6u4roa1so9fuqm4vhur9ta at 4ax.com: > indexMax = -1 Don't get it. Why '-1'? -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From asdf at asdf.com Wed May 19 00:05:01 2004 From: asdf at asdf.com (asdf sdf) Date: Wed, 19 May 2004 04:05:01 GMT Subject: install problem with moinmoin on win2k In-Reply-To: References: Message-ID: Mike Rovner wrote: > asdf sdf wrote: > >> pages = os.listdir(text_dir) >> WindowsError: [Errno 3] The system cannot find the path specified: >>'data\\text/*.*' >> > > > No subdirectory 'text' inside 'data' was found. > > HTH, > Mike > thanks, Mike. But is there a larger significance? The moinmoin installation creates a 'data' directory containing subdirs plugin, text and user, as well as the intermap.txt file. text is set to everyone with full control. in fact the path from root to text grants everyone access with full control. The text directory itself contains language-specific help files for moinmoin. all are full control to everyone. From newsgroups at jhrothjr.com Wed May 5 19:59:59 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 May 2004 19:59:59 -0400 Subject: Absolute Imports and PYTHONPATH References: Message-ID: <109j0266q0t5ifc@news.supernews.com> "Richard Cooper" wrote in message news:mailman.288.1083793726.25742.python-list at python.org... > I can't believe I've just been bitten by this again! > > I'm part of a team writing an application in python. We have an fairly > extensive package structure and like sensible pythoneers we use > absolute imports throughout. The top level of our package is in > PYTHONPATH so that all the absolute imports can work. > > This is all fine and dandy until I start playing with two different > versions of the code (working on 2 CVS branches for example). Whenever > I do this I inevitably forget to change PYTHONPATH at some point and > waste an hour or so debugging a problem that occurred because the > __main__ module from one tree is now importing from the other. This has > happened to me a few times now and is really irritating. > > Am I missing an obvious non-hacktastic way to avoid this problem? > > If not would it be possible to fix this problem in a future python? I'm > thinking something along the lines of: > > When a module is imported its import search path includes everything it > does now PLUS the directory that is the top of the module's enclosing > package structure. That way you wouldn't have to add entries to > PYTHONPATH for packages that only import from themselves (and stdlib > and site-packages). Possible? Sensible? What do you think? As far as I'm concerned, the whole notion of Pythonpath is seriously broken, but I'm not about to suggest replacing it given the discussion around PEP 328. Redesigning the whole import mechanism is something that will have to wait for the ever receeding 3.0 What I do is I have a separate command prompt (I'm on Windows) for each different Pythonpath I need to work with, and it sets the correct path for the rest of the work. > > Regards, > > Rich > > From E.A.M.Huijbers at REMOVEstudent.tue.nl Wed May 26 11:21:02 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Wed, 26 May 2004 17:21:02 +0200 Subject: Creating Python class wrapper for a command line tool In-Reply-To: <87aczvxuvr.fsf@titan.staselog.com> References: <87aczvxuvr.fsf@titan.staselog.com> Message-ID: Edvard Majakari wrote: > Hi, > > I was wondering what would be the most elegant way for creating a Python class > wrapper for a command line utility, which takes three types of arguments: > > 1. options with values (--foo=bar) > > 2. boolean options (--squibble) > > 3. data lines (MUNGE:x:y:z:frob) > > So, when you call the program from command line it looks like > > command --foo=bar --hip=hurray --squibble --optimize \ > MUNGE1:x1:y:z:frob1 \ > MUNGE2:x2:y:z:frob2 \ > MUNGE3:x3:y:z:frob3 > > and it produces something. The idea is to make class with methods for > setting the options and data, and then calling write() after all options > have been set. > > My current model is like this: > > class Wrapper: > > def __init__(self, **kwargs): > """Initialize object""" > > opts = [] > > for key, val in kwargs.items(): > if isinstance(val, str) and val.find(' ') > -1: > val = '"%s"' % val > opts.append("--%s %s" % (key.replace('_', '-'), val)) > > def setbool(self, opt): > pass > > def data(self, data): > pass > > def write(self): > pass > > > The init method might look a bit odd; the reason is that I thought to call > Wrapper like this: > > obj = Wrapper(use_bar=foo, treshold=10, name="alley cat") > > and __init__() would transform those keyword parameters to long string > of the form '--use_bar foo --threshold 10 --name "alley cat"' > > However, using **kwargs I cannot use boolean values, because a key in a > dictionary must have a value. Using parameter boolean=True would transform > to --boolean 1, which is not correct. That's why I added a separate method > setbool(), but that doesn't seem nice. To wrap the command line call > > command --optimize --use_bar foo --threshold 10 --name "alley cat" \ > MUNGE1:x1:y:z:frob1 \ > MUNGE2:x2:y:z:frob2 \ > MUNGE3:x3:y:z:frob3 > > obj = Wrapper(use_bar=foo, treshold=10, name="alley cat") > obj.setbool('optimize') > obj.data("MUNGE1:x1:y:z:frob1") > obj.data("MUNGE2:x2:y:z:frob2") > obj.data("MUNGE3:x3:y:z:frob3") > > This is acceptable, but I'm sure many of you professional Pythonistas have > a more elegant solution. What do you think? I am by no means a professional Pythonist... but it doesn't seem too bad to me to check for each kwarg whether it's type is boolean and if so, just add it to the command line as a flag instead of as a value parameter. And data arguments can be passed in the *args tuple. I'm thinking along the lines of: def __init__(self, *args, **kwargs): self.opts = [] for key, val in kwargs: cmdkey = key.replace('_', '-') if isinstance(val, bool): self.opts.append("--%s" % cmdkey) else: if isinstance(val, str) and val.find(' ') > -1: val = '"%s"' % val self.opts.append("--%s %s" % (cmdkey, val)) Which would be called like: obj = Wrapper("MUNGE1:x1:y:z:frob1", "MUNGE2:x2:y:z:frob2", "MUNGE3:x3:y:z:frob3", optimize=True, use_bar=foo, threshold=10, name="Alley cat") This just wraps everything in the constructor. Alternatively, you could go for setting each command-line parameter via a method flag. obj = Wrapper() obj.boolParam('optimize') obj.valueParam('use_bar', 'foo') obj.valueParam('threshold', 10) obj.valueParam('name', 'alley cat') obj.dataParam("MUNGE1:x1:y:z:frob1") obj.dataParam("MUNGE2:x2:y:z:frob2") obj.dataParam("MUNGE3:x3:y:z:frob3") Combining the two methods seems ugly to me, though. - Rico From ykingma at accessforall.nl Fri May 14 07:50:05 2004 From: ykingma at accessforall.nl (Ype Kingma) Date: Fri, 14 May 2004 13:50:05 +0200 Subject: capture exception raised by child thread. References: Message-ID: <40a4b26d$0$557$e4fe514c@news.xs4all.nl> Joe Wong wrote: > Hi, > > I have a class that created a child thread for processing, this thread might raise an exception under some condition. On the main program that create an object of this case, I put a try/except block trying to capture the exception but failed. Am I doing anything wrong here? See the modifications to your code. I hope I got all the names right, it's been a while, but it should give you an idea about one way how to do it. > > here is the stripped version of my code: > > class A: > def __init__(self): > self.thread = threading.Thread(None, self.MyThread) > self.thread.setDaemon(1) It's a bit unusual for a deamon thread to end in an exception, but that doesn't matter. self.caughtException = None self.endEvent = Event() # from the threading module iirc. > self.thread.start() > > def MyThread(self): try: try: > while 1: > # do something. if error: > > if error: > raise exception except exc: self.caughtException = exc # evt. raise exc again finally: self.endEvent.set() > > in my Main program: > > main() > a = A() > while 1: > # do something.. # test (or wait) for the event from a here. if a.endEvent.isSet() and a.caughtException: ... Have fun, Ype From Scott.Daniels at Acm.Org Mon May 17 17:17:56 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 17 May 2004 14:17:56 -0700 Subject: raise exceptions in generators/functions from other tasks/functions In-Reply-To: References: Message-ID: <40a93112$1@nntp0.pdx.net> Dominic wrote: > ... > class TaskHandler(object): > def __init__(self): > self.tasks = [] > def addTask(self, task): > self.tasks.append(task) > def removeTask(self, task): > del self.tasks[task] > ... I think you mean: def removeTask(self, task): self.tasks.remove(task) Or, perhaps: class TaskHandler(object): def __init__(self): self.tasks = {} def addTask(self, task): self.tasks[task] = task def removeTask(self, task): del self.tasks[task] -- -Scott David Daniels Scott.Daniels at Acm.Org From apardon at forel.vub.ac.be Wed May 12 08:31:29 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 May 2004 12:31:29 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> Message-ID: Op 2004-05-12, Duncan Booth schreef : > Antoon Pardon wrote in > news:slrnca428q.1i9.apardon at trout.vub.ac.be: > >> IMO lacking an assignment that copies the value >> of one object into another was a mistake and >> which creats IMO a lot of difficulties. >> >> If I have a function with an object as a paramter. >> and this object is mutable. Now within this function >> I find a second object with the value I want the >> argument to have. Now I can't simply copy the >> second object over the argument but I have to >> copy attribute by attribute from the second object >> into the argument. > > Why wouldn't you just return the second value (or a copy of it) as a result > from the function? That is usually a more flexible choice since it gives > the caller the option of either replacing the original value or using the > modified value somewhere different. Well because the object could be bound with more than one name. > Anyway, if you really need to do this then the mutable object should have > some sort of updateState method which takes the second object as a > parameter. That way the original object can have control over which > attributes get overwritten and which don't. And I think it is a pain in the butt to always have to write such an UpdateState method whenever you want one object to be copied in place from an other. -- Antoon Pardon From mwilson at the-wire.com Wed May 12 09:38:31 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 12 May 2004 09:38:31 -0400 Subject: OT: Idea for Python T-shirt References: <2472a0tgrcv1oc3mbu0ndljogpc5out9da@4ax.com> Message-ID: In article , Christos "TZOTZIOY" Georgiou wrote: >On Tue, 11 May 2004 15:03:13 -0400, rumours say that Peter Hansen > might have written: > >>> [snip "nibbles exploding with desire"] >>> >>> >>>>Also, I don't get it... >>> >>> >>> Based on the hungarian phrase-book sketch from the Flying Circus... "my >>> nipples explode with desire!" >> >>Yeah, that part was obvious (to an MP fan). But why the bit-eating >>snake then? It's gratuitous at that point. Oh, wait, were the ones >>and zeros supposed to be "exploded nibbles"? That's a reach... > >Well, I won't pretend that my pun was cleverly funny, I'll just say that >I thought it was simply funny... My whole idea was of Python processing >happily data, which grouped in fours were nibbles, and there came the >pun of s/p/b/g as Tim said; the "desire" instead of "delight" part of >course was a misteak due to weak memory. Actually, the first thing I thought of was the after-dinner mint scene from "Meaning of Life". Regards. Mel. From peter at engcorp.com Thu May 13 07:16:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 07:16:11 -0400 Subject: make faster Richards benchmark In-Reply-To: <40a33350$1@pfaff2.ethz.ch> References: <6748553f.0405122211.5be5a150@posting.google.com> <40a33350$1@pfaff2.ethz.ch> Message-ID: <9I6dnQvfQ9hgxT7dRVn-tw@powergate.ca> Josef Meile wrote: > Duncan Lissett wrote: > >> I'd appreciate any suggestions on how to make faster Python >> implementations of Richards benchmark. Perhaps there are obvious >> problems that can be corrected? >> >> http://www.lissett.com/ben/bench1.htm > > What's about including a second python implementation of the Richards > benchmark using psyco? You don't have to modify your code, you only have > to add two lines. It would be also interesting to see the differences > between both source codes. I get an immediate 38% speedup by doing "import psyco; psyco.full()" at the start of the benchmark. -Peter From asdf at asdf.com Mon May 10 18:01:25 2004 From: asdf at asdf.com (asdf sdf) Date: Mon, 10 May 2004 22:01:25 GMT Subject: How to read files written with COBOL In-Reply-To: References: Message-ID: Batista, Facundo wrote: > People: > > I'm trying to convert my father from using COBOL to Python, :) > > One difficult thing we stuck into is how to read, from python, files written > with COBOL. > > Do you know a module that allows me to do that? > > It should avoid us the work to write a COBOL program that open the COBOL > file and write a CSV one (easily readable from python). > > Thank you all! > > Facundo Batista > Desarrollo de Red > fbatista at unifon.com.ar > (54 11) 5130-4643 > Cel: 15 5132 0132 > > > i'm going to watch this thread with interest. a couple of weeks ago, i asked about python to legacy mvs particularly for DB2 and Adabas access. i got zero responses which suggested to me that no tools or modules are in wide use. i think you are undertaking a simpler problem generally. if all your records are text it should be fairly straightforward. if not, you'll need to figure out how to map COBOL data representations into python. i seem to remember COMP-3, COMP-5 and packed decimal formats, among others. what they mean, i dont't know, but generally various floating and fixed point formats. you also need to handle REDEFINES which is used to produce a c-union sort of arrangement, where multiple formats can be used to access the same record. 88-Levels are a similar problem. after Y2K, a lot of COBOL files contain some non-obvious date handling, which could involve bit manipulation. if you learn of any sorts of tools at all, please post them back here. python screen scrapers, python compatible database drivers, anything at all. interesting project idea: a COBOL to python _code_ converter. should be feasible, in light of COBOL's very limited syntax. ah, COBOL fun. all us old guys are reflecting on how glad we are we left it behind. it might be a good exercise for your dad, if he wants to retool himself, and he already knows all the data format stuff. From peter at semantico.com Tue May 11 09:45:59 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 11 May 2004 14:45:59 +0100 Subject: perl to python In-Reply-To: References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: <40a0d992$0$25815$afc38c87@news.easynet.co.uk> Ville Vainio wrote: > It's funny, but somehow I can't really think of cases that a > specialized language would do better (ignoring the performace, which > is rarely a concern in sysadmin tasks) than Python with some > modules. There is more to computer usage than sysadmin tasks, sed is an ideal tool for processing large sets of large files (I have to handle small files that are only 130 Mb in size, and I have around 140,000 of them). Performance is not an issue you can ignore when you are handling large amounts of data. Long may sed and awk live, just have to make sure that the O'Reilly's are to hand because the syntax is a bugger. From tjreedy at udel.edu Thu May 6 11:16:23 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 May 2004 11:16:23 -0400 Subject: Scope rule pecularities References: Message-ID: "Antoon Pardon" wrote in message news:slrnc9kilq.5fa.apardon at trout.vub.ac.be... > Now I think I understand what is causing this, but I think this > kind of thing shouldn't happen. If a += b is just syntatic sugar > for a.__iadd__(b) then the first should be acceptable where the > second is acceptable. For immutables, a += b is better thought of as syntactic sugar for a = a+b. tjr From theller at python.net Mon May 10 11:22:23 2004 From: theller at python.net (Thomas Heller) Date: Mon, 10 May 2004 17:22:23 +0200 Subject: Shipping embedded Python project References: Message-ID: Miki Tebeka writes: > Hello, > > I've extended a C++ project with Python. > I'd like to ship the new project with all the required Python modules > but *without* installing Python on client machines. > > I know that py2exe/Installer/cx_freeze ... know how to find which > modules are needed and pack them. > > Is there a "standard" way to do this? I didn't find anything in the docs. py2exe and cx_freeze (not 100% sure about the latter) use modulefinder to find the modules needed. Installer has it's own mf5.py. Or you use py2exe to build a zip-compatible archive, and insert it into sys.path in your program. Do not specify any of the console and windows options, and pass your 'main-module' with the --includes command line option. py2exe will happily create a dist directory for you, without an exe-file. Thomas From gatti at dsdata.it Fri May 14 04:17:19 2004 From: gatti at dsdata.it (Lorenzo Gatti) Date: 14 May 2004 01:17:19 -0700 Subject: liburl cant load webpage with Javascript References: Message-ID: <5b3fd64f.0405140017.3d3a6538@posting.google.com> Uwe Mayer wrote in message news:... > Hi, > > I want do use liburl to scan a webpage which is only accessible from within > my LAN environment. While mozilla manages to load the target URL properly > neither wget, nor liburl or liburl2 does. > I had a closer look at the html source and discovered a lot of Javascript, > including Cookies. > > My suspicion is that the Javascript code needs to be executed for the page > to work properly. Also I don't know how liburl deals with Cookies, but > since they are handled by the Javascript in the source code they are > probably not considered at all. > > In any case I get an IOError: connection refused, Error Code 111. > > Does anyone know a way out of this? > > Thanks for any hints, > Ciao > Uwe Mozilla is a web browser, and it implements cookies, DOM for HTML pages, and a Javascript interpreter with objects representing browser automation. It's unlikely and inappropriate for low level HTTP implementations like wget and liburl to have that kind of support for advanced web features; maybe you can support cookies and Javascript in your application. In the specific case of "IOError: connection refused, Error Code 111", however, the failure seems to happen at a lower protocol level: wrong host names or port numbers, unavailable servers and maybe proxy authentication requirements are the usual causes of refused connections. Lorenzo Gatti From zucker at research.dfci.harvard.edu Thu May 27 17:33:13 2004 From: zucker at research.dfci.harvard.edu (Jeremy Zucker) Date: Thu, 27 May 2004 17:33:13 -0400 Subject: Python for AI: OWL and CLIPS anyone? Message-ID: <753C9F82-B025-11D8-BF76-0003938051D2@research.dfci.harvard.edu> Hello Andre, Did you get an answer to your question? I would like to know, too. Sincerely, Jeremy Zucker Bioinformatics Specialist Dana-Farber Cancer Institute url: http://research.dfci.harvard.edu email: zucker at research.dfci.harvard.edu work: 617-632-6852 cell: 617-833-3196 From Chris.Hornberger at blackrock.com Wed May 12 12:50:16 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 12:50:16 -0400 Subject: newb: object factory, and iteration Message-ID: Your object factory class will be responsible for creating your fileinfo object and associating a file to it, yes? Your factory object should be able to track them by adding them to a list upon creation. Upon completion of whatever operations, the fileinfo class(es) can notify the factory "I'm done" in which case the factory can remove it from the list and let normal reference counting and scoping cleanup take place. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Chris Sent: Wednesday, May 12, 2004 12:22 PM To: python-list at python.org Subject: newb: object factory, and iteration I'm developing a thing that gathers data as follows: 1. For all files of a certain name: I. for all lines in each of those files: i. split the /-separated values in each of those lines, and stuff them into a list (or dict or whatever) ... and this is for a hundred or so such files of that name, with each file having a hundred or so of such lines, with each line having 10 or so of such /-sep'd values. I thought that an instructive way of doing this would be to have a class describing each of these files and their contents, and create a new instance of this class for each file. As I'm writing this, it occurs to me that I could stick to a numbered naming convention (e.g., df1, df2, etc) for when I need to access this data later in the program. But is there a way for me to list all instances of a certain class? I.e., if the classname were FileInfo, and I had hundred objects of that class, could I somehow loop: for all objects created from FileInfo do some stuff TIA for any help. I'll get used to Python sooner or later =) -cjl -- http://mail.python.org/mailman/listinfo/python-list From anthony at python.org Thu May 13 09:48:03 2004 From: anthony at python.org (Anthony Baxter) Date: Thu, 13 May 2004 23:48:03 +1000 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: <40A37C93.1090305@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.4 (release candidate 1). Python 2.3.4 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.4 will follow late next week. For more information on Python 2.3.4, including download links for various platforms, release notes, and known issues, please see: ~ http://www.python.org/2.3.4 Highlights of this new release include: ~ - Bug fixes. According to the release notes, more than 20 bugs ~ have been fixed, including a couple of bugs that could cause ~ Python to crash. These were discovered by Zope3. 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) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFAo3yTDt3F8mpFyBYRAicdAJwOngKitELJ25u3oCW+iQcc581wbQCgh1Ah f/Ci2omZVG7p63xY9cfZiSw= =e3Rv -----END PGP SIGNATURE----- From shalabh at cafepy.com Sat May 29 13:40:52 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sat, 29 May 2004 10:40:52 -0700 Subject: JMS-like Messaging Service for Python? In-Reply-To: <9405c70f.0405290650.8e5ad88@posting.google.com> References: <9405c70f.0405290650.8e5ad88@posting.google.com> Message-ID: Sarah Wang wrote: > Does python have JMS-like messaging service? (open-source preferred) > > or any kind of message queue server? Perhaps spread might interest you: http://www.python.org/other/spread/ Also look at Twisted: http://www.twistedmatrix.com/ -- Shalabh From michael at stroeder.com Mon May 3 03:10:30 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 03 May 2004 09:10:30 +0200 Subject: Cross-Language Encryption: Python/Java In-Reply-To: References: Message-ID: <6s7hm1-ha1.ln1@nb2.stroeder.com> Daniel Orner wrote: > I tried porting the Python rotormodule.c to Java, From http://www.python.org/doc/current/lib/module-rotor.html: "Deprecated since release 2.3. The encryption algorithm is insecure." For encryption to be secure you really have to understand what you are doing! Ciao, Michael. From ville at spammers.com Thu May 20 13:45:02 2004 From: ville at spammers.com (Ville Vainio) Date: 20 May 2004 20:45:02 +0300 Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> I do think that Python's designers should wait til PyPy with Paul> native-code backends has been deployed for a while before Paul> defining too much of Python 3.0, so we can first gain some Paul> experience with compiled Python. Python should evolve Paul> towards being compiled most of the time. I think we might be able to get significant benefits from the .NET implementation (provided that Mono would prove to be legally feasible in the future) - a lot of the JIT work is done by "other people", and being able to seamlessly combine Python with a statically typed language (which probably produces faster code) would be able to give Python a sweet role in many programming projects - the role of the initial implementation/specification language, with grunts doing the possible mechanical porting of performance critical areas. We could have such a role already, but only in theory. C/C++ integration is not seamless enough, and the languages themselves are considered to be too difficult, clumsy and unproductive to attract companies. One thing is pretty certain to benefit any future speedup efforts, whatever road is chosen, namely optional type declarations. Their implementation could be left unspecified, and the initial Python implementation could use them only for runtime type checking in debugmode (or ignore altogether). Type inferencing could also use them to smooth up things. -- Ville Vainio http://tinyurl.com/2prnb From gabor at z10n.net Sun May 23 12:19:02 2004 From: gabor at z10n.net (gabor) Date: Sun, 23 May 2004 18:19:02 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <1085329143.12505.23.camel@dubb> On Sun, 2004-05-23 at 09:25 -0400, Roy Smith wrote: > Peter Hansen wrote: > > If by "C++ brigade" you mean "programmers who think C++ does > > things the right way" then the only way to get them to take > > Python seriously will be either (a) to change Python into > > something that closely resembles C++, or (b) to change those > > programmers so that their thinking fits Python better. > > The world doesn't need another language that looks like C++. Java > already fills that niche quite nicely. > > > Merely adding "proper encapsulation" (and I happen to believe > > Python already has encapsulation that is quite proper) will > > not suffice. And that's a good thing, too.... ;-) > > 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. hmmm...i understand that you can cast away const, but what about... class C { private x; }; (i hope it's correct c++ (i haven't written c++ in the last 2years)). so, how can you write to that variable from the outside? ok, you can take the address of an instance, cast it to (int*) and somehow calculate the address of C.x .but it's very dangerous,because a different compiler can compile it to a different thing and so on... so, except the pointer+offset algo detailed above (which i consider highly unpropable to happen), how can an user of my class/library access that variable? gabor p.s: just for the record.no, i don't like c++. yes,i would like to have private variables in python. no, i don't like perl => i don't want to prefix all my private vars with _. From fredrik at pythonware.com Tue May 25 08:56:08 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 14:56:08 +0200 Subject: SSL Socket EOF protocol violation References: Message-ID: "Josh" wrote: > s.connect( host, port ) > > ssl_object = socket.ssl( s ); > > I don't understand the error, because I think connect takes 2 > arguments according to the docs at the python.org site. where did you look? the current documentation at http://docs.python.org/lib/socket-objects.html says: connect(address) Connect to a remote socket at address. (The format of address depends on the address family -- see above.) and then says: Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later. hope this helps! From bjg at network-theory.co.uk Sun May 2 05:35:33 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 02 May 2004 10:35:33 +0100 Subject: except AttributeError, TypeError: References: <19zy0i7gw5uym.dlg@thorstenkampe.de> Message-ID: <87smejb28q.fsf@network-theory.co.uk> Thorsten Kampe writes: > What is the best way to except two errors, when the except handling in > both cases is the same? The "except" keyword can take a list of exceptions in parentheses, except (AttributeError, TypeError): ... See the "Errors and Exceptions" chapter in the Python tutorial for more details and examples. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From elainejackson7355 at home.com Sat May 15 23:54:43 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 16 May 2004 03:54:43 GMT Subject: tkinter button widget References: Message-ID: <7CBpc.467692$Pk3.138905@pd7tw1no> Thanks for replying, but what you suggest doesn't seem to be working. Nothing I try gets the button to have focus in the first place. If I omit the part corresponding to e = Tkinter.Entry() e.pack() b.pack(anchor=Tkinter.E) then nothing happens, but if I include it, it's an error. Maybe you can point me toward some kind of online resource? My favorite would be to get the knowledge required for this one trick (invoking a button's function with a keypress instead of a mouse click) without climbing any more of the Tkinter learning curve (for now) than I need to. Peace "Jeff Epler" wrote in message news:mailman.0.1084663672.13608.python-list at python.org... | You'll have to arrange for the widget with keyboard focus to have a | binding for the "" event ("" is a valid event name, but | it refers to the event generated when the mouse pointer enters a | widget). The called function would call the invoke() method on the | button. | | You can create a binding on all widgets within a given toplevel by | making the binding on the toplevel itself. | | Example: | | import Tkinter | | def c(): | print "button invoked" | | t = Tkinter.Tk() | b = Tkinter.Button(t, text="Do the thing", command=c) | t.bind("", lambda event: b.invoke()) | e = Tkinter.Entry() | e.pack() | b.pack(anchor=Tkinter.E) | t.mainloop() | | Jeff | From tim.one at comcast.net Mon May 10 10:43:04 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 10 May 2004 10:43:04 -0400 Subject: Integer division, surprising results In-Reply-To: <20040510135905.GH30818@ninthorder.com> Message-ID: [Michael Cornelius] > As an old C programmer, I'm surprised by some results I'm getting with > integer division. For example: > > >>> -1/1000 > -1 As an old C programmer, you should have known that the C standard (C89) didn't define whether the result here was -1 or 0. > >>> -9/2 > -5 Likewise C didn't define whether this was -5 or -4. > I expect the results of these expressions to be 0 and -4, > respectively. Most C compilers do generate code to return those. > I've looked at faqs and documentation, and nothing jumped out at me. > Can anyone explain the reasoning for this? It's primarily driven by the desire that i%j have the same sign as j. If you want that, and also want i == (i/j)*j + (i%j) then integer division has to return the floor. C also requres that identity to hold, and then compilers that truncate i/j need to make i%j have the same sign as i. There are few real use cases for i%j when j is negative. When j is positive, there are many, and in virually all of them it's more useful for i%j to be >= 0 (if the clock says 10 now, what did it say 200 hours go? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite). From greg at cosc.canterbury.ac.nz Wed May 12 23:10:13 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 13 May 2004 15:10:13 +1200 Subject: Integer division, surprising results In-Reply-To: References: Message-ID: <2gg78nF2ck5oU1@uni-berlin.de> Tim Peters wrote: > For example, C99 mandates "the wrong" behavior here (where C89 was > silent), and for no reason other than "because that's what Fortran did". This kind of idiocy seems to be all too common. I was disappointed when Think Pascal changed from the right way to the wrong way, apparently to be compatible with some ill-considered Pascal "standard". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From deetsNOSPAM at web.de Tue May 4 16:57:07 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 04 May 2004 22:57:07 +0200 Subject: iter jitters References: Message-ID: Steven Brent wrote: > In the snippet below, I'm trying to overload the __iter__ list method: > > def __iter__(self): > print "using custom iter" > counter = 0 > end = len(self.data) - 1 > while counter <= end: > print self.data[counter] > counter += 1 > > It pretty much works, except that the output is ugly when the while loop > falls off the end of the list: > > File "mylist.py", line 38, in ? > for item in L3:print item, > TypeError: iter() returned non-iterator of type 'NoneType' > > Oh, yeah, plus it's adding a newline at the end of each item even though > I've got the comma there. I'm gonna keep plugging away to see if I can > figure this out, but stuff like this makes me frustrated... Thanks a > million. I think you've got something wrong here - __iter__ is supposed to return an object that supports the iteration protocol - mainly a next() method that throws an exception when no more elements are available. Today, this kind of thingy is usually done using generators: class foo: def __init__(self): self.data = range(10) def __iter__(self): def _my_iter(): for e in self.data: yield e return _my_iter() for i in foo(): print i -- Regards, Diez B. Roggisch From winexpert at hotmail.com Thu May 27 10:56:40 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 14:56:40 +0000 Subject: how to store binary file data to a database blob Message-ID: Hi, I'd like to read the contents of a file into memory. The problem is that this file is binary. I then want to store the whole thing in memory to a database as a blob. I have no problem reading from a file: I did this: import os f = open('/bin/ls' , 'r+b') data = f.read() f.close() How do I place that in a blob? If I concatenate this to a sql string, how will the database sql parser know where my data string ends, knowing that my data string could contain lots of ' and " and other little things in it. ??? storeString = "insert into mytable (filedata) values ( %s ) " % data Does that look right? I don't think it would execute correctly. Thanks David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ From beliavsky at aol.com Wed May 19 17:26:59 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 19 May 2004 14:26:59 -0700 Subject: comparing strings and integers Message-ID: <3064b51d.0405191326.124a3ab3@posting.google.com> By mistake I coded something like print ("1" > 1) and got the result "True". Comparing an integer and a string seems meaningless to me, and I would prefer to have an exception thrown. Can someone explain why Python allows comparisons between integers and strings, and how it handles those cases? Why is "1" > 1? Pychecker does not warn about the line of code above -- I wish it did. In my code what I really intended was to convert the "1" to an int and THEN do a comparison. From jepler at unpythonic.net Thu May 13 21:34:48 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 May 2004 20:34:48 -0500 Subject: struct doesn't handle NaN values? In-Reply-To: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> References: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> Message-ID: <20040514013446.GA26047@unpythonic.net> On Fri, May 14, 2004 at 01:07:25AM +0000, Grant Edwards wrote: > In order to provide robust translation between native and IEEE > floating point formats, Python is going to have to know what > the native format is. No, it merely needs to use ldexp() with the proper values. Did you try reading what Python actually does? See Objects/floatobject.c's function family _PyFloat_{Unpack,Pack}{4,8} Jeff From jeremy at o-donoghue.com Fri May 14 14:37:53 2004 From: jeremy at o-donoghue.com (Jeremy O'Donoghue) Date: 14 May 2004 11:37:53 -0700 Subject: Real-time graphs References: <20040512152247.68328.qmail@web40001.mail.yahoo.com> Message-ID: I'm the maintainer of the wx backend for matplotlib. My original reason for getting involved with matplotlib was related to real-time graphing and analysis, so hopefully I can give you some indications on performance. John Hunter wrote in message news:... > >>>>> " " == writes: > > > I've trolled the lists, FAQs, and Net as a whole, but can't > > find anything definitive to answer this. > > > We're looking for real-time graph capability (bar, line, etc), > > so that we can display telemetry from a robot system. There > > are a bunch of packages out there, but many seem to provide > > only static graphs (e.g. for scientific, financial data, > > etc). Does anyone currently display real-time telemetry using > > Python? Can anyone provide any suggestions? > > You can do animated graphs with matplotlib - see the examples in the > src distribution anim.py, system_demo.py and dynamic_demo.py. On my > computer (fairly fast) I can get 80-frames per second continually > redrawing the system_monitor figure after updating the data > (admittedly a fairly simple graph) using the antigrain/gtk backend. There is a (rather primitive) example (dynamic_demo_wx.py) supplied in the default matplotlib install, which indicates the basics of embedding a dynamically updated matplotlib plot in a wxFrame (the code is essentially identical in the case of a wxPanel). Having just run the sample, I should note that some of the event handling needs tidying up, but for someone experienced in wx this should be a breeze. > I'm in the process of making some optimizations that will provide some > additional gains, but more work will be required to support real time > charting, especially for more complicated plots. Depending on your > needs and size of plots, however, it may be fast enough. My application displays two separate plots, with multiple axes. One indicates (in real-time) data throughput at the different layers, for a GPRS mobile phone, and the other provides TCP/IP throughput. The application is generally executed on reasonably modern laptops, and you should bear in mind that the main overhead is parsing the logging output to obtain the desired information (I also display signalling information in a text window). The main issue under wx is that the wx backend uses double buffering, and there seems to be a finite time to blit the frame buffer to the screen. In my application, I'm seeing 5-10 updates per second. My estimate is that an application with lower preprocessing requirements would get about 4x the update rate. In my case, I actually wait until I have 16 new points before updating the chart (which gives me my 5-10 Hz updates), but I'm well aware that this will not be adequate for some applications. The fastest solution, under Windows (but not Linux or Mac), using wx, is not to use double buffering, but to use the GDI-style commands. The earliest versions of backend_wx worked this way (but, obviously, flickered somewhat). If this is very important, I can indicate what would be needed to bring back this functionality (basically replacing wxMemoryDC with wxPaintDC, if memory serves). The signal processing in matplotlib is actually very fast indeed, courtesy of Numeric. I believe that you would be hard put to go faster in C. The key issue is in optimising your updating, to minimise the number of redraws. Overall, it has served me very well, although if your performance needs are much beyond what I have noted, you probably are better off with Labview controls, assuming you can run to the price. One other thing I'd point out (as John is too modest) is that matplotlib is being very actively developed as a truly cross platform solution (I originally developed under Linux, now Mac, but deploy under Windows at work), with quite a number of contributors. This means that you can rely on support of an active community that typically fixes bugs in a day or two. It's also pretty well documented (although the 'matlab' interface is much better documented than the object oriented interface, as most contributors make more use of that approach. If you decide to go with Matplotlib, I'll try to give you some pointers. Regards Jeremy From tuure at laurinolli.net Wed May 12 08:31:50 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Wed, 12 May 2004 15:31:50 +0300 Subject: Python dynamic function selection In-Reply-To: References: Message-ID: Eric wrote: >>>>def func(): > print "true" >>>>rules=(func,) >>>>for rule in rules: > rule > I expect the final function to print true, but instead i have > Why? You are not calling the function, so in the interactive interpreter you get the representation instead. >>>>for rule in rules: > > rule("true") Call it without passing arguments. The parentheses denote that the name to their left is callable and should be called with whatever arguments there are inside them, there can also be 0 arguments. for rule in rules: rule() From okyoon at stanford.edu Thu May 6 20:37:16 2004 From: okyoon at stanford.edu (Oh Kyu Yoon) Date: Thu, 6 May 2004 17:37:16 -0700 Subject: Newbie : Greek letters Message-ID: Is there an easy way to include greek letter symbols in TextCtrl of wxPython? -- From gabriel.cooper at mediapulse.com Mon May 3 11:22:29 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 03 May 2004 11:22:29 -0400 Subject: Python CSV DictWriter Problems In-Reply-To: <40966026.70600@mediapulse.com> References: <40966026.70600@mediapulse.com> Message-ID: <409663B5.90102@mediapulse.com> Is there a known-bug in csv.DictWriter? It is ignoring my attempts to specify a Dialect. It doesn't even error if you give it anything invalid. I can send it the registered string-name of the dialect, a string of gibberish, a dialect object instance, a dialect class object... it accepts all and ignores all. Take for example a default-created Dialect, excel-tab: Python 2.3.3 (#1, Apr 14 2004, 01:02:50) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> csv.list_dialects() ['excel-tab', 'excel'] >>> csv.excel_tab.delimiter '\t' >>> a = csv.DictWriter(open('/root/quickbooks/testout.iif','w'),['a','b'],"excel-tab") >>> a.writer.dialect.delimiter ',' >>> a = csv.DictWriter(open('/root/quickbooks/testout.iif','w'),['a','b'],csv.excel_tab()) >>> a.writer.dialect.delimiter ',' >>> a = csv.DictWriter(open('/root/quickbooks/testout.iif','w'),['a','b'],"no one is listening") >>> a.writer.dialect.delimiter ',' >>> a = csv.DictWriter(open('/root/quickbooks/testout.iif','w'),['a','b'],csv.excel_tab) >>> a.writer.dialect.delimiter ',' >>> a.writer.dialect = csv.excel_tab() Traceback (most recent call last): File "", line 1, in ? TypeError: readonly attribute >>> Currently I have to go through and manually set each of the dialect's attributes individually, like so: >>> a.writer.dialect.delimiter = '\t' (etc.) From dmq at gain.com Tue May 18 06:20:39 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 18 May 2004 03:20:39 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> Message-ID: On 17 May 2004 12:35:23 -0700, corey.coughlin at attbi.com (Corey Coughlin) wrote: >You know, it's interesting, I'm an engineer at a semiconductor >company, and I've written netlist manipulation objects over and over >again with only the most basic oop structure, and they usually work >fine. Associating data with each cell is usually not that hard, >although the show() function showing data from all cells above it (?) >seems kind of strange. This type of problem is a case where object >encapsulation is usually a lot more effective than inheritance. In my >netlist objects, the most basic object is just a name object, which >everything inherits because everything in a netlist has a name. >Beyond that, there's some container inheritance, I came up with an >ordered dictionary for pin data, some simple inheritance where Pin >objects inherit from Net objects, but that's about it. > >The basic object structure is pretty simple. The highest level object >is a netlist. The netlist contains a list (just a simple python list) >of cell objects. The cell objects contain a list of nets, a list of >pins, and a list of instances. There are classes for instances, nets, >and pins (which inherit from nets). The instances do refer to their >parent cells, and the pins from the parent are copied in, but that's >about as complicated as things get in the class hierarchy. There's >also a special container class to describe the connections in a cell, >so I can send the connection mesh a net, an instance, or an >instance,pin tuple, and find out what it's connected to. That's >probably the most complicated class, since it uses a few internal >dicts and a type driven interface to resolve the input data. But >that's really about the size of it. Transistors would be instances in >cells (although a transistor cell parent is also in there) and gates >would simply be cells. Now if you had similar cells with different >current or power characteristics, I suppose you'd need to associate >those with an instance class instead of a cell class. Beyond that, I >don't really see why this is such a difficult thing to do. Unless >there's some other overriding goal this needs to accomplish that isn't >in the spec below. You might want to try just coming up with >something like the container hierarchy I have, not worrying about >inheritance, and see if that does the trick for you. This is the kind of thinking I like. 90% of what we need to do can be done with the simplest of programming constructs. I know your company probably considers what you develop proprietary, but would it be possible for you to contribute an example suitable for teaching OOP to EE students? I will probably still keep the Animals example in the intro, since it shows almost everything we will ever need in the simplest possible structure. A netlister would be a great example, however, especially since my students are studying EDA tools. -- Dave From missive at frontiernet.net Mon May 17 17:03:21 2004 From: missive at frontiernet.net (Lee Harr) Date: Mon, 17 May 2004 21:03:21 GMT Subject: program works as a script, not interactively References: <40A8CED9.2AA19629@uk.ibm.com> Message-ID: On 2004-05-17, Philip Carter wrote: > Hello there, > > I am using: > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > > on a win2k box. > > I have the following piece of python code: > > inputTmpFileOnSTAXServer='c:/temp/phil.txt' > outputTmpFileOnSTAXServer='c:/temp/philOut.txt' > import re # import regular expression module > regExp=re.compile('(\[.+\]) Tests run: (\d+), Failures: (\d+)') # > compile the regular expression > inFile=open(inputTmpFileOnSTAXServer) # open the input file for reading > outFile=open(outputTmpFileOnSTAXServer,'w') # open the output file for > writing > aLine=inFile.readline() # read a line > while aLine != "": # loop round until EOF > match=regExp.search(aLine) # search for regExp in aLine > if match: # if there is a match > aDir = match.group(1) # store the dir section of the line > attempted = match.group(2) # store the number of tests attempted > > attemptedInt = int(attempted) # convert it into an int > failed = match.group(3) # store number of failures > failedInt = int(failed) > passedInt = attemptedInt - failedInt # calculate the number > passed > passedStr = str(passedInt) # convert it into a string > outLine=aDir+'\n'+attempted+' tests were > attempted\n'+passedStr+' test(s) passed\n' # create summary line in > correct format > outFile.write(outLine) # write out the summary line > aLine=inFile.readline() # read a line > outFile.close() # close the output file > inFile.close() > > When I save in a file - terry.py and run it: > python terry.py > it works fine. > > However, if I try and paste it into an interactive python window, I get > the following error: > > ... outFile.close() # close the output file > File "", line 14 > outFile.close() # close the output file > ^ > SyntaxError: invalid syntax > > Any idea why this is? > Try typing something simple at the prompt ... >>> if True: ... print 'true' ... true and notice that to get out of the if statement, you have to press ENTER twice. In any event, you will probably be better off putting your code in to a file and importing it. From Mike at DeleteThis.Geary.com Mon May 24 13:17:15 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 24 May 2004 10:17:15 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> <22b7fd40.0405240325.7b2b6376@posting.google.com> Message-ID: <10b4bgsimk120ce@corp.supernews.com> Ralph A. Gable wrote: > The data I want is being stripped out when I access the URL > via urllib. I CAN see the data when I go into IE and do view > source but when I use urllib the site intentionally blanks out > the information I want. For that reason, I would like to get it > using IE6 if I can. If there are other ways to fake out the site, > I would be interested in that also. You may be able to get urllib or urllib2 to work using some of the other tips in this thread, such as the user agent string. Or it may have to do with cookies, in which case the ClientCookie module may be useful: http://wwwsearch.sourceforge.net/ClientCookie/ If you do want to use IE, it's really easy. Let's assume you have an ie object that you've gotten with: ie = win32com.client.Dispatch( 'InternetExplorer.Application' ) and you've navigated to your URL using ie.Navigate( url ), and you've waited for Navigate to finish. Then, you can get the document with: doc = ie.Document >From there, you can get to anything. If you want the entire HTML source, it's: doc.documentElement.outerHTML Or better yet, you can use the IE object model to let IE do the work of parsing the HTML for you. For example, suppose the document contains a form named 'loginForm' with 'username' and 'password' fields, and you want to fill in those two fields and submit the form. You could do it with: form = doc.forms.loginForm form.username = 'myname' form.password = 'mypassword' form.submit() Basically, you can use about the same code you'd use in JavaScript or Visual Basic inside the web page. Here's the MSDN reference for the InternetExplorer object: http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/internetexplorer.asp And here's the reference for the document object: http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_document.asp (Sorry about the long URLs; you know what to do.) One other note: You probably already know about this, but after you do do the Navigate, you need to wait until IE has loaded the page. You can either use the NavigateComplete2 event, or it may be easier to cheat a bit and use a loop with time.sleep() and test the ie.Busy property. I like to wait until ie.Busy is false and remains false for a couple of seconds, to avoid being tripped up by redirects where Busy may go false momentarily and then become true again during the redirect. -Mike From deetsNOSPAM at web.de Thu May 20 10:32:45 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 May 2004 16:32:45 +0200 Subject: query regarding python script References: Message-ID: Shubhra Gupta wrote: > > >> Hi, >> >> I have the following statement in one my python script :- >> >> assert not opt_initialize or os.path.exists(initdir), "initialize implies >> init directory" As the or-operator is non-strict, the right side of it gets only evaluated if the left is False. So the comment pretty much says it: If opt_initialize is True, the not negates it and then the os.path.exists(initdir) is executed - but orly then. -- Regards, Diez B. Roggisch From michela_rossi66 at hotmail.com Sun May 16 06:26:42 2004 From: michela_rossi66 at hotmail.com (michela rossi) Date: 16 May 2004 03:26:42 -0700 Subject: MailMan integrated with JSP/Servlet integration References: <1ed550fd.0405150539.3adffc13@posting.google.com> Message-ID: <1ed550fd.0405160226.5a088220@posting.google.com> Andreas Kostyrka wrote in message news:... > Am Sa, den 15.05.2004 schrieb michela rossi um 15:39: > > Hi, > > Wonder if anyone can help me. > > > > I have a client for whom we are building a website using J2SE & TOMCAT > > 4.1.7. (at clients request). The client also has an installation of > > MailMan that they would like us to use to validate registered users. > > > > All well and good, but given that the bulk of the websites code will > > be written using Java, and MailMan is written in Python - this seems > > to represent a problem or two : e.g. how will the Java code > > interrogate the MailMan installation to find out whether a user has > > validated correctly? Is there any kind of Java interface that anyone > > knows about? > Well the authentication game is fairly easy: Just access an URL that > requires authentication. > > This should work both ways: Java -> Mailman and Mailman -> Java :) > > Andreas Andreas, Thanks - but I don't really understand the reply. Can you expand at all? Thanks, Michela. From mcherm at mcherm.com Wed May 26 09:30:57 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 26 May 2004 06:30:57 -0700 Subject: Why a class when there will only be one instance? Message-ID: <1085578257.40b49c1135e12@mcherm.com> Mitchell Timin writes: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? Some people have learned to think in terms of objects, so they find it useful, mentally, if everything is an object. (Particularly true, in my experience, of people coming from a Java background.) Mitchell adds later: > OK, that makes some sense - to associate certain data and code items and > separate them from other code and data. Wouldn't that purpose be served > even better by putting them into a different file, and not bother with a > class? Other people are comfortable with a procedural paradigm and will use modules for this purpose. That's OK... there are numerous examples in the Python libraries. Roy Smith commented: > More than that, most times I've decided to not bother making something a > class because it was too simple, I've eventually added enough > functionality to it to change my mind and have to re-do things. And finally, some people are comfortable with both paradigms, but prefer to use objects most of the time. The overhead of typing "self" is remarkably small (if you're a slow typist, define a macro!), and they find the objects to be more flexible later. Either way works. But the two most common reasons I've seen for Python users to be "object happy" are because they don't know any better, and because they DO know better. -- Michael Chermside From kamikaze at kuoi.asui.uidaho.edu Wed May 5 16:08:10 2004 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 5 May 2004 20:08:10 GMT Subject: Tkinter vs. wxPython? References: <408E9DCA.EC753FE6@shaw.ca> <408EE7A6.321ED53A@shaw.ca> Message-ID: SeeBelow at SeeBelow.Nut wrote on Tue, 27 Apr 2004 23:07:16 GMT: > I'm mostly a C programmer, with a little Python experience. I have only > basic needs for GUI and graphics. The Tkinter set of widgets seems > adequate for my needs, although one never knows for sure what ones needs > might be. > Portability is important. My audience is 50/50 linux and Windows > people. I myself use Win 2000. > Ease of learning is important to me. I have only a little experience > with GUI and graphics programming. I keep using the phrase "GUI and > graphics" because I need graphical output from my programs, not just a > GUI to control them. For ease of learning and portability, and if you don't need 60fps videogame speed, Tkinter blows anything else for Python away. Pick up John Grayson's _Python and Tkinter Programming_ , and don't look back. I wrote Umbra, a pseudo-3D computer RPG, in Python with Tkinter. While it has problems, it works. Two years ago, I attempted to rewrite it in PyQT, which was a total failure. Last year, I attempted to rewrite it in PyGame, which works and is faster, but requires an immense amount of extra code to accomplish the same tasks. However, Tkinter works well enough that it's not a big issue for applications other than games. Drawing on a Tkinter canvas is not as slow as you'd expect, though it's fairly limited. The image support is terrible (especially since the cropping function from Tk has never been implemented in Tkinter, and the maintainers don't seem to give a damn), but PIL sort of fills the gap, if you don't mind learning yet another API and converting back and forth (which is slow). I've written a few toy apps in wxWindows^WwxWidgets, and it's really a pain in the butt, on par with PyQT for doing things its own way instead of the Python way, and of course there's bugger-all in the way of documentation. Distribution of any of the alternative GUI toolkits with Python apps is a pain. It can be done, but it's extra work in packaging, and more potential problems for end-users, that you don't have with Tkinter. The GUI experience on Python is inadequate. I love Python for server-side tasks, but I will never write another serious GUI app in it until/unless it gets a better standard GUI, preferably something built on top of PyGame. -- Mark Hughes "Doing the impossible makes us mighty." -Captain Malcolm Reynolds, Firefly From ramen at lackingtalent.com Wed May 5 18:41:35 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 05 May 2004 22:41:35 -0000 Subject: MySQL vrs SQLite References: Message-ID: In article , Michael wrote: > I'm considering changing a Python program of mine, that uses MySQL as > it's db backend, to use SQLite. I'm mostly wanting something that can > make my program a complete package without requiring the user install > and configure an external db program. Has anyone experience with these? > They both follow the same DB-API so the code should be pretty easy to > port, right? Any draw backs to making this change? I haven't used SQLite, through Python or otherwise, but I think it's important to note nonetheless that it is supposedly a "typeless" database, as opposed to MySQL, which (though perhaps tolerant to a fault) conforms your data to the datatypes of your columns. The following paragraph from the SQLite web site makes me rather uncomfortable: """SQLite is "typeless". This means that you can store any kind of data you want in any column of any table, regardless of the declared datatype of that column. (See the one exception to this rule in section 2.0 below.) This behavior is a feature, not a bug. A database is suppose to store and retrieve data and it should not matter to the database what format that data is in. The strong typing system found in most other SQL engines and codified in the SQL language spec is a misfeature - it is an example of the implementation showing through into the interface. SQLite seeks to overcome this misfeature by allowing you to store any kind of data into any kind of column and by allowing flexibility in the specification of datatypes.""" -- http://www.hwaci.com/sw/sqlite/datatypes.html If you are doing any type of database work where you need to deal with different types of data (ie. not just strings) and you are concerned with the integrity of your data, I recommend that you take a good hard look at this "feature, not a bug" and determine if SQLite meets your project's requirements. Like I said, I've never used it, so this is all conjecture. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From dlissett0 at yahoo.com Sun May 16 20:53:49 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 16 May 2004 17:53:49 -0700 Subject: make faster Richards benchmark References: <9c2d8268.0405140624.f7a167e@posting.google.com> Message-ID: <6748553f.0405161653.1a7fb8b2@posting.google.com> Peter Hansen wrote in message news:... > My raw numbers are 862806 ticks beforehand, which corresponds > reasonably well with your value. After inserting the two lines > "import psyco" and "psyco.full()" as the very first lines in > the file, I get 627476 ticks. Am I putting it in the wrong > place? (Also tried it at the end just before the call to > main() with no difference.) Pysco is now shown http://www.lissett.com/ben/bench1.htm http://www.lissett.com/ben/bench3.htm From moughanj at tcd.ie Mon May 17 23:11:44 2004 From: moughanj at tcd.ie (James Moughan) Date: 17 May 2004 20:11:44 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> Message-ID: <16752bcc.0405171911.6f4bbb6f@posting.google.com> David MacQuigg wrote in message news:<4ka7a0t585802d81i417j5ufmrdjbq6hei at 4ax.com>... > I'm beginning to understand what you are saying. Thanks for hanging > in there. > > On 12 May 2004 20:51:20 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >David MacQuigg wrote in message news:... > >> On 10 May 2004 16:53:06 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> > >> >David MacQuigg wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... > >> >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> > >> < snip topics we have finished > > >> > > > >As far as I understand it, this is fairly different; the way I would > >implement it, each cell would be an instance, not a class. I would > >have to look at some kind of code/spec to really know, though. Do you > >have an example of a piece of software were you follow this approach? > > Using instances instead of classes is something I hadn't considered. > I could add one line after each class to instantiate it. I'll have to > play with this a bit, and see if I can come up with a *simple* program > to do the same thing as Animals_2, but using instances. I don't yet > have the code written for my circuit-design platform, but I can give > you a spec that describes some of the needs I see. > > 1) We need to represent a hierarchy of cells, typically 5 to 10 levels > deep. > 2) Each cell has data associated with it. Some of this data is a > cummulative total of similar data from all subcells -- total currents, > total chip area, etc. > 3) The data for each cell is unique, and it must be displayed in a > format unique to that cell. > 4) We need a simple function, show() that can be called for any cell > or no cell at all (just knowing the cell type). This function should > show the cell data and the data from all cells above it. In case no > cells of a particular type have been added to the design, the > cummulative data should just show a default value, like zero. > > In addition to these functional requirements, we need to make the > program structure as simple as possible, to use as an introduction to > OOP for design engineers who have no CIS background, but have learned > Python up to the point where OOP is introduced. > > Robustness and generality are not prime requirements at this point, > although introducing something like _private variables is OK, because > it won't distract from the introduction. > I think another poster gave a sample architecture for this type of thing - on a brief look it looks sound, and since he's an electronic engineer I'd say he probably understands the precise problem better than I do. > >> I'm sure there are other examples from other specialties. In > >> accounting, I can imagine a hierarchy of accounts, with a total for > >> each account including all of its subaccounts. Don't just assume that > >> the problem isn't real because you haven't encountered it in your > >> work. > > > >Sorry, but that's not how you would do an accountancy package in OO. > >Again each account would be an instance, not a class, otherwise adding > >a new account would require either code modification or metaclass > >hacking. Instances scope down, and having a count of the sub-accounts > >stored in an object would be OK in my book. Though you wouldn't need > >to, since the container for the instances would do it for you. > > Seems like this is very much like the Animals example. We create an > instance for each asset, but there is one Asset class which is not an > instance. You can't transfer funds to the Asset class, only one of > its accounts. The Asset class, like the Mammal class, keeps data that > is representative of all instances of the class. > Again, no - can you imagine how disasterous out-of-synch is in accountancy? It would be better to physically destroy the hardware than cause an OOS error. I'd keep all of the assets in a container and add their values when the number is needed -effectively re-implementing a database. > >But even this isn't how you would organize an accountancy program. > >You'd use a database. > > That would not work as an example introducing OOP. It would be like > saying to the students -- You can't understand OOP, so we're not even > going to try. Just learn this database program, and use it to solve > whatever problems you may encounter. > We were specifically talking about real world examples - if there's no need to use this structure then there's no need to teach it. Instead, you could choose examples reflecting how OOP is generally used. > >> > >> > >> > >> > > > >70 -> 30 because of this? Really? > > I would also cut way back on the "motivational" parts, and a number of > other things that fit well in the current presentation, but are not > necessary in the presentation I have in mind. My 30 page estimate is > based not on crossing out topics in Learning Python, but on looking at > the 7 pages I have now, and guessing what more I need to add. > > One of the best books I've ever read on a complex subject is > Introduction to Quantum Theory by David Park. The book is split into > two parts: the theory, which is presented in a brief, straightforward, > but unrushed manner; and the examples, which amplify and re-iterate > what is in the theory section. The first time through, you need to > spend a lot of time reading the examples along with the theory. Years > later, you can quickly read just the theory section, and it is a real > pleasure. > > I think I can present the "theory" of OOP in 7 pages, at a sensible > pace, including everything I think will be needed to write most > programs ( bound and unbound methods, lambdas, static methods, etc. ). > http://ece.arizona.edu/~edatools/Python/Prototypes.doc Adding > examples and exercisise may take another 25 pages. Adding > supplementary topics ( multiple inheritance, method resolution order, > some of the techniques you are showing to make classes more versatile > and robust, etc. ) may take another 30 pages. > > >Anyway, I guess you know what you have time to do, it being your > >course 'n all. :) > > > >> > >> > >> >> > >> >> What data are we talking about? numMammals is specific to Mammal. > >> >> genus is specific to Feline, but *inherited* by instances of a > >> >> subclass like Cat. > >> > > >> >The numAnimals etc... data, which is stored in Animals but gets > >> >arbitrarily altered by the actions of subclasses of Animal, and > >> >therefore is not specific to animal; it doesn't represent the state of > >> >the Animal class or of Animal objects, but of a whole bunch of > >> >subclasses of Animal. > >> > >> The total current to an IC is the sum of the currents to all of its > >> subcircuits. That current is a single number, for example, 35 > >> microamps. It has a name "Iss". Iss is a characteristic of the IC > >> which appears in data sheets, etc. It is a variable representing the > >> state of the entire IC. It does not represent the state of any > >> subcircuit in the IC, even though it gets "altered" whenever one of > >> those subcircuit currents changes. > > > >So the IC is an instance which stores or accesses data about the > >instances which it contains, i.e. circuit elements; not a class which > >you sub-class to get subcircuit elements. I'm discussing classes and > >class heirarchies, not instance heirarchies. > > I was also assuming a class hierarchy. The idea of a hierarchy of > instances is new to me. I guess I'll need an example to know what you > are talking about. > I just mean that one instance contains other instance, which contain further instances... to access an instance, access it's container. I'm sure you're familiar with this. > >> Looks like this whole argument comes down to what we mean by the word > >> "specific". Let's drop it and focus on the more interesting topics in > >> this thread. > > > >From here, it looks like the problem is the difference between an > >instance and a class? > > ??? > > >> >> > >> >> These are normal programming errors that can occur in any program, no > >> >> matter how well structured. I don't see how the specific structure of > >> >> Animals.py encourages these errors. > >> > > >> >Imagine if your structure had been implemented as one of the basic > >> >structures of, say, Java. That is, some static data in the Object > >> >class stores state for all the subclasses of Object. Now, someone > >> >coming along and innocently creating a class can break Object - > >> >meaning that may break anything with a dependency on Object, which is > >> >the entire system. So I write a nice GUI widget and bang! by some > >> >bizzare twist it breaks my program somewhere else because of an error > >> >in, say, the StringBuffer class. This is analagous to what you are > >> >implementing here. > >> > >> I'll need an example to see how these general worries can affect the > >> Animals_2 hierarchy. What I see is quite robust. I added a Feline > >> class between Mammal and Cat, and I had to change only two lines in > >> the Cat class. ( And I could avoid even that if I had used a "super" > >> call instead of a direct call to the Mammal functions.) > > > >And if someone unfamiliar with the code neglects to call the > >superclass initializer when they create a new animal, then the code > >will break in unpredictable places. Not calling the superclass is a > >common problem - but easily fixable, *providing* the effects show up > >in the subclass, and not at some other random place in the heirarchy. > > Adding a call to a superclass __init__ is a common pattern in the > examples I've seen. See the section "Calling Superclass Constructors" > starting on page 321 in Learning Python, 2nd ed. > Yup; people still forget the simplest things. *Especially* the simplest things, in fact. > We need to make a distinction between users and programmers in our > expectations of what kind of errors they will make. Users only need > to *read* a class definition and understand what it does. Programmers > are the group that needs to remember to add a call to the superclass > when they write a new class. > > I am a user of the Qt Toolkit, but I would not attempt to add a class > to their existing hierarchy. Nor would I expect Trolltech to provide > me with some kind of robust class-generating function that was > guaranteed to generate an error-free class at any point in their > hierarchy I might chose to insert it. > If you're writing code, you're writing it to be modified at some point, unless it's a few lines-long script. If the modifications are made by someone else then they will reasonably expect that the code doesn't contain implicit deathtraps, like non-local data. > >> > >> We are modeling the real world here. When you add a lion to a zoo, > >> you add one to the count of all animals. > > > >When you add a lion to a zoo, you add one entry in the lion table of > >your database. When you want to know the number of animals in the > >zoo, the database query counts the number of entries in all of the > >animal tables. *Real* databases are built that way because of > >experience; repetition of data invariably causes out-of-synch > >problems. > > I think the database problem is different than our Animals example. > With a database, you typically have many users directly changing the > data over a long period of time when errors can accumulate. Maybe > some user runs a "transaction" script to debit one account and credit > another, but his line goes down before the second part completes. So > it makes sense in this case to store only the primitive data, and > accept the overhead of recalculating everything else from that data > whenever it is needed. > Solving the problem of atomic transactions is something else, and will make your head spin. The accepted design restrictions on databases are not specific to examples using concurrent transactions. The database problem is really no different to the case of a zoo - we want to store a bunch of data about instances/entries of types/tables. Databases just make this much more natural and robust. > >I worked on a project a couple of years ago to port a legacy database > >into MySQL, and it was made damned close to impossible by this sort of > >thinking; how the heck do you port a database which has had it's > >shortcomings patched over to the point where it depends on the > >inconsistent results for it's output? :-\ > > > >> When you add 2 microamps to > >> the core currents in a bandgap voltage reference, you add that same 2 > >> microamps to the total supply current. > >> > > > >Again, I'd be inclined to handle this problem at the instance level, > >not the class level. > > > >> I'm no expert in OOP, but what I have seen so far is not near as clear > >> in structure as the origninal Animals_2 example. > >> > > > >When you have to troll through a 20K line program where the > >functionality for a single subsystem is scattered through multiple > >classes in a heirarchy, it puts a really different perspective on what > >'clear structure' is. Likewise, when everything is modularized > >explicitly and you can alter a complex system which you barely > >understand to include completely new core functionality in an hour or > >two of work. > > I would expect a Python programmer seeing the Animals_2 example for > the first time, could add a class between Feline and Mammal by the end > of an hour, and be quite confident that nothing was broken. I studied > your example for two hours, and I still don't understand it well > enough to make some basic changes. > Yes, the code is too complex - I don't normally use run-time metaprogramming to keep a count of cows :) - but that's because I was straining to find a good solution within the paradigm you had set. I'd expect a Python professional to undestand the example I gave fairly quickly, though - but then again, most of the time they will not need to. > > > >You're right, I don't give a damn whether classes model the real > >world; what matters, in general order of preference, is: > > > >- Robustness > >- Maintainability > >- Programmer time > >- Efficiency > > This is a good set of priorities for a production program. For > teaching OOP, I would say clarity is the over-riding concern. > Sure. But close to that should be examples which reflect on the way you would actually solve a problem. > >I will sell any theoretical principle to the salt mines for those. > >'Classes-model-the-real-world' is an abstract theory, an evolutionary > >holdover from when OO was the Next Big Thing in AI. If it leads you > >to design a non-robust, hard to maintain system then, in my book, it > >gets dropped. > > > >> I'm reminded of the criticism Linus Torvalds got when he first > >> published Linux. The academic community thought it was the worst, > >> most fundamentally flawed design they had ever seen. It did not fit > >> some expectation they had that a "microkernel" architecture was the > >> proper way to design an OS. Luckily, Mr. Torvalds was not dependent > >> on their approval, and had the confidence to move ahead. > > > >I've been trying to explain why the pattern in your example will cause > >bugs; you've been justifying it in terms of OOP metaphors. *shrug* The > >comparison is clear enough to me... :) > > I find the "piece of machinery" metaphor to be helpful, but no big > deal. Mostly, it re-inforces the idea of encapsulation, keeping the > dirty details of how an alternator works inside the component, and > presenting to the outside world, a simple interface: if you want more > current at that output, put more voltage on this input. > > I'm not using metaphors to justify bad programming. I am just having > trouble seeing how one program, side-by-side with another, is > supposedly bad. > > >> >> >> I'm not sure what you mean by "side effects" here. The show() > >> >> >> function at each level is completely independent of the show() > >> >> >> function at another level. > > >> >> > > >> >> >But the inventory data isn't independent. It's affected by classes > >> >> >somewhere else in the heirarchy. Worse, it's done implicitly. > >> >> > >> >> The "inventory data" actually consists of independent pieces of data > >> >> from each class. ( numCats is a piece of inventory data from the Cat > >> >> class.) I'm sorry I just can't follow this. > >> >> > >> > > >> >numMammals OTOH is not just a piece of data from one class - it's a > >> >piece of data stored in one class, but which stores data about events > >> >in many different classes, all of which are outside it's scope. > >> > >> Exactly as we see in objects in the real world. > > > >Objects perhaps, but not classes. This seems to be the distinction > >which is driving this whole problem; you are regarding extending a > >class as if it were adding a member to an instance. > > ??? > > >> >That's the way it has to be, if you want to write it like that. > >> >However there is nothing to say that a given problem must use a > >> >certain class structure. If you come up with a solution like this > >> >then it's near-guaranteed that there was something badly wrong with > >> >the way you modelled the domain. Either the program shouldn't need to > >> >know the number of instances which ever existed of subclasses of > >> >mammal or else your class structure is wrong. > >> > >> Trust me, the need is real. We just need to find the optimum example > >> to show how Python solves the problem. > > > >Mail me some code where you need to do this in a real system, and I'll > >show you how to refactor it. :) > > Let's see if we can get the Animals_2 example right, based on the > requirements I stated above. It will be a few months before I have my > design platform ready, and it will be far more difficult to discuss > basic ideas in the context of a big system. I think Animals_2.py has > one of everything I will be using. > > >> In my work as a software product engineer, I've learned to deal with > >> two very common criticisms. 1) The user doesn't need to do that. 2) > >> The user is an idiot for not understanding our wonderful methodology. > >> These are generally irrefutable arguments that can only be trumped by > >> a customer with a big checkbook. > >> > >> I generally don't engage in these > >> arguments, but on one occasion, I couldn't resist. I was trying to > >> show an expert how a complicated feature could be done much more > >> easily with simpler functions we already had in our program. > >> > >> His argument was basically -- every expert in this company disagrees > >> with you, and you're an idiot for not understanding how our new > >> feature works. I replied that I was the one who wrote the User Guide > >> on that feature. He started to say something, but it was only a > >> fragment of a word, and it kind of fell on the table and died. There > >> was a few seconds of silence, while he tried to figure out if he could > >> call me a liar. I just looked right at him without blinking. > >> > >> Forget what you have learned in books. Think of a real zoo. Think > >> how you would write the simplest possible program to do what Animals_2 > >> does -- keep track of all the different classes of animals, and > >> display the characteristics of any animal or class, including > >> characteristics that are shared by all animals in a larger grouping. > > > >What you're asking is how would I implement something simply, > >providing that I have to implement it with method X. Give me a > >functional spec - what the system needs to do from the user point of > >view - and I'll tell you how I would do it. > > See above for functional spec. > > >In the case of a real zoo, I can pretty much guarantee that it would > >begin > > > >>>>import PySQLdb > > Don't forget. My basic purpose with the Animals_2 example is to teach > OOP, not the use of a particular database. > The example should follow the purpose, though - find an example which reflects accurately on good OOP and it will make things considerably clearer. > >> >And, as general rule, you should think carefully before using classes > >> >to store data; that's typically what objects are for. I used static > >> >data in programs quite a lot before I realised that it too-often bit > >> >me later on. > >> > >> Classes *are* objects. > > > >In Python, classes are 'first class objects' - you can pass them > >around as references, alter them and so on. That's in the same way as > >functions are 'first class objects'. That's a different and older > >piece of terminology than the term 'object' in OOP, which unhappily > >coincides with it. > > > >Wherever I can, I'll convert the discussion over to use the term > >instance if you're more comfortable with the terminology, but in the > >canonical definition a class is not an object. Objects get created > >from classes, and the term is equivalent to instance for practical > >purposes (though you get into occasional pieces of terminology like > >'object instance' where it's just convenient to not have to say > >'object object', and 'object variable' would get kinda confusing too.) > > Check any basic text on OOP for confirmation, say > >http://java.sun.com/docs/books/tutorial/java/concepts/ > > I agree the terminology is confusing, and I try to use "object" only > in the most generic sense. "Class" and "instance", as Python uses > them are OK with me. > > The question, as I understand it, is whether classes should hold just > methods, or both methods and data. Again, the examples I have seen > show plenty of data being stored as attributes of classes. See > Learning Python, 2nd ed. p. 317. The general form of the class > statement according to Mark Lutz is: > No, that's not the issue. Classes can certainly store data, though you should hesitate a little before doing it; the problem is that you're using classes to store non-local data, in particular data about subclasses of the class. As I said, keeping a count of Mammals in Felines in Feline would be fine, if odd for most applications; keeping that count in mammals (and accessing it through Bovine!) is a bug waiting to happen. > class (superclass, ...): # Assign to name. > data = value # Shared class data > def method(self, ...): # Methods > self.member = value # Per-instance data > > Methods are more prevalent in the examples than data, but as far as I > know, there is no warning to the effect: This is possible, but not > good practice. > > >> I think you mean instances. I make a > >> distinction between class variables and instance variables, depending > >> on whether the variable is different from one instance to another. > >> Every instance has a different cat.name, but all cats share the genus > >> "feline". In fact, they share that genus with all other members of > >> the Feline class. That is why I moved it from Cat to Feline as soon > >> as our example was big enough to include a Feline class. > >> > >> > > >> >OK: start with the basics. We need iterative counting data about the > >> >individual elements of the heirarchy. > >> > > >> >The first thing is that we need to factor out the print statements. > >> >Your back-end data manipulation modules should never have UI elements > >> >in them. So, whatever form the data manipulation comes in, it should > >> >be abstract. > >> > >> You are adding requirements to what I already have. OK if it doesn't > >> slow the introductory presentation too much. > >> > >> >Secondly, we want to keep the data stored in each class local to that > >> >class. So, Mammal can store the number of Mammals, if that turns out > >> >to be a good solution, but not the number of it's subclasses. OTOH we > >> >could remove the data from the classes altogether. > >> > >> Think of a real zoo. If you ask the zookeeper how many animals he > >> has, will he tell you only the number that are animals, but are not > >> also lions or tigers or any other species? That number would be zero. > >> > > > >In a real zoo, it would not require brain-surgery on the zookeeper to > >introduce a new type of animal. :) > > Adding the Feline class to the existing hierarchy was very easy. > But it required modification of the program code, and would require modification each time you wanted to add a new animal. Better to avoid that complexity for your user - unless you're in the business of selling updates. > >Also, as I say, in a real zoo you would use a database for this task. > >Any good database design person would balk at the idea of even storing > >the number of a particular animal as an explicit variable in the > >database. Think about that. > > Just so we can move on, I will accept your assertion that a truly > bulletproof zoo program would use a database. We still need an > example that doesn't use a database, or anything other than Python's > basic functionality, to teach students about OOP. > > >> I really do want numMammals to display the total number of all > >> mammals, whether or not they are a member of some other class in > >> addition to Mammal. > >> > >> If I were to guess at your objection to this, I would assume you are > >> worried that the different counters will get "out-of-sync", if for > >> example, someone directly changes one of these variables, rather than > >> calling the appropriate functions to make a synchronized change. > >> > >> My answer to that is to make the counter variables private. I've > >> added a leading underscore to those names. numMammals is now > >> _numMammals. > >> > > > >OOS due to an explicit variable alteration is pretty much the > >worst-case scenario, yes. It would require quite an incompetent coder > >to do it, but it could still easily happen. The more likely problem > >is the failure to call the superclass constructor - which may even be > >harder to debug, since at least in the other case you can run through > >the program in a debugger and find where the variable is being > >changed, or just grep numMammals. > > > >Your faith in private variables is touching. :) > > The Python policy on private variables, which I agree with, is that we > don't need to prevent deliberate action, just make sure the user > understands a variable is private, not to be altered except by the > provided functions. > Oh, I agree - when people want to access private variables they often just delete that annoying little 'private' word. The __ syntax at least gives something searchable. Generally, though, it's better to solve a problem through making the program *necessarily* do what you want than through depending on conventions to save the design. > >> >Thirdly, it would probably be nice if we had the ability to implement > >> >the whole thing in multiple independant systems. Currently the design > >> >only allows one of "whatever-we're-doing" at a time, which is almost > >> >certainly bad. > >> > >> ??? > > > >Supposing I want to store data for two zoos. If the data on the > >number of animals is stored at class-level, then I literally can't do > >that without closing down the program and opening up a different data > >set. Munging the code to have numMammals_at_zoo_1 isn't a good > >solution either. :) > > OK, now I understand. Let's make "Multi_Zoo.py" an example later in > the chapter, not part of the introduction. > > >> >After a bit of brainstorming this is what I came up with. It's not a > >> >specific solution to your problem; instead it's a general one. The > >> >following class may be sub-classed and an entire class-heirarchy can > >> >be placed inside it. It will then generate automatically the code to > >> >keep a track of and count the elements of the class heirarchy, > >> >returning the data you want at a method call. > >> > > >> >This is done with a standard OO tool, the Decorator pattern, but > >> >ramped up with the awesome power of the Python class system. :) > >> > >> My non-CIS students are not familiar with the Decorator pattern. I > >> fear that will make this example incomprehesible to them. > >> > >> > > >> >The above code is 51 lines with about 10 lines of comments. For a > >> >project of any size, this is a heck of an investment; I believe it > >> >would take a fairly determined idiot to break the system, and *most > >> >importantly*, they would be able to trace back the cause from the > >> >effect fairly easily. > >> > >> This is an impressive bit of coding, but I can assure you, as an > >> introduction to OOP, it will blow away any non-CIS student. It may > >> also be difficult to modify, for example, if we want to do what > >> Animals_2 does, and provide a custom display of characteristics for > >> each class. > >> > > > >Hmm, do you mean the talk method or the formatting of the inventory > >data? Because of the rather convoluted scoping rules you have to call > >say animal_farm..talk(self) to access the superclass > >from within the talk method, which is a minor annoyance I guess. > > > >To format the show method differently for each class would be a little > >more awkward, though you're not doing that at the moment. > > I am intending to do exactly that. Because the example is short, you > are tempted to say I really don't need different show functions for > each class. I can add more unique items to each class if I must, > making it look more like a "real program", or you can accept the > requirement that the small differences in the example display are > important. > *Shrugs* fine, if you want that as a requirement. I guess each class could define a format function, and you could return the function alongside the number. You would still get the advantage of inheritance. > How about something like this: We put all data and formatting unique > to each class within that class, but we don't use the trick of each > class calling its parent to generate a complete display. The > sequencing of displays could then be done by some generic function, > calling in sequence the unique display functions from each class. > Sounds reasonable. I'd still be more comfortable if you used a different example for your students, but it's up to you.. > >> One possibility is to make this an Animals_3 example. Animals_1 was a > >> simple two-class structure. It served to introduce instance > >> variables, and some basic concepts like inheritance. When we moved to > >> Animals_2, we pointed out the limitations of Animals_1, like not > >> having enough classes to put variables like 'genus' where they really > >> belong. > >> > >> Maybe we should go one more step, and make this a third example. We > >> can point out the limitations of Animals_2 in the introduction to > >> Animals_3. I can see the benefit of moving the print statements to > >> the top level. This is needed if we ever want to make the classes in > >> Animals_2 work in some kind of framework with other classes. The > >> show() functions in Animals_2 could be modified to return a list of > >> strings instead of printing directly to the console. > >> > >> I've posted your program as Solution 3 to the exercise at > >> http://ece.arizona.edu/~edatools/Python/Exercises/ Could you give us > >> a brief description of the advantages and disadvantages compared to > >> the original. I'm not able to do that, because I'm having difficulty > >> restating what you have said above in terms that students will > >> understand. I cannot, for example, explain why your solution is more > >> robust. > >> > > > >Advantages: > > Robustness; no requirement for a programmer to keep a count of > > instances or update the count of the super class by calling it's > > initializer. This minimises the chance of programmer error. > > Avoids replication of data, eliminating OOS errors. > > > > Maintainability; all of the code for counting is contained in a > > single module, so modifications will not require changes to > >multiple > > similar pieces of code throughout the class structure. > > > > Agility; we can maintain more than one zoo in a program by > >creating > > new instances of of the animal_farm class. Class level data would > > limit us to data on a single zoo system. > > > > Generality; the Collection class can be used for any problem of > > this type. > > This is excellent. I will add it to my web-page. > > >> >Admittedly the solution is on the complicated side, though perhaps > >> >someone with more experience than me could simplify things. > >> >Unfortunately, a certain amount of complexity is just a reflection of > >> >the fact that your demands strain the OO paradigm right to it's limit. > >> > You could possibly implement the same thing in Java with a Factory > >> >pattern, and perhaps the reflection API. > >> > >> Your vast experience may be blinding you to the problems non-CIS > >> students will have with these more complex solutions. I may be > >> pushing a paradigm to some limit, but these are real-world problems > >> that should be easily solved with a good OOP language. > > > >This isn't something I'd show a programming beginner either! I'd > >choose a different way of demonstrating a class heirarchy, myself. > > OK, I'm convinced we need a third example. Animals_2 will remain part > of the introduction, and our next example Animals_3 will be our > bullet-proof, production-quality, > what-you-better-do-if-someone-is-paying-you, final solution. > > I would still like to see some simplification of Animals_JM.py > Although clarity is not specifically on your list of requirements, I > think it does impact maintainability and programmer time. > There are a couple of places where it could be simplified slightly, but usually my approach to clarifying complex algorithms is just to blit the code with comments. I also try to avoid complexity by picking a natural paradigm for the task, of course. > Meanwhile, I'll try doing something with your "instances instead of > classes" suggestion. > > -- Dave From kmmcdonald at wisc.edu Tue May 4 00:19:23 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Tue, 04 May 2004 04:19:23 GMT Subject: Very, very strange problem with properties References: Message-ID: Urgh, and that explains why it was working before: I changed my class's parent class from 'object' to another classic class. Sigh. Still, I find it kinda strange that the getter worked... Thanks for the help! Ken In article , Carl Banks wrote: > Kenneth McDonald wrote: >> >> >> For some reason, properties seem to have stopped working correctly >> on my system. (Mac OS X 10.3, custom-compiled Python 2.3.3) To the >> best of my knowledge, they were working correctly at some point >> in the not-too-distant past. The confusing thing is that they >> _partly_ work. >> >> Consider the following code: >> >> class foo: > > > There's your problem. You've defined a classic class. Properties > only work with new-style classes, so you need to use "class > foo(object)". > > > suspects-he-will-have-realized-this-2-seconds-after-posting-ly yr's, > > From fnord at u.washington.edu Mon May 10 13:05:20 2004 From: fnord at u.washington.edu (Lonnie Princehouse) Date: 10 May 2004 10:05:20 -0700 Subject: Best IDE? References: <4ace7f9f.0404111147.3120288a@posting.google.com> Message-ID: Actually, there is a way to use VIM as the editor for Visual Studio. See http://www.vim.org/htmldoc/if_ole.html (related bonus link: use VIM for Mozilla text boxes, http://mozex.mozdev.org) -ljp Timothy Wu wrote in message news:... > rakanishu wrote: > > I don't know if I'd call 'em IDEs but it's worth taking the time to > > learn either emacs or vim. Both are very powerful editors that run on > > multiple platforms. I tried emacs three times, but couldn't get into > > it. I'm now getting hooked on vim. YMMV. > > I love Vim. I really do. And it works wonderfully on both Linux and > Windows with Exuberant ctags (http://ctags.sourceforge.net/) on Python > code. However the only thing that's bugging me is once I'm used to using > Vi(that's practically the only editor I've ever use), I'm forever stuck > with using Vi. I wish all other real IDEs comes with Vi mode, or I can > somehow embed Vim in there (or someone else doing it for me as I'm not > that technical). I would love to be using an IDE if it doesn't slow me down. > > Timothy From sylphaleya at gmx.net Thu May 27 05:37:51 2004 From: sylphaleya at gmx.net (Manuel Huesser) Date: Thu, 27 May 2004 11:37:51 +0200 Subject: PyPGSQL - OID Message-ID: Der Python DB API supports the method oidValue on a cursor instance. On PostgreSQL I get the internal used oid from each row, but I need the id from the primary key. Is there a way? Thanks From Holger.Joukl at LBBW.de Thu May 6 10:25:58 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Thu, 6 May 2004 16:25:58 +0200 Subject: introspection: How to find out the class defining a method Message-ID: Hi, introspection works different in python 2.3: Python 2.3.3 (#12, Feb 19 2004, 11:42:09) [GCC 2.95.2 19991024 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: ... def do(self): ... pass ... >>> class Moo(Foo): ... pass ... >>> x=Moo() >>> x.do.im_class >>> whereas: Python 2.1 (#3, Jun 1 2001, 15:51:25) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> class Foo: ... def do(self): ... pass ... >>> class Moo(Foo): ... pass ... >>> x=Moo() >>> x.do.im_class >>> Is there an elegant way to achieve the latter result (i.e. the base class in which this method actually is defined) in python 2.3, too? Couldn?t find it in the docs. Cheers Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From FBatista at uniFON.com.ar Thu May 13 09:22:16 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 13 May 2004 10:22:16 -0300 Subject: Python - open forever ? Message-ID: [Romans Krjukovs] #- - How we can minimize such risk ? (Become a member of some club, #- buy licenses, support etc.) A common aproach to this is to have one or several persons involved in Python as developers full time in your enterprise. I mean this: some people, that go to work to your offices and you pay them, and they do Python full time. Human power is always needed... . Facundo From garret_mcgraw at yahoo.com Sun May 9 18:38:04 2004 From: garret_mcgraw at yahoo.com (Garret McGraw) Date: Sun, 09 May 2004 18:38:04 -0400 Subject: Excel database module Message-ID: <409EB2CC.1010906@yahoo.com> Has anybody heard of or know of a python module for reading/parsing/writing microsoft excel databases? Any response would be greatly appreciated. Thanks, GEM From apardon at forel.vub.ac.be Thu May 6 10:24:57 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 May 2004 14:24:57 GMT Subject: Scope rule pecularities Message-ID: Well to test things out I wrote the following: class Int: def __init__(self, v): self.value = v def __add__(self, term): return Int(self.value + term.value) def __iadd__(self, term): self.value += term.value return self.value def __str__(self): return `self.value` a1 = Int(14) a2 = Int(15) b = Int(23) print a1, a2 def foo(): a1 += b a2.__iadd__(b) foo() print a1, a2 Now the a1 += b line doesn't work, it produces the following error: UnboundLocalError: local variable 'a1' referenced before assignment. The a2.__iadd__(b) line however works without trouble. Now I think I understand what is causing this, but I think this kind of thing shouldn't happen. If a += b is just syntatic sugar for a.__iadd__(b) then the first should be acceptable where the second is acceptable. -- Antoon Pardon From roland at catalogix.se Fri May 28 10:06:46 2004 From: roland at catalogix.se (Roland Hedberg) Date: Fri, 28 May 2004 16:06:46 +0200 Subject: Module calling-newbie question Message-ID: <40B74776.2080603@catalogix.se> Hi! I'm having problems with using modules. I'lls start with the error as it is presented: Exception in Tree control callback Traceback (most recent call last): File "/local/develop/apacheadmin/Tree.py", line 427, in PVT_set_state self.widget.get_contents_callback(self) File "sexptree.py", line 11, in getelements for element in spo.sublist(node): File "/local/develop/apacheadmin/sexp.py", line 103, in sublist ss = string.split( subspec, "/" ) File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) I using the tkinter based Tree.py module Charles E. "Gene" Cash and have built one module sexp.py which among other things tries to split a string. Really nothing fancy but it fails when the sexp module is used by a python program sexptree.py (also by me). Sexp.py as well as sexptree.py imports string. What more can I do ?? What am I doing wrong ?? -- Roland From timr at probo.com Mon May 10 00:52:53 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 09 May 2004 21:52:53 -0700 Subject: list comprehension References: Message-ID: Guy Robinson wrote: >This works I was just wondering if something could be written more >concisely and hopefully faster: > >s = "114320,69808 114272,69920 113568,71600 113328,72272" >e = s.split(' ') >out ='' >for d in e: > d =d.split(',') > out +='%s,%d ' %(d[0],-int(d[1])) >print out Well, why not the more obvious: s.replace(',',',-') -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From donn at drizzle.com Sat May 22 14:28:33 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 22 May 2004 18:28:33 -0000 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> Message-ID: <1085250512.626217@yasure> Quoth David MacQuigg : | import math | | def mypow(x, y): | return x**y | | class MathA: | pow = math.pow | | class MathB: | pow = mypow | | ma = MathA() | mb = MathB() | | print ma.pow(2,4) #=> | 16.0 | print mb.pow(2,4) #=> | # TypeError: mypow() takes exactly 2 arguments (3 given) | | How would you explain this to non-CIS students in a class on circuit | design, where there is very little time to discuss programming? I wouldn't. I would say "Classes allow you to create objects with their own functions, called methods, that you write. Each function takes `self' as its first parameter." "Here's a class:" class A: def __init__(self): self.data = 'spud' def hello(self): print 'Hello, I am a class A', self.data "Classes can inherit functions from other classes:" class B(A): def __init__(self): self.data = 'gerbil' "The actual object - a class `instance' - is created by invoking the class name, applying arguments which will be passed to __init__." Then I would go over that, showing what happens and why, until the concepts introduced above seem to be clear for everyone. That would conclude my treatment of classes. As an elementary language, there are some slightly hard things to learn about Python, but this isn't going to be one of them unless you make it hard. Donn From max at alcyone.com Fri May 14 17:38:41 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 May 2004 14:38:41 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 References: <3064b51d.0405140758.4c556d8e@posting.google.com> Message-ID: <40A53C61.BE0712FD@alcyone.com> beliavsky at aol.com wrote: > Thanks to the Python developers for their continuing work. > > I wonder why the Linux installation needs to be more tedious than the > Windows counterpart. The problem is of course not specific to Python. > There are many Linux distributions, running on different kernels, but > maybe binaries that have been tested on the "major" distributions like > Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. Why do you think the standard and near-universal ./configure && make && make install is tedious? -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ This moment is / Mine -- Chante Moore From andy at andybak.net Wed May 12 10:20:40 2004 From: andy at andybak.net (Andy Baker) Date: Wed, 12 May 2004 15:20:40 +0100 Subject: newbie question: should I learn TKinter or skip it and learnmoreadvanced toolkit? In-Reply-To: Message-ID: I started with Tk and dropped it on horror when I realised it had no muti-column list box. Shame coz it is better documented than anything else. Next I tried Wx I am on Windows so the dependency issue wasn't a problem and the install was easy. There are some great example files and documentation is getting better but it is rather less Pythonic than I would have liked and you find yourself reading C++ docs and mentally translating them. Not the kind of thing I got into Python for! Which brings us to Wax. I really hope this project takes off as it seems the perfect solution. It is definitely usable. I am going to use it where I can and learn enough wx to fill the gaps where Wax doesn't reach. Hopefully when my Python-fu improves I might even be able to contribute! I think it should be possible to mix wx and Wax code quite easily although I am at an early stage of my investigations. pyQt doesn't look like an option on Windows and pyGTK looks like it is even less documented than wx although I may be wrong here. > -----Original Message----- > From: python-list-bounces+andy=andybak.net at python.org > [mailto:python-list-bounces+andy=andybak.net at python.org] On > Behalf Of Hornberger, Chris > Sent: 12 May 2004 13:42 > To: python-list at python.org > Subject: RE: newbie question: should I learn TKinter or skip > it and learnmoreadvanced toolkit? > > First learn crawl, then learn walk. Nature rules, Daniel San. > > -------------------------- > Chris Hornberger > Blackrock - 302.797.2318 > chris.hornberger at blackrock.com > > Card carrying MSDN member since 2004. > No, really. I've got the card to prove it. > > > -----Original Message----- > From: python-list-bounces+chris.hornberger=blackrock.com at python.org > [mailto:python-list-bounces+chris.hornberger=blackrock.com at pyt > hon.org]On > Behalf Of Porky Pig Jr > Sent: Tuesday, May 11, 2004 7:28 PM > To: python-list at python.org > Subject: newbie question: should I learn TKinter or skip it > and learn moreadvanced toolkit? > > > I'm in a process of digging into Python, and one of the > problems I'm having is whether I should spend any time at all > learning TKinter or skip it and start with more advanced > staff like wx or QT. > > I have no experience with GUI whatsoever, so anything will be > a learning experience for me. The reason I've decided to post > this question is that I see some contradictory information in > different resources. > > In 'Programming Python', learning TKinter is recommended -- > before you move to more advanced toolkits. The rationale is > (i) it is built-in and since it is also shared by TCL and > Perl, it is well-maintained and always in sync with the > latest version of Python, (ii) it is fairly simple to learn, > small learning curve, easier to grasp some concepts before > moving to more comprehensive production quality toolkit such as QT. > > In some other resources TKinter is critisized as not well > integrated at Python at all, so recommendation is 'not to > waste your time and start learning GUI with either wx or QT'. > > My intent is *not* to become professional GUI developer, but > simply to get a handle on it, so if I write some utilities, I > can provide some nice GUI if required. Yet of course, since > I'm learning something new, it would be nice to learn it > 'right from the start'. > > So: should I spend some time or TKinter or simply skip it and > start learning GUI with something like wx or QT? > > (my background: solid C, enough C++ to understand the OOP > concepts, Perl, too much of it to my liking, BTW) > > TIA. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > From beaststwo at yahoo.com Tue May 4 07:52:08 2004 From: beaststwo at yahoo.com (Tim Sharpe) Date: 4 May 2004 04:52:08 -0700 Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> <4093de02$0$17252$a1866201@newsreader.visi.com> Message-ID: <5600d16b.0405040352.47c9087e@posting.google.com> Peter Hansen wrote > > The last sentence is really the whole point. The OP needs > to be aware that the accuracy *cannot* be *guaranteed* > to better than "tens of milliseconds", overall, regardless > of the "accuracy" of the clock tick or the resolution of > anything... > As a network geek who writes crude software to test problems, I wonder if we're not getting overly hung up on "exact". My experience shows that, outside of bulk transfers running at least tens of megabits per second, network delays don't become noticeable until round-trip delays in the range 100mS or greater are observed (there's a wealth of Internet documentation on "bandwidth-delay issues" that well cover the impact of delay on performance of TCP-based applications). This would appear to indicate that the above numbers (tens of milliseconds) may be quite reasonable if the intent is to identify operational problems, vice academic interest. To troubleshoot problems that occur with delay deltas less than about 25mS, you're going to be into those $100,000+ software packages that rich folks use to model traffic patterns, that is if you want anything meaningful. For this kind of accurancy, it should be reasonable to create a multithreaded program, spawn the worker threads (they'll do the actual pinging) in advance, then use queues (see Aahz's great threading tutorial at http://starship.python.net/crew/aahz/OSCON2000/TOC.HTM) to activate the workers to ping each host. This would seem to get as close to a simultaneous start and operation as practical. The trick would be to make sure that your Ping code runs thread safe and that you use unique numbers in the ICMP "indentifier" field, or your code can't tell which ICMP packet belongs to which thread (it may still be tough). If you really need more accuracy, then your best bet is to use libpcap (or winpcap for Windows, see http://www.tcpdump.org), as it provides packet timestamps that I've found to be accurate to fractions of milliseconds. You could spawn Pings, capture them with libpcap, then decode the libpcap packet header to extract the timestamp. Ok, not a great answer, but it really depends on the desired result of the program. Less accuracy may well do the job. Tim From gerrit.muller at embeddedsystems.nl Fri May 7 02:12:43 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 07 May 2004 08:12:43 +0200 Subject: VPython and 3D Visualization In-Reply-To: References: Message-ID: Joel C. Alcarez wrote: > > I have been using VPython ( http://www.vpython.org) in developing cross > platform 3D visualization tools for Physics Lectures. > > My experience with Python and VPython has been rewarding in more ways > than one. > > My employer Mapua (http://www.mapua.edu.ph/) has decided to support my > work and send me (Joel Alcarez) and my collaborator Prof. Joyrence Agas > to Ateneo de Davao to demonstrate the software developed using Python > and VPython to a very receptive audience composed of distinguished > Physics professors from all over the country. > sounds great! I have been playing myself somewhat with VPython and it is amazing how fast you can create 3D visualizations. regards Gerrit -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From jfranz at neurokode.com Wed May 12 13:18:11 2004 From: jfranz at neurokode.com (Jon Franz) Date: Wed, 12 May 2004 13:18:11 -0400 Subject: Python+SQL References: Message-ID: <012c01c43845$1b0619a0$5c01a8c0@letterbox1> The official references don't include anything since the modules are just implementations of the DBAPI standard - getting to know that standard will help you immensely. http://www.python.org/sigs/db-sig/status.html Alternately, try using PDO (Python Database Objects). You will still need a DBAPI complaint module for PDO to work correctly, but it is designed to be easy to use and provides some nice features like column-access-by-name, while still being lightweight and very fast. Oh, and its free. http://pdo.neurokode.com ~Jon Franz NeuroKode Labs, LLC ----- Original Message ----- From: "Chris Stiles" To: Sent: Wednesday, May 12, 2004 12:02 PM Subject: Python+SQL > What are my options for using Python and SQL - specifically mysql ? So far > I've found pysqldb and python-mysql on sourceforge, but the official > references don't seem to include anything. > > Is there an API that supports the 'table row expressed/mapped to object' > paradigm ? > > -- > regards, chris > > From csad7 at yahoo.com Mon May 17 13:27:34 2004 From: csad7 at yahoo.com (chris) Date: Mon, 17 May 2004 19:27:34 +0200 Subject: general Wiki format question and Python Wiki markup parsing libraries In-Reply-To: <10afm96drie41b5@news.supernews.com> References: <10afm96drie41b5@news.supernews.com> Message-ID: John Roth wrote: > "Jarek Zgoda" wrote in message > news:c87e40$mbj$3 at nemesis.news.tpi.pl... > >>chris pisze: >> >> >>>is there something like a "standard" wiki format at all, or at least one >>>that is widely used? >> >>Don't think so. I saw more than 10 "simplified markups", of which nearly >>all was more complicated than original HTML. > > > Well, I think the "simplified" seems to be a tradeoff in > terms of fewer keystrokes, rather than any conceptual > simplicity. If you really want to simplify things, please come > up with a little WISIWIG editor rather than yet more > line noise. > > John Roth > > >>-- >>Jarek Zgoda >>http://jpa.berlios.de/ > > > well, i think it is not fewer keystrokes but to be able to easily read the text (like here in this email without the html tag noise in e.g. javadoc) when working on the xml/xsl file but at the same time to be able to generate a structured xhtml documentation from the same text. so something like restructured text seems like the best option to me for now. chris From Moiz.Golawala at ge.com Thu May 6 09:27:53 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Thu, 6 May 2004 08:27:53 -0500 Subject: How to get Hostname using SimpleXMLRPCServer Message-ID: I have multiple xmlrpc clients talking to my SimpleXMLRPCServer. When a method on my server is invoked, I would like to know the hostname of the client that has invoked the method. Does anybody know how to get the client host name from the xmlrpc request call to the SimpleXMLRPCServer. Any help is appreciated. Thanks in advance. - Moiz From apardon at forel.vub.ac.be Fri May 14 03:21:31 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 May 2004 07:21:31 GMT Subject: Scope rule pecularities References: <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: Op 2004-05-13, Aahz schreef : > In article , > Antoon Pardon wrote: >> >>Well one could drop the immutability of certain classes instead. One >>would then loose the immutabilty purity and gain the consistency >>purity. In a choice between those two purities I would choose the >>latter. > > That won't fly. What do you use for dict keys? You make a copy of the key and use the copy in the internals of the dictionary. -- Antoon Pardon From P at draigBrady.com Fri May 28 07:00:44 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Fri, 28 May 2004 12:00:44 +0100 Subject: Non-programmer needs help with PyGTK-2.0.0 In-Reply-To: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> Message-ID: <40B71BDC.4050700@draigBrady.com> Mark Mitchell wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > I have a program written in python that tells me it requires PyGTK, so I > DLed, ./configure, make, make install and the process seems to go ok. Some > errors but the process finishes so I assumed they weren't fatal errors. > > So now I attempt to run my python program and I get; > $ gccp.py > Traceback (most recent call last): > File "./gccp.py", line 9, in ? > import pygtk > ImportError: No module named pygtk > > I'm running Slackware 9.1 with a 2.6.6 kernel, and I don't know what other > information would be helpful. Why not try a prepackaged version? http://www.linuxpackages.net/search_view.php?by=name&name=pygtk2&ver=9.1 At least it will give you info on the right thing to do P?draig. From sholden at holdenweb.com Tue May 25 19:20:12 2004 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 May 2004 19:20:12 -0400 Subject: Named integers and enums In-Reply-To: References: <40b37015$1@nntp0.pdx.net> Message-ID: Hallvard B Furuseth wrote: > Scott David Daniels wrote: > >>Hallvard B Furuseth wrote: >> >> >>>I wonder: isinstance() says that even classic class instances are 'object' >>>instances, even though they do not seem to be (since __slots__ does not >>>work): >>> >>> class o: __slots__ = () >>> ... >>> >>> isinstance(o(), object) >>> 1 >>> >>> o().foo = True >>> >>> >> >>Actually __slots__ works, you just have a funny idea of what __slots__ >>is _for_. __slots__ is a _storage_optimization_. > > > That's not what I mean. > > I'm wondering why isinstance() claims that instances of 'o' are > instances of 'object', when 'o' is not declared to be a subclass of > 'object'. > Instances of o are instances of object because, I believe, everything is ultimately held to be an instance of object. Unless you can find an x such that isinstance(x, object) is false - I couldn't find such a value. > I used __slots__ to check if 'o' is a subclass of 'object' anyway, since > __slots__ is documented to only work for new-style classes - i.e. > classes derived from 'object'. Well, it is not. If it had been, the > assignment to o().foo above would have failed. > As you appear to have deduced, the purpose of __slots__ is to limit the keys that can be stored in the object's __dict__, and so clearly o is not a subclass of object. But you could have determined that directly: >>> class o: pass ... >>> issubclass(o, object) False >>> issubclass(int, object) True However, none of this tells you anything about the relationship between object, old-style class and instances thereof: >>> type(o) >>> oi = O() >>> type(oi) >>> issubclass(oi, object) Traceback (most recent call last): File "", line 1, in ? TypeError: issubclass() arg 1 must be a class Sometimes it's difficult to keep your head from exploding: >>> type(object) >>> type(type) regards Steve From danu_milis at yahoo.com Mon May 31 10:34:22 2004 From: danu_milis at yahoo.com (danu kusmana) Date: Mon, 31 May 2004 07:34:22 -0700 (PDT) Subject: SimpleXMLRPCServer performance issue in MSWin In-Reply-To: <40B5EB86.3050305@sweetapp.com> Message-ID: <20040531143422.33891.qmail@web60610.mail.yahoo.com> When I ran the server script on Windows platform is running very slow. The log printed automatically by the SimpleXMLRPCServer class; I assumed, is processing every 5 second each process if 1 client connected. If 1 more client accessed the time is decreasing half of the first. But compared when the server script running on Linux is much to slow. Maybe I also forgot mention before that if the script running on Windows its only processing 1 thread/Main thread are being processed, even when 2 or more clients are connected. Is it the class it self or something else I should have know? Thanx danu --- Brian Quinlan wrote: > danu kusmana wrote: > > Hi > > > > Im trying to figure out why the same server script > I > > use is running slower in Windows than in Linux. > > Please provide more details e.g. timings, whether > the performance > problem is found in the client/server/both, etc. > > Cheers, > Brian __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From teiffel at attglobal.net Tue May 18 11:25:49 2004 From: teiffel at attglobal.net (Marcello Pietrobon) Date: Tue, 18 May 2004 11:25:49 -0400 Subject: How to just wait 3 secs ? Message-ID: <40AA2AFD.1080804@attglobal.net> Hello, I would like to make my script to wait 3 seconds ( so I can read the output on the console ) and then continue. How do I do it ? Thank you, Marcello From sorr at rightnow.com Thu May 20 14:17:01 2004 From: sorr at rightnow.com (Orr, Steve) Date: Thu, 20 May 2004 12:17:01 -0600 Subject: N-Tier Web Applications, Application Servers and Python Message-ID: I'm looking to architect a 4-tier or N-tier Python web/CGI app with database connection pooling for high performance. Is there a Python equivalent to Sun's now famous Java PetStore application? (Or something like this link: http://www.developer.com/tech/article.php/606971?) Any Python recommended links/white papers? I've glanced at various Python utilities and frameworks (including Twisted) but what I really need is a fairly complete and robust sample/demo app like Java PetStore. If there is no such Python equivalent then there OUGHT to be. ;-) TIA, D. B. From stani_ at hotmail.com Sat May 1 18:06:21 2004 From: stani_ at hotmail.com (SM) Date: 1 May 2004 15:06:21 -0700 Subject: Best IDE? References: <9be5e130.0404160049.257ce8e1@posting.google.com> Message-ID: <99230dbb.0405011406.7f37c033@posting.google.com> Hi, Just to let you all know that there is a new version of SPE being developped with a much faster class/index/todo browser (can be even realtime!), wxPython 2.5 support, simultaneous view of source code, you can choose between MDI or SDI both with tabs, better control of calltips (only first paragraph or all doc) ... If you are curious, you can download it from http://projects.blender.org/projects/spe/ The windows XP version is already quite stable, for linux and mac os x, I'm dependent of other users. Stani hemanth_sethuram at yahoo.com (Hemanth P.S.) wrote in message news:<9be5e130.0404160049.257ce8e1 at posting.google.com>... > If you are looking for an IDE only for Python development, take a look > at SPE.(http://spe.pycs.net). It looks quite cool with PyCrust > integrated. > Here is the blurb from the site: > """ > Spe is a python IDE with wxGlade GUI designer, auto-indentation, auto > completion, call tips, syntax coloring, syntax highlighting, class > explorer, source index, auto todo list, sticky notes, integrated > pycrust shell, python file browser, recent file browser, drag&drop, > context help, ... Special is its blender support with a blender 3d > object browser and its ability to run interactively inside blender. > Spe is extensible with boa. > """ > > --Hemanth > > Josiah Carlson wrote in message news:... > > > This has prolly been asked 100 times - so please refrain from flaming if you can... > > > > > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > > > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > > > > > Thing is, I'm sure there is something better. Is there? > > > > Many people stick with the standard Python-included Idle. > > > > Others use their favored *nix editor on Windows (usually Emacs or VI(M)) > > > > Some have found they love SciTE. > > > > If you could get Eric3 running on Windows, it'd probably be /very/ nice. > > > > The editor component of Boa Constructor is pretty good (haven't used it > > in a while), but is a bit sluggish. > > > > SPE (Stani's Python Editor) is also pretty good, though can be slow at > > times, and uses MDI, which people usually love or hate. > > > > I use PyPE, find it to be a satisfactory replacement for Idle, and is > > quite fast. I wrote it, which is why I place it at the bottom. > > > > > > There are many other general text editors with some sort of Python > > support, but I don't use any of them, so I'll not talk about them. > > > > - Josiah From simon at brunningonline.net Fri May 7 05:28:08 2004 From: simon at brunningonline.net (Simon Brunning) Date: 7 May 2004 02:28:08 -0700 Subject: polymorphism w/out signatures? References: Message-ID: <314b29e9.0405070128.28de9ff6@posting.google.com> "Delaney, Timothy C (Timothy)" wrote in message news:... > A better approach anyway IMO for the above is to either always require > an iterable, or to accept a variable number of parameters i.e. > > def nuke (lang, *langs): # must have at least one parameter > nuke(lang1) > > for lang in langs > nuke(lang) > > I could of course have constructed a combined tuple, but that's silly. > > Then you can call the above as any of: > > nuke('Perl') > nuke('C++', 'Java', 'Perl') > nuke(*('C++', 'Java', 'Perl')) This is nice, Tim. But it only works if you don't need to pass in other stuff, too. I've used an approach like this many times: def setText(window, text, append=False): # Ensure that text is a list try: text + '' text = [text] except TypeError: pass ... rest of funtion, which can assume that 'text' is a list I prefer not to use type() - it's enough that text is string-like or list-like. Cheers, Simon B. From jepler at unpythonic.net Mon May 31 08:10:18 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 31 May 2004 07:10:18 -0500 Subject: exceptions In-Reply-To: References: Message-ID: <20040531121017.GB16742@unpythonic.net> Use "pass" as the body of the "except:" block. For example: def put(s, i, j): """Store j at s[i], or do nothing if s is not that long""" try: s[i] = j except IndexError: pass >>> l = [1, 2, 3] >>> put(l, 1, "hi") >>> put(l, 4, "bye") >>> l [1, 'hi', 3] 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 Mon May 31 08:19:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 May 2004 08:19:54 -0400 Subject: exceptions In-Reply-To: References: Message-ID: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Zunbeltz Izaola wrote: > I've the following problem with try/exception. > I've a try block that will raise some exceptions. > I want the program to ignore this exceptions completely. > Is it possible? In the following, all exceptions will be ignored: try: # something that raises exceptions except: pass This is definitely *not* a recommended way to write software, however. You should really understand what you are doing before writing code this way. -Peter From noamr at correctme.users.sourcephorge.net Fri May 21 12:18:40 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Fri, 21 May 2004 19:18:40 +0300 Subject: Python2.2 + mailbox. Bug???? In-Reply-To: <70c4ef5f.0405210756.187b7f07@posting.google.com> References: <70c4ef5f.0405210756.187b7f07@posting.google.com> Message-ID: hector wrote: > Hi > > This is my program: > > #!/usr/bin/python > import sys > from mailbox import PortableUnixMailbox > tmp = sys.stdin > mbox = PortableUnixMailbox(tmp) > mbox.next() > ... > ... > > When I execute: "./program.py < mboxfile.txt", there's no problem > > But, if I execute: "cat mboxfile.txt | program.py" ... too bad! > > the error: > > Traceback (most recent call last): > File "./prueba.py", line 8, in ? > mbox.next() > File "/usr/lib/python2.2/mailbox.py", line 23, in next > self.fp.seek(self.seekp) > IOError: [Errno 29] Illegal seek > > Why????? Thanks ALL!! Hello, I assume that when you write "./program.py < mboxfile.txt", Python knows that sys.stdin is a regular file, so it can do seek on it (for example, go back to its beginning). When you write "cat mboxfile.txt | program.py", the program cat outputs the file mboxfile.txt into sys.stdin byte by byte, so you can't do seek on it. Bye, Noam From peter at engcorp.com Wed May 5 15:47:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 May 2004 15:47:18 -0400 Subject: Improvement ? In-Reply-To: References: Message-ID: <-_SdnT1LNfnR2QTdRVn-jw@powergate.ca> Jean-Marc Ranger wrote: > With Python 2.3.3 for Windows, I understand why > os.makedirs("C:\SomeDirectoryThatDontExist\.\AnotherDirectory") fails > throwing an exception saying "OSError: [Errno 17] File exists" - the > period is like a request to create the same directory a second time. > > But is this the expected behavior ? I personaly would prefer to see > this operation succeed - and don't like the idea of writing a > workaround :) Wouldn't using os.path.normpath() on the string first be a really really easy workaround? -Peter From stephen.no at spam.theboulets.net.please Sat May 1 01:05:14 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Sat, 01 May 2004 00:05:14 -0500 Subject: silent raw_input for passwords References: Message-ID: Thanks! Heather Coppersmith wrote: > On Fri, 30 Apr 2004 21:26:40 -0500, > Stephen Boulet wrote: > >> I need a password for a script and I would like to not have it >> stored in a file or shown in a terminal. > >> "passphrase = raw_input()" still lets you see the input on the >> screen. Is there a way to have it be hidden? It's my gpg >> passphrase, so I don't want it anywhere except in my head. > > See the getpass module; it's part of the standard library. > > Most GUI's have similar functionality. > > HTH,, > Heather > -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From matthiasjanes at gmx.net Thu May 13 02:11:14 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 12 May 2004 23:11:14 -0700 Subject: Smalles Possible Browser to display python cgi program Message-ID: Dear everyone, I would like to know what would be the smalles possible WebBrowser for displaying Python CGI application. I developed a few small application with an WebInterface. The appplication runs just locally. I use CGIHTTPServer.py Module as a small webserver and Mozilla Firebird as Browser. Does anyone know of a very small browser which I can directly integrate. Just the very minimum for this purbose, no bookmarks, no tools, no javascript, no flash ...... just displaying frames, html, forms, python cgi files and images. Regards, Matthias Janes From devilwolf22 at hotmail.com Fri May 7 13:45:45 2004 From: devilwolf22 at hotmail.com (Steve Menard) Date: Fri, 07 May 2004 13:45:45 -0400 Subject: Debuggin a ptyhon extension In-Reply-To: References: <409ab831_3@127.0.0.1> Message-ID: <5_Pmc.73807$j11.882729@weber.videotron.net> Thomas Heller wrote: >>"Steve Menard" wrote in message >>news:rzxmc.26524$j11.254148 at weber.videotron.net... > > >>>I am writing a python extension module in VC++ on windows. At some >>>point, my extension crashes. >>> >>>Now I want to debug exactly why. I built the python projects in VC++, >>>and put the resulting python_d.exe in my ptyon home directory, and >>>the python23_d.dll in the windows/system32 directory. I also tried to >>>put the python23_d.dll in python's home directory, to the same >>>result. >>> >>>Problem is, running my scripts/extension with python_d.exe, it always >>>complains it can't find win32api. Yes, I am using win32API to preload >>>a dll, and can't really get rid of it. >>> > > > "Roger Upole" writes: > > >>It's probably looking for the debug version of win32api >>(win32api_d.pyd, which will also require a debug build of Pywintypes). >>You can grab the pywin32 source and roll your own debug binaries, or >>alternately you might be able to get away with creating a release >>build of Python that contains debug info. > > > If Steve only uses win32api to call LoadLibrary it is probably easier to > use ctypes for that. Of course he needs a debug version of ctypes, but > that should build out of the box from the sources, if he has VC. > > >>>Are my problems caused because python 2.3.3 (and possible win32all) were >>>build using VC.net? > > > No, python 2.3 and pywin32 (formerly called win32all) are built using > MSVC 6. > > Thomas > > thanks for your help guys. While I didnt manage to get pywin32 working with python_d, I wrote my own little library to do the loadLibrary, and that works. Thanks for the ctype hint though, I didnt know about it. Is it portable across platforms? Steve Menard From slawek at cs.lth.se Wed May 26 19:10:03 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Thu, 27 May 2004 01:10:03 +0200 Subject: Two questions about efficiency In-Reply-To: References: Message-ID: <20040527010348.780C.SLAWEK@cs.lth.se> On 26 May 2004 13:39:30 -0700 humean at fea.st (Steve M) wrote: #> I am interested in his claim that the second version is less #> efficient unless the requested key is "almost never" in the #> dictionary. I would have thought that the overhead to do a key #> lookup is quite a bit less than the overhead required to create an #> exception object, so that the first version would be on average #> more efficient only if the requested key is in the dictionary, say, #> more than half the time. #> Does the "key in dict" test internally raise an exception on #> failure, thus incurring at least the same overhead as the first #> version? Or is the overhead to raise an exception much less than I #> have naively supposed? #> I have a similar idiom buried in a nested loop, and I'd like to #> select the approach that is likely to be most efficient. My best #> guess is that the key lookup will fail half the time. I suggest: >>> import profile >>> p = profile.profiler() >>> def ver1(): ... # put version 1 here ... >>> def ver2(): ... # put version 2 here ... >>> p.run("ver1()").print_stats() >>> p.run("ver2()").print_stats() Do not forget to share the results :D -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) The Main Library at Indiana University sinks over an inch every year because when it was built, engineers failed to take into account the weight of all the books that would occupy the building. From aahz at pythoncraft.com Mon May 3 22:48:23 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 May 2004 22:48:23 -0400 Subject: fixedpoint cmp conundrum References: Message-ID: [BTW, please try to avoid using quoted-printable if at all possible] In article , Robert Brewer wrote: > >>>> a = fixedpoint.FixedPoint(3, 2) >>>> bunch = [None, 12, a] >>>> bunch.index(a) >Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\Lib\fixedpoint.py", line 316, in __cmp__ > xn, yn, p = _norm(self, other, FixedPoint=type(self)) > File "C:\Python23\Lib\fixedpoint.py", line 482, in _norm > y = FixedPoint(y, x.p) > File "C:\Python23\Lib\fixedpoint.py", line 255, in __init__ > raise TypeError("can't convert to FixedPoint: " + `value`) >TypeError: can't convert to FixedPoint: None > >Mmrph! I could fix this by: > >1. Iterating through "bunch" by hand and trapping TypeError, >2. Overriding or hacking the __cmp__ function in fixedpoint, or >3. Overriding or hacking the _norm function in fixedpoint > >The question is: given that there are multiple places to "fix" this, >where should I do so? http://fixedpoint.sourceforge.net/ with a patch using option 2. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From robin at reportlab.com Mon May 10 14:23:21 2004 From: robin at reportlab.com (Robin Becker) Date: Mon, 10 May 2004 19:23:21 +0100 Subject: bug in inspect (was cgitb vs traceback) In-Reply-To: <409F9B8B.60707@chamonix.reportlab.co.uk> References: <409F9B8B.60707@chamonix.reportlab.co.uk> Message-ID: <409FC899.9020604@chamonix.reportlab.co.uk> Robin Becker wrote: > def raise_an_error(): > a = 3 > b = 4 > c = 0 > try: > a = a/c > except: > import sys, cgitb, traceback, inspect > tbt,tbv,tb = sys.exc_info() > print 'traceback\n',''.join(traceback.format_exception(tbt,tbv,tb)) > print '\n\ncgitb\n',cgitb.text((tbt,tbv,tb),1) > > raise_an_error() > ..... the above script demonstrates a bug in the inspect module's getinnerframes function which is using the frame f_lineno instead of the traceback's tb_lineno. eg from inspect.py:getinnerframes we see that the traceback is followed and the frame only is passed to getframeinfo which then has to use frame.f_lineno. tb.tb_frame.f_lineno==tb.tb_lineno is not always true. What this means is that a wrong line of code can be cited for the error in the returned lines. A fix is to allow getframeinfo to have an optional lineno passed in which getinnerframes can set using tb.tb_lineno. If not set or None getframeinfo can use frame.f_lineno as before. def getframeinfo(frame, context=1): """Get information about a frame or traceback object. .......""" if istraceback(frame): frame = frame.tb_frame if not isframe(frame): raise TypeError('arg is not a frame or traceback object') filename = getsourcefile(frame) or getfile(frame) lineno = frame.f_lineno ....... def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist -- Robin Becker From andy at andybak.net Thu May 13 16:08:26 2004 From: andy at andybak.net (Andy Baker) Date: Thu, 13 May 2004 21:08:26 +0100 Subject: perl to python In-Reply-To: Message-ID: Here is a small feline amongst the pigeons... Surely support for regular expressions is 'un-pythonic'? The Python way would be to code regex's explicitly, surely? If you like regex's then any missing awk/sed functionality could be a Python module too? (If you don't like regex's and never use them in Python then you have earned the right to be consistent in your dismissal of awk and sed too!) > -----Original Message----- > From: python-list-bounces+andy=andybak.net at python.org > [mailto:python-list-bounces+andy=andybak.net at python.org] On > Behalf Of Heather Coppersmith > Sent: 13 May 2004 12:50 > To: python-list at python.org > Subject: Re: perl to python > > On 13 May 2004 08:37:00 +0300, > Ville Vainio wrote: > > > Because Python code is more readable and maintainable. That > is a huge > > win in multi-maintainer situations (which is typical in production > > code) ... > > Agreed. > > > ... You can also bump up the functionality of the script while > > porting, and get better reuse. > > That part makes me cringe. > > Port first. Make sure the new code still passes every *old* > test you can find. Write new tests against the current > functionality and the new code; porting inevitably leads to > new corner cases and language idiosyncrasies. > > Bump the functionality later. > > If I'm the manager and I hear, "feature X, which wasn't even > in the old code, is almost working; but featyre Y, which was > in the old code, seems to be broken," then heads will roll. > > Obviously, e.g., porting an OS from one hardware platform to > another (which I've done, more than once) will lead to > functionality changes, but there had better not be any > bumping until you know that the port is at least as solid as > the original. > > Most of the time, though, it's the other way around: you > find bugs in the old code due to the new scrutiny, but then > you have the nasty problem of determining whether or not > something else depends on the buggy behavior (but that's a > better topic for a new thread on another newsgroup). At that > point, bumping the functionality during the port could be > extremely troublesome. > > Regards, > Heather > > -- > Heather Coppersmith > That's not right; that's not even wrong. -- Wolfgang Pauli > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed May 26 12:04:27 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 May 2004 12:04:27 -0400 Subject: modifying mutable list elements in a for loop References: <9d5509fa.0405260439.175797e@posting.google.com> Message-ID: "Peter Ballard" wrote in message news:9d5509fa.0405260439.175797e at posting.google.com... > The python tutorial tells me "It is not safe to modify the sequence > being iterated over in the loop". What is not safe *in general* is adding and subtracting items to and from the list while traversing it, either directly or indirectly (via an index variable). There are exceptions, but they may or may not be implementation dependent (I would have to read the standard more closely to say more), and should only be used by people who understand them. What is safe is modifying or replacing the 'current' item. The former is easy. The latter requires the item index, as in 'for i in range(l): l[i] = f(l[i])' (in-place map) -- but here, the iteration list isnt the list being modified! (nor is it with enumerate()!) Terry J. Reedy From michele.simionato at poste.it Tue May 18 09:13:50 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 18 May 2004 06:13:50 -0700 Subject: where is Python Tools/scripts directory? References: <95aa1afa.0405142203.7dd64fad@posting.google.com> Message-ID: <95aa1afa.0405180513.72a9b384@posting.google.com> Skip Montanaro wrote in message news:... > Michele> Is there a simple way to get the path to the Python > Michele> Tools/scripts directory? > I'm not aware of a better way short of identifying those scripts of interest > and modifying setup.py to install them in $PREFIX/bin. In setup.py search > for "Tools/scripts" and modify the list. Feel free to submit a patch to SF > if you think those scripts would be of broader interest and ought to be > installed by default. > I just discovered that in my installation at work (which is a Debian distribution not managed by me) there is a copy of Tools/scripts in /usr/share/doc/python2.3/examples/Tools/scripts May I assume that this location is typical of Linux installations? Michele From jjl at pobox.com Mon May 24 15:24:34 2004 From: jjl at pobox.com (John J. Lee) Date: 24 May 2004 20:24:34 +0100 Subject: ANN: Pyrex wrapper for the Aspell API References: <40b1ff18_3@news.unc.edu> Message-ID: <87lljh1vd9.fsf@pobox.com> "Gary Bishop" writes: > http://prdownloads.sourceforge.net/uncpythontools/aspell-1.0.zip?download > > """A Pyrex wrapper for the aspell api. > > Pyrex is ****SO**** great! I wrote this in about 1 hour from the > Aspell doc. I spent most of that hour figuring out that I needed to > set the Aspell prefix to get it to work! [...] Be sure to let the aspell author, Kevin Atkinson, know about it. IIRC, he likes to know about these things. John From ahk at writeme.com Wed May 5 03:23:03 2004 From: ahk at writeme.com (ahk) Date: 5 May 2004 00:23:03 -0700 Subject: python/pyGtk : How to generate a keyboard interrupt? References: Message-ID: Yup.. Sorry that I didnt phrase my query more clearly. Is it possible to generate all those raw keystrokes w/o actually typing on the keyboard? Perhaps write to some keyboard buffer or something??? TIA From tjreedy at udel.edu Mon May 17 10:20:21 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 May 2004 10:20:21 -0400 Subject: benchmarks and questions for new python programmer References: <10agki14qhts2c2@corp.supernews.com> Message-ID: "stormslayer" wrote in message news:c5f75ecc.0405170409.59f8f54 at posting.google.com... > Thanks for all the help. Mike is correct -- the integer random number > gen from the math library isn't all that good and is causing the > slowdown. And thanks to Terry for math lib suggestions. You folks > are great. Thanks, your're welcome. > I got a bunch of emails Ignore them. Public posts should usually be reponded to publically -- or not at all. Dropping negative comments in your mailbox is nasty. Helpful comments should be public for the benefit of everyone. I'm glad Michael responed publicly and reminded me that some problems, like this one, have a better list initializer than the standard default None (so much for writing at 2 AM). > saying that one shouldn't benchmark languages > this way, or do so without knowing the language really well, or that > my code wasn't pythonish enough. There are occasional trolls who do a dippy 'benchmark', find Python lacking, and then post something to the effect that Python is 'bad'. You were benchmarking your ability to use three languages. When you found you ability with Python inadequate, you asked for help and got at least three good responses. > You folks need to wake up and smell the compilers (or interpreters). I presume 'you folks' refers to the private emailers ;-) > The whole point of a tool such as a > compiler or interpreter is to take reasonable code (and in this case, > my algorithm is certainly that -- the fault wasn't in my code but in a > python function) and generate reasonable program speeds. You are leaving out programmer speed, which is a large part of overall problem solution cost. Python is used by people who value their own time *and* who find programming in Python to be faster than in other languages, once a reasonable proficiency is obtained. Some whizzes in other languages never find the latter to be true, even after a fair trial, and so they properly stick with their other languages. The quality of implementation of various functions in various modules varies. Random.randint() is known to be slowish. I presume it could be made faster, but that is apparently not an itch of any of the current contributors. If you look at the code and see how, I presume a patch would be welcome, but you might ask first on the development list about undocumented rationales for the current implementation. > Sure, experts should be able to fiddle and get something more out of it, Here I think you are over-reacting to hitting a bad spot in the road, and perhaps forgetting what newbie C++ code can look like, and how much you have internalized expert fiddling in the languages you know better. > but the whole attraction of python for me is that it looks like pseudo code. Ditto, as I wrote at least 7 years ago. > If you can't write things the way you think, then it isn't much > help to use python. People who use Python do so at least in part because they find it better fits how they think than, for instance, C++. In any case, get it right, then make it faster if not fast enough. For some people, Python makes 'get it right' easier and faster. > It is still the case that unoptimized code in > borland's C++ is 5x faster than python (and that's for a windows > program w/ dialog boxes, etc. rather than a console app), and this is > distressing, Remembering when CPU time cost 50-100 times as much as programmer time, I once did too. If you focus on total clock time from start to finish, and on long term maintainability, you might find it less distressing ;-) If you use use Numerical Python, which wraps expert-written Linpack and FFT routines, among others, or Psyco (if you can -- it is CPU specific still), you migh find 5x less true. > but I'll keep trying w/ python. Python is beautiful... Be careful, or it might grow on you. Terry J. Reedy From __peter__ at web.de Thu May 27 16:08:00 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2004 22:08:00 +0200 Subject: remove item from list based on name References: Message-ID: Bart Nessux wrote: > I am generating a list of file names... some of the files are locked by > the OS (Windows XP) and I know the names of these files (NTUSER.DAT, > ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is > there a way that I can delete these items from the list based on their > names? >>> from sets import Set >>> list(Set(["a", "b", "c"]) - Set(["c", "d"])) ['a', 'b'] Remember to pass all filenames through os.path.normcase() before trying the above. Peter From daniel.dittmar at sap.com Wed May 12 11:46:42 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 12 May 2004 17:46:42 +0200 Subject: Can Python be compiled by a C++ compiler ? References: <40A242B8.30703@skynet.be> Message-ID: Helmut Jarausch wrote: > having read http://www.python.org/doc/current/ext/ext.html by Guido > van Rossum and Fred Drake, > I got the impression I should compile Python with g++ since section > 1.11 indicates that otherwise the constructor of a global or static > object (of an extension in C++) won't be called. > > Now trying to build Python (CVS version) with g++ fails. E.g., one You'll need to link Python using C++. This is necessary to include the C++ runtime. The individual .c files should be compiled with C. I believe that using C++ for the link step is even the default choosen by ./configure. Otherwise, extensions such as wxPython wouldn't work out of the box as they contain code written in C++. Daniel From matthiasjanes at gmx.net Thu May 13 02:02:37 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 12 May 2004 23:02:37 -0700 Subject: CGI Proplem displaying image References: Message-ID: > > > > BUT What I want is that I display the image on an HTML page with text > > together. > > > You should have a script (if you don't want to have two different scripts), > which would return an image or a page depending on its parameters, > something like http://your.site.net/cgi-bin/witty_page.py?action=page to return > """ > ...... Content-type: plain/text\n\n > ...... > ...... > """ > and http://your.site.net/cgi-bin/witty_page.py?action=image to return a picture. > > > sys.stdout.write( "Content-type: text/html\n\n" ) # yield html > > sys.stdout.write( "%s%s" % (style,title) ) > sys.stdout.write( "%s visits to %s" > "

%s%s%s
%s%s%s
\n" % (counter,name) ) > sys.stdout.write( "\n" > % ('Date','Time','IP') ) Thanks: does anyone knows if the CGIHTTPServer.py module can handle this kind of requests. Do I have to use the 'sys.stdout.write( something )' or is it also good enough to use 'print (something)' regards Matthias Janes From peter at engcorp.com Fri May 7 07:31:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 May 2004 07:31:59 -0400 Subject: printing float as formatted dollars In-Reply-To: References: Message-ID: Tim wrote: > "Larry Bates" wrote in message > news:YtqdnZOyj_KSfArdRVn_iw at comcast.com... > >>Here is a function I wrote and use. Note: floats >>have rounding "issues" when they get very large. [snip long code] >> > Thanks for the code!, it was a big help. I had started trying to piece > together some logic (below), but I know there are holes in it (negative > numbers, for one). [snip also long code] I still find this one much easier to swallow (from the aforementioned other thread). >>> import re >>> s = 1234567.89 >>> '$' + re.sub(r'(?<=\d)(?=(\d\d\d)+(\.|$))', ',', str(s)) '$1,234,567.89' -Peter From andy at andybak.net Sat May 15 15:12:10 2004 From: andy at andybak.net (Andy Baker) Date: Sat, 15 May 2004 20:12:10 +0100 Subject: Python vs. VBScript vs. JavaScript in context of Windows ScriptingHost? In-Reply-To: <051601c43aaf$07874590$210110ac@jsbwxp3> Message-ID: As far as I know all windows scripting host (WSH) languages are allowed to access the same object models so there shouldn't be any limitations on what you can do from Javascript. As a bonus I have found the MSDN documentation reasonable language neutral. Javascript is quite a tidy little language in some ways! > -----Original Message----- > From: python-list-bounces+andy=andybak.net at python.org > [mailto:python-list-bounces+andy=andybak.net at python.org] On > Behalf Of John Benson > Sent: 15 May 2004 20:01 > To: python-list at python.org > Subject: Python vs. VBScript vs. JavaScript in context of > Windows ScriptingHost? > > Hi, I'm in a tightly-secured environment where I may not be > allowed to use Python for some scripting work, and may have > to fall back on what came with Windows 2K. > > I'm cracking "VBScript in a Nutshell" from O'Reilly, and have > found a number of disappointments: > > * can't find "Introspection" in the Index > * no record types, just numerically-indexed arrays, so record > handling is kludgy > * zero-based array indexing (this is Basic?) > * script debugger is slanted towards debugging VBScript > inside Internet Explorer > * "on error resume next" pretty much sums up the error handling > * truly bizarre use of parentheses to override argument > passing by reference in a completely nonobvious context > > It looks pretty weak compared to Python, but I may not have > the luxury of Python in this situation. > > Here's the question: If JavaScript is available to me within > the Windows Scripting Host, can it do everything that > VBScript can? My JavaScript documentation (the O'Reilly rhino > book) is "client-side scripting"-centric, and as such accepts > the limitations on file manipulation imposed by the > client-side security scruples. Can anyone recommend a > reference on JavaScript as an expedient replacement for > Python within the context of the Windows Scripting Host? > > I know this isn't the real concern of this forum, but I know > there are a lot of experienced generalists out there whose > experience I would like to tap. > Thanks in advance for any responses. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From SeeBelow at SeeBelow.Nut Sun May 16 11:26:53 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sun, 16 May 2004 15:26:53 GMT Subject: Where do I find what colors and fonts are available? References: <40A3FD3E.B1B71DA8@shaw.ca> Message-ID: <40A7884F.320C8D4A@shaw.ca> Cousin Stanley wrote: > > On Thu, 13 May 2004 22:56:44 GMT, SeeBelow at SeeBelow.Nut wrote: > > > I'm learning Tkinter, from Grayson's book and some online sources. > > > > I don't know how to find out which color names and font names are > > available on my system. I'm using Windows 2000. I assume that info is > > in some file or files somewhere, buy I don't know the file name or > > directory. > > > > Thanks, > > > > Mitchell Timin > > Mitchell .... > > For a list of fonts in Tkinter, > you might try .... > > import Tkinter > import tkFont > > root = Tkinter.Tk() > > list_fonts = list( tkFont.families() ) > > list_fonts.sort() > > for this_family in list_fonts : > > print this_family > > For a list of colors in Tkinter > check the list at .... > > http://www.tcl.tk/man/tcl8.3/TkCmd/colors.htm > > -- > Cousin Stanley > Human Being > Phoenix, Arizona Thanks, Couz, that's very good info. m -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From stevewilliams at wwc.com Wed May 12 00:28:03 2004 From: stevewilliams at wwc.com (Steve Williams) Date: Wed, 12 May 2004 04:28:03 GMT Subject: How to read files written with COBOL In-Reply-To: <0Y6oc.47320$jI4.23568@newssvr29.news.prodigy.com> References: <0Y6oc.47320$jI4.23568@newssvr29.news.prodigy.com> Message-ID: asdf sdf wrote: > Steve Williams wrote: > >> I wrote an ETL system in python for a client to convert from >> Microfocus COBOL to DB2. Here are some of the problems I saw: >> >> 1) COBOL has a very rich set of datatypes defined by the PICTURE clause > > <...snipping various items...> > >> That is, I took the original COBOL 01 level definition and >> converted it to a list with definition parameters name, type, >> length, decimal point, etc. to make it easy for Python and >> to add some stuff to make DB2 happy (convert to title case. . .) > > Steve, > > I've been looking for ideas on getting at DB2 and Adabas from Python. > You might have some thoughts. > > Is it feasible to go to directly to MVS/DB2/Adabas from Python on Unix > or Win? > > Is it more realistic to hit DB2 on AIX or Linux and use some kind of DB2 > linking or replication to reach DB2/MVS? > > Other ideas? Maybe 3270 emulation with screen scraping? How about > telnet 3270? (Hundreds years of ago, I could dial into a command line > MVS environment.) > > I don't mean to hijack the thread. I think this is related and might be > helpful to unfortunates to have to interoperate with legacy systems. > > > > > > > Well, the application processed a lot of data on a nightly basis. It used FTP to connect to the COBOL machine (an AIX box) and FTP callbacks to sequentially read the files and convert the the data. There are two a bugs in the Python FTP module that surface if the file size is larger than 2 gig, but they're easily fixed. I developed this application on Windows, initially targeting a test DB2 database on Windows and then moving the DB2 database to AIX and posting with ODBC over the network from Windows. In the full production environment I moved the Python application to AIX. The moves were straightforward--Python was platform independent for my purposes. Initially I used ODBC or the API to post the data to DB2, but that turned out to be slow. To get the speed I needed, I just wrote the converted data to a CSV flat file and passed the file to the DB2 loader utilities. No matter how good your code is, you'll never outperform the database utilities. I've never used replication or linking. I know nothing about DB2 on MVS. In general, my experience with DB2 on networks (admittedly Unix and Windows boxes) tells me accessing DB2 on MVS over a network would not be a problem. I know nothing about ADABAS. Python will certainly do TELNET and screen scraping, but life is short. Other than the overall success of the project (I've been told successful data warehouse projects are rare) the major benefit of using Python was the ability to try new concepts quickly. With python you have enormous flexibility, as opposed to compiled languages (COBOL, C, etc) or third party ETL utilities. As an example, my application converted accounting data on a nightly basis. With no advance warning, the Accounting department converted to another package. The python code to extract and load the data from the new system was written and in production in 2 days. From jepler at unpythonic.net Tue May 25 22:57:08 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 May 2004 21:57:08 -0500 Subject: Cleaner idiom for text processing? In-Reply-To: References: Message-ID: <20040526025708.GC32066@unpythonic.net> I'd move the logic that turns the file into the form you want to process, under the assumption that you'll use this code from multiple places. def process_tokens(f): for line in infile: tokens = line.split() d = {} for i in range(0, len(tokens), 2): d[tokens[i]] = tokens[i+1] yield d Then, for d in process_tokens(infile): do_something_with_values(d['foo'], d['bar']) If the specific keys you want from each line are constant for the loop, have process_tokens yield those items in sequence: def process_tokens2(f, keys): for line in infile: tokens = line.split() d = {} for i in range(0, len(tokens), 2): d[tokens[i]] = tokens[i+1] yield [d[k] for k in keys] for foo, bar in process_tokens(infile, "foo", "bar"): do_something_with_values(foo, bar) Jeff From skip at pobox.com Tue May 4 13:09:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 May 2004 12:09:26 -0500 Subject: doctest: address in output In-Reply-To: References: Message-ID: <16535.52806.804997.427383@montanaro.dyndns.org> Param> Recently (30 minutes ago...) I need to write a doctring of the Param> following type: >>>> import mymodule >>>> mymodule.do_something() Param> Param> And I wanted to run doctest on this module. Now, I agree that Param> avoiding addresses in test output is a good thing in general; Param> but, in this case I wanted the '...' to match whatever address Param> the object happened to be at. [patch elided] Why not just change your doctest to be >>> import mymodule >>> isinstance(mymodule.do_something(), mymodule.coolObj) True ? That avoids two problems, the issue of addresses and the possibility that the repr() of your coolObj class changes. Skip From andymac at bullseye.apana.org.au Wed May 19 19:15:39 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 20 May 2004 09:15:39 +1000 (EST) Subject: Serious trouble with https (Python 2.2.3 & 2.3.3), How to check for working ssl? In-Reply-To: References: Message-ID: <20040520090040.H72700@bullseye.apana.org.au> On Wed, 19 May 2004, Phillip wrote: > My strong suspicion is that the socket stuff (dunno exact libname right > now...) is compiled without ssl support. > > What I would like to know now is following: > > > 1) What is the default setting for the compilation of the original > Python source? _With_or _without_ ssl support? The ssl support, on both 2.2.x and 2.3.x, is built via the setup.py script which gets run after the interpreter itself is built. If setup.py can find the SSL headers, it will attempt to build with SSL support. > I just downloaded the sources onto Debian Linux and did the configure, > make, make install dance. No fumbling on my side done here. > > Is there anybody I could ask who could know? Appart from bugging Guido > van Rossum over this that is. :-) You didn't inspect the logs from the make process? the output from setup.py towards the end will give clues as to whether SSL support was included. > 2) If this can't be said for shure _how_ can I find out if my version of > Python was compiled with ssl support? Apart from trying to connect via > https that is. Like I said: I've got a seriously growing suspicion that > it _is_ unsupported ssl due to compilation. For 2.3.x, there will be a _ssl.so to go with the _socket.so. There is no visible indication with 2.3.x. > 3) Where do I change the compile options (???), switches (???) - I don't > know how excactly this stuff is called - to set such stuff as what > things are compiled into the installation and which aren't. This is a > more general Linux/make/configure/gcc/whatnot sort of question, I know, > but I would be gratefull for any help. Build options for SSL support are in setup.py. Linux distros tend to "localise" anything and everything, so its not possible that setup.py is not finding the SSL headers because they're not where non-Debian people expect them to be. Added to the fact that Linux distros also seem to go overboard in separating "developer" bits (like header files) from "application bits". If you need the headers, you need to install the apropriate developer packages. I would have expected the Debian package of Python to have SSL support though, unless its an optional package... -- 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 jbperez808 at yahoo.com Fri May 28 03:41:56 2004 From: jbperez808 at yahoo.com (Jon Perez) Date: Fri, 28 May 2004 15:41:56 +0800 Subject: partial / wildcard string match in 'in' and 'list.index()' In-Reply-To: References: Message-ID: <2ho8clFeu0egU1@uni-berlin.de> Patrick Hall wrote: > Hi, > > >>For a given list: >>fruits=["apples","oranges","mangoes","bananas"] >> >>Is it possible to do wildcard matches like shown below? >>1. "man*" in fruits >>2. fruits.index("man*") >>3. "*nanas*" in fruits >>4. fruits.index("*nanas") > > I'm not sure if this is what you had in mind, but you can use list > comprehensions: > > fruits=["apples","oranges","mangoes","bananas"] > import re > 1. [fruit for fruit in fruits if re.match("man.*",fruit)] > 2. [fruits.index(fruit) for fruit in fruits if re.match("man.*",fruit)] > 3. [fruit for fruit in fruits if re.match(r".*an.*",fruit)] > 4. [fruits.index(fruit) for fruit in fruits if re.match("man*",fruit)] These would work, but I was wondering if there was some compact way to get 'in' and lists.index() to do wildcard matching as opposed to exact matching. From dmq at gain.com Sun May 30 19:42:44 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 30 May 2004 16:42:44 -0700 Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> Message-ID: <0dqkb09bc54jlo8m9aqcosei5p7olccvec@4ax.com> On 30 May 2004 10:51:44 GMT, Duncan Booth wrote: >David MacQuigg wrote in >news:qathb0ltkjpafa01ica9gdglnohptuuo3n at 4ax.com: > >>>Ok, I'll try and give you a couple of examples, feel free to tear them >>>apart. The most obvious one is to write factory methods: >> >> I like these examples, and I think they will fit nicely into the >> teaching sequence -- Spam and Foo, Animals_1, Animals_2, then some >> real programs. I would change the classmethods to staticmethods, >> however, and avoid the need to teach classmethods. This would make >> your calls look like: >> >> print Shape.fromCenterAndSize(Rectangle, 10, 10, 3, 4) >> -- or if you prefer a short alias -- >> print CS(Rectangle, 10, 10, 3, 4) >> > >So how do you handle the case where you need to override one of the factory >methods in a subclass? > >e.g. Rather contortedly: I'm not sure what this modification is intended to do, but assuming it must work with multiple subclasses of OffsetRectangle, I would write the example as follows: class OffsetRectangle(Rectangle): '''A rectangle where the 'center' is actually half way up the left edge''' def fromCenterAndSize(cls, cx, cy, width, height): self = cls() self.moveTo(cx+width/2.0, cy) self.resize(width, height) return self ## fromCenterAndSize = classmethod(fromCenterAndSize) frmCenterAndSize = staticmethod(fromCenterAndSize) class Rect1(OffsetRectangle): pass class Rect2(OffsetRectangle): pass class Rect3(OffsetRectangle): pass for cls in Rect1, Rect2, Rect3, Rectangle: print OffsetRectangle.fromCenterAndSize(cls, 5, 10, 10, 10) On the other hand, if you don't want to use the specific method from OffsetRectangle, but you want the method to be chosen from the same class as the class being instantiated, the last line would be: print cls.fromCenterAndSize(cls, 5, 10, 10, 10) I may be missing your intent. If so, maybe you could show a more complete example. -- Dave From ramen at lackingtalent.com Thu May 6 14:22:18 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 06 May 2004 18:22:18 -0000 Subject: MySQL vrs SQLite References: Message-ID: In article , Richie Hindle wrote: > > [Dave, quoting the SQLite docs] >> """SQLite is "typeless". This means that you can store any kind of data you >> want in any column of any table, regardless of the declared datatype of that >> column. (See the one exception to this rule in section 2.0 below.) This >> behavior is a feature, not a bug. A database is suppose to store and >> retrieve data and it should not matter to the database what format that data >> is in. The strong typing system found in most other SQL engines and codified >> in the SQL language spec is a misfeature - it is an example of the >> implementation showing through into the interface. SQLite seeks to overcome >> this misfeature by allowing you to store any kind of data into any kind of >> column and by allowing flexibility in the specification of datatypes.""" > > How about this? > > """Python containers (eg. lists, sets, tuples) are "typeless". This means > that you can store any kind of data you want in any container, without a > declared datatype for that container. This behavior is a feature, not a bug. > A container is suppose to store and retrieve data and it should not matter > to the container what format that data is in. The static typing systems > found in many other programming languages and codified in many language > specs is a misfeature - it is an example of the implementation showing > through into the interface. Python seeks to overcome this misfeature by > allowing you to store any kind of data into any container and by allowing > flexibility in the specification of datatypes.""" First of all, a minor nit: the word you want here is "supposed", not "suppose". =) Database relations are not generic containers. For a tuple to exist in a relation, it must satisfy a set of predicates that have been defined for that relation. These predicates include primary key, foreign key, and unique constraints. They also include (IMHO) the domains of the values for any particular column. A "typeless" database would limit the kinds of assertions I could make about a relation, and to me this is a misfeature. > See every third posting to comp.lang.python over the past ten years for why > this kind of thing may or may not be a good idea. Most of the arguments > that apply to dynamic typing in Python also apply to typelessness in > databases (the main one being: it's up to your unit tests, not anything > else, to make sure your program works). If Python's dynamic typing fits > your brain, it seems likely that a typeless database should do so too. I reject the claim that typing issues in programming languages are the same for databases. There are definite advantages to programming in dynamically typed languages like Python; most importantly, they are lean on syntax and don't get in your way like the popular statically typed languages. The main thing that makes programming in statically typed languages a pain is the amount of explicit type annotations and casts typically required to pull it off. This is more of a flaw in the respective type systems of these languages than with static typing in general. Languages in the ML family have shown that a type system can be out of your way (via type inference) yet still allow for compile-time checks. The "duck typing" concept that Python and Ruby programmers get so excited about can be accomplished using OCaml's objects because OCaml's type inference system is powerful enough to support this. Don't get me wrong; I love Python, and I love dynamically typed languages. There are still lots of things you can do in a dynamically typed language that would be difficult or impossible to accomplish in a statically typed language (without heavy use of reflection and dynamic casts, anyway). However, you simply cannot extend this issue to cover databases as well. For instance, SQL does type inference also. The only time you need to specify the types of data is when you declare your schema. The types of columns returned by queries are inferred by the database automatically. No explicit type annotations are necessary here. So, SQL does not suffer from my main pet peeve with statically typed languages, even inside of a "typeful" database. If the database has the expressiveness to make assertions about the data it contains, these assertions become assumptions to the programs that use the database. If you like simple, terse Python programs, you'll enjoy using a database that guarantees that your assertions were met, because these assertions do not need to be checked by your program. Databases may be shared by multiple programs written in multiple programming languages. How are you going to write a unit test to ensure that someone doesn't write a program in the future that sticks "hello" in a customer's age field? Put simply, if the database does not ensure that this will not happen, you'd better guard against this by using an int() cast and catching the ValueError exception, in which case you're basically back to type annotation. Your claims about types in database being a feature remind me of MySQL's earlier claims about why they didn't support foreign key constraints (if you write your code properly, you don't need them; they just get in the way). Now, you'll notice that they have thoroughly removed such claims from their documentation. I think it's fine if you want to have a typeless database. I was just advising the OP to take a look at his requirements and make sure that this is acceptable. Surely you don't expect him to assume that since he already uses Python, a dynamically typed (read: not *typeless*) language, he does not need to consider the repercussions that switching from MySQL to SQLite will have on his program, because of a few weak analogies and claims of brain-fitting? -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue May 25 02:26:31 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 25 May 2004 08:26:31 +0200 Subject: PyQt, main window can't have reference to application class In-Reply-To: References: <2hegkeFblripU1@uni-berlin.de> Message-ID: <2hg78nFc7ejmU1@uni-berlin.de> Phil Thompson schrieb: > On Monday 24 May 2004 3:54 pm, Sibylle Koczian wrote: > >>Still trying to learn PyQt from a book about several Python GUI >>toolkits, I seem to learn first what doesn't work. The following small >>script seems to work, but after closing the window I get the error >>message "Fatal Python error: PyEval_RestoreThread: NULL tstate". > > > You have created a circular reference which won't help. The problem doesn't > occur if PyQt is built with SIP v4 - it uses the newer Python thread API. > But the circular reference would remain, wouldn't it? I still don't see a way around it: the main window must know about the GUI independent methods of the application, and those methods should be able to exchange data with the main window. But I still want to keep the GUI independent things separate. > >>Without the line "self.app = app" the error goes away. So I suppose the >>main window can't have a reference to the application class. Right? >>Using the global variable qApp instead of self.app doesn't work either: >>qApp seems to be an instance of QApplication, not an instance of HelloApp. > > > It's the same C++ instance, but they are different types. knopftext is an > attribute of the HelloApp type. qApp is of type QApplication. > That's what I meant. 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 me at privacy.net Wed May 12 08:02:21 2004 From: me at privacy.net (Duncan Booth) Date: 12 May 2004 12:02:21 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> Message-ID: Antoon Pardon wrote in news:slrnca428q.1i9.apardon at trout.vub.ac.be: > IMO lacking an assignment that copies the value > of one object into another was a mistake and > which creats IMO a lot of difficulties. > > If I have a function with an object as a paramter. > and this object is mutable. Now within this function > I find a second object with the value I want the > argument to have. Now I can't simply copy the > second object over the argument but I have to > copy attribute by attribute from the second object > into the argument. Why wouldn't you just return the second value (or a copy of it) as a result from the function? That is usually a more flexible choice since it gives the caller the option of either replacing the original value or using the modified value somewhere different. Anyway, if you really need to do this then the mutable object should have some sort of updateState method which takes the second object as a parameter. That way the original object can have control over which attributes get overwritten and which don't. From sholden at holdenweb.com Fri May 28 07:51:41 2004 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 28 May 2004 07:51:41 -0400 Subject: pdf2txt In-Reply-To: References: Message-ID: LB wrote: >>I know that a txt2pdf exists, was checking to see if the opposite would >>as well. > > > I'm sure that from Acrobat you can save a .pdf as .rtf (that is text...). > Then it will be easy to do anything on it. > I remember also some utilities to "pdf2txt", try a search on google. > > LB > > Unfortunately the text you get from Acrobat, or most other transformations on PDF, won't guarantee any particular order of the elements. This will make pasing difficult, but if all your documents are similar you may get enough similarity from a text (not, IIRC, rich text) file from Acrobat. For extra marks you can use Acrobat's automation interfaces to actually convert the PDFs. Good luck! regards Steve From nelson at monkey.org Sun May 9 11:42:51 2004 From: nelson at monkey.org (Nelson Minar) Date: Sun, 09 May 2004 15:42:51 GMT Subject: urllib user agent? References: Message-ID: Michael writes: > How do you change the user agent reported by urllib? I need to access > a resource that rejects anything but IE. Here's how I do it in urllib2: req = urllib2.Request(url, None, {'User-agent': userAgent}) fp = urllib2.urlopen(req) Beware, some earlier versions of Python had bugs in the urllib* libraries where it may override your setting of user agent or other HTTP headers. This works fine for me in Python 2.3.3. From tim.golden at viacom-outdoor.co.uk Fri May 21 11:00:37 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 21 May 2004 16:00:37 +0100 Subject: Deleting Directories Message-ID: | This is probably a very basic question but I started learning | python. I | am almost done writing my delete directory script but I am at a stand | still right now. | I want to delete folders in my "/var/www/html/da" directory that are | over 1 day old. | | But, when I find the folder a simple rmdir() command does not work | because the directory is not empty. What else do I need to do | to delete | a directory that contains content? Well, it depends slightly on what you want to happen when you encounter a directory with stuff in, but the simplest answer is probably to use the shutil module and the rmtree function: import shutil shutil.rmtree ("c:/temp/abc1233") TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star Internet. 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 dlissett0 at yahoo.com Thu May 6 19:02:28 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 6 May 2004 16:02:28 -0700 Subject: Richards bench benchmark References: <6748553f.0403291446.27fb7b93@posting.google.com> <6748553f.0403300836.744e3e22@posting.google.com> <6748553f.0403302317.4595844@posting.google.com> <6748553f.0404060802.6e0d708c@posting.google.com> <6748553f.0404211342.7591cd8e@posting.google.com> <40899240.7020508@engcorp.com> <6748553f.0404241759.1f98a441@posting.google.com> Message-ID: <6748553f.0405061502.6f2cb03e@posting.google.com> Peter Hansen wrote in message news:... -snip- > I'll make a prediction: with an hour or two of work, any > good Python programmer can get a 10x speedup out of the > program. I don't know how meaningful it will be as a > benchmark at that point, but it is probably fair to compare > with the object-oriented versions which already violate the > original specification (e.g. the Java version, and the > Smalltalk ones Duncan mentioned). There are now separate pages for the Richards implementations that stick to the spec, and for the object-oriented variant. So the other languages shown with Python are solving the same problem in the same way. http://www.lissett.com/ben/bench3.htm From prudek at bvx.cz Fri May 21 14:04:40 2004 From: prudek at bvx.cz (Milos Prudek) Date: Fri, 21 May 2004 20:04:40 +0200 Subject: httplib set timeout Message-ID: <40AE44B8.7080806@bvx.cz> How can I set httplib timeout for httplib.request() ? httplib.request timeouts after 3:10 with "socket" timeout error message. I found socket.settimeout() and I believe there is a way to add ".settimeout()" function to httplib without hacking httplib source. Is it possible? -- Milos From fredrik at pythonware.com Tue May 25 03:14:57 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 09:14:57 +0200 Subject: terminological obscurity References: <1085210465.206473@yasure><1085248385.210031@yasure><51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com><1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: Arthur wrote: > And of course by making his shoes of the same data type and his sandal > example let's say say more challenging, he would have thereby > implicitly accepted the challenge of defending the wroding of his > edict, it all its subtlety. > > He chose not to, big time. > > The fact that others have accepted that challenge is welcome. > > That they choose to do so explicitly on his behalf, is - to me - > peculiar. replace tuples and lists with shoes and sandals, and this thread plays like a scene from the "the afterlife of brian, revisisted" documentary by cristopher guest. narrator: "when we meet him 40 years later, Arthur's still hasn't gotten over that shoe incident" flashback: http://bau2.uibk.ac.at/sg/python/Scripts/LifeOfBrian/brian-17.html From mark at hahnca.com Mon May 24 17:44:22 2004 From: mark at hahnca.com (Mark Hahn) Date: Mon, 24 May 2004 14:44:22 -0700 Subject: Prothon should not borrow Python strings! In-Reply-To: <40B2671B.5020308@prescod.net> Message-ID: <000201c441d8$4740d8b0$0b01a8c0@mark> > From: Paul Prescod > > I can recognize. But I'll give you as much guidance as I can. Wow, thanks, this is some really great stuff. I'm going to have to go off and study up on it. This may be a stupid question, but couldn't I have many "types" of strings and some be 8-bits, some 16-bits, and some 32-bits? Couldn't normal method overloading handle the type conversion? Why is there all this confusion? Isn't this what object-centric computing is designed for? From repettyBOGUS at austin.rr.com Sat May 1 02:05:26 2004 From: repettyBOGUS at austin.rr.com (Richard Petty) Date: Sat, 01 May 2004 06:05:26 GMT Subject: Replacing RPM with Source Install Message-ID: I've got a machine running Yellow Dog Linux (a PPC version of Red Hat) which has Python 1.5.2-35a and I'd like to update. I'd prefer to install from sources rather than depend on other people to release RPMs but I have a little question. My first instinct was to remove the RPM version of Python but I got a whole screenful of dependency warnings (see below). How should I proceed? Should I go ahead and yank the RPM-based Python and then compile/install the new version or should I try to keep both installations? --Richard [root at g3server ~] rpm -e python error: removing these packages would break dependencies: python = 1.5.2 is needed by python-devel-1.5.2-35a python >= 1.5.2 is needed by pygtk-0.6.8-3 python = 1.5.2 is needed by python-tools-1.5.2-35a python is needed by PyXML-0.6.5-4 python is needed by 4Suite-0.11-2 python = 1.5.2 is needed by tkinter-1.5.2-35a python >= 1.5.2-27 is needed by python-xmlrpc-1.5.1-7.x.3 python is needed by dateconfig-0.7.4-6 python is needed by mx-2.0.1-1 python is needed by postgresql-python-7.2-2a python >= 1.5.2 is needed by rpm-python-4.0.3-1.03a python >= 1.5.2 is needed by yup-0.7.6-8a python >= 1.5.2 is needed by apacheconf-0.8.1-1 python >= 1.5.2 is needed by bindconf-1.6.1-1 python is needed by fetchmailconf-5.9.0-11 python is needed by printconf-0.3.61-4.1 /usr/bin/python is needed by gettext-0.10.40-4 /usr/bin/python is needed by PyXML-0.6.5-4 /usr/bin/python is needed by 4Suite-0.11-2 /usr/bin/python is needed by alchemist-1.0.18-1 /usr/bin/python is needed by yup-0.7.6-8a /usr/bin/python is needed by gnome-core-1.4.0.4-38a /usr/bin/python is needed by bindconf-1.6.1-1 /usr/bin/python is needed by kdelibs-2.2.2-2a /usr/bin/python is needed by printconf-0.3.61-4.1 /usr/bin/python is needed by printconf-gui-0.3.61-4.1 From tdelaney at avaya.com Thu May 20 21:32:09 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 21 May 2004 11:32:09 +1000 Subject: Confused about while statement Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0180E0C0@au3010avexu1.global.avaya.com> EAS wrote: > In theory, the following code should ask for the user to enter a > value for h until he/she enters hello or goodbye. > > h = "hi" > while h != "hello" or "goodbye": > h = raw_input("Value for h:") > > But the program keeps asking for a value no matter what I enter. Why > doesn't it work? Because h is only being compared to "hello". The while line is being parsed as: while (h != "hello") or "goodbye": Every object in Python has a truth value - in the case of strings, an empty string is considered false and all others are considered true. So the above is effectively equivalent to: while (h != "hello") or True: which is always going to be true. There are two normal ways to write the condition you want: while (h != "hello") and (h != "goodbye"): or (more general - extends better): while h not in ("hello", "goodbye"): Tim Delaney From mahasamatman at nm.ru Sat May 8 10:35:48 2004 From: mahasamatman at nm.ru (Vladimir Ivanov) Date: Sat, 08 May 2004 17:35:48 +0300 Subject: Help me. How to open a new IE window? In-Reply-To: References: Message-ID: angel wrote: > Hi > > I want python(win32com) to open a new IE window. > Source is: > /******/ > import win32com.client > msie = win32com.client.Dispatch("InternetExplorer.Application") > msie.Visible = 1 > msie.Naviagte(http://www.python.org) > /******/ > The problem is the program always grabs a existed IExplorer window or > Explorer window. It never opens a new window. > > Please help me. Thanx > Victor > > > > > > import webbrowser webbrowser.open_new("www.python.org") it will work fine with IE (if IE is the default browser) From fgeiger at datec.at Tue May 18 11:58:19 2004 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 18 May 2004 17:58:19 +0200 Subject: OPC Server in Python References: Message-ID: "Ville Vainio" schrieb im Newsbeitrag > OPC is rather unpleasant. Systems that use OPC should rather use > CORBA, which is an open standard. Many people in automation industry > seem to be rather backward in the sense that they consider Windows, > COM and such things "standard" in some perverse fashion. Thanks for the hint, Ville! Kind regards Franz GEIGER From grante at visi.com Mon May 17 15:39:50 2004 From: grante at visi.com (Grant Edwards) Date: 17 May 2004 19:39:50 GMT Subject: bit shifting question References: Message-ID: On 2004-05-17, Michael Hudson wrote: >> My question is does python share java's peculiar mode of bit >> shifting, or does python adhere closer to c's bit shifting? > > The right shift in Python is arithmetic, i.e. preserves the > sign bit. Which one is the sign bit? IOW, how wide is a "word"? -- Grant Edwards grante Yow! LBJ, LBJ, how many at JOKES did you tell today??! visi.com From tor.iver.wilhelmsen at broadpark.no Mon May 24 12:45:27 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 24 May 2004 18:45:27 +0200 Subject: Passing parameters to functions References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: > 1. When I run it, Python gives me the following error message: > Syntax error. There's an error in your program: *** non-keyword arg > after keyword arg As the error message says: Keyword args (your m=2) need to go at the end. At least according to my copy of "Programming Python" chapter 8. From has.temp2 at virgin.net Fri May 21 10:33:18 2004 From: has.temp2 at virgin.net (has) Date: 21 May 2004 07:33:18 -0700 Subject: How do I create a dynamic wrapper for another language? References: Message-ID: <69cbbef2.0405210633.310835e4@posting.google.com> > Whitney Battestilli wrote: > > > I'm trying to embed python into an application that already contains a > > scripting language. This scripting language contains thousands of > > commands and I have the ability to query the script engine and get > > syntax information regarding valid arguments and such. > > > > Rather than writing explicate wrappers for each command (which will be > > very time consuming), I would like to extend python by creating a module > > that allows any function name to be executed with any number of keyword > > arguments.. I would then like to take the function name and keyword > > arguments and pass these to the apps script engine in the format required. > > > > Is there any way to do this or any way to do something like this? It's pretty easy using Python's introspection features to supply the syntactic sugar. Simple example: class _Callable: def __init__(self, name): self._name = name def __call__(self, **args): # [Do argument name checking, etc. here] # [Dispatch command here] print 'Sending command %r with arguments: %r' % (self._name, args) # TEST class Bridge: def __getattr__(self, name): # [Do command name checking here] return _Callable(name) bridge = Bridge() bridge.foo(bar=1, baz=True) # -> Sending command 'foo' with arguments {'baz': True, 'bar': 1} Also see my Python-to-Apple Event Manager bridge for ideas and/or code: http://freespace.virgin.net/hamish.sanderson/appscript.html From peter at engcorp.com Wed May 26 12:24:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 12:24:42 -0400 Subject: Adding your own site directories cleanly and supportedly? In-Reply-To: References: Message-ID: Tim Bradshaw wrote: > Ah, but. How do I add an application-specific site directory, and do > all the .pth file searching? It looks like I can call > site.addsitedir() to add a directory of my choosing, and this will all > work. This is all fine. > > The question is: is this the right way to do this? The documentation > for site doesn't describe any functions it exports, so I'm not sure if > I'm relying on something that might change or go away at some point. I think the comments at the top of site.py are often considered to be the _real_ documentation for that module. Note especially this one, at the end of those comments: '''After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary additional site-specific customizations. If this import fails with an ImportError exception, it is silently ignored. ''' In the past, I've done what you describe by including a sitecustomize.py in the application directory, and putting only these lines in it: import site site.addsitedir('.') Then include one or more local .pth files and you're set. Note that the code shown there works only if the current directory is the directory where the application code resides, but that was always the case in our code. You might need something other than '.' if that's not the case. -Peter From rechapman at hotmail.com Sun May 30 01:12:27 2004 From: rechapman at hotmail.com (Bob Chapman) Date: Sun, 30 May 2004 00:12:27 -0500 Subject: pywin32 201.1 Windows98SE Problem? References: <40b93ee2_5@127.0.0.1> Message-ID: > "Bob Chapman" wrote in message > news:c9aper$6os$1 at ngspool-d02.news.aol.com... > > On two different Windows 98SE Systems, I have attempted to upgrade working > > Python 2.3.3 and win32all installations to Python 2.3.4. After what > > appeared to be successful installations of Python-2.3.4.exe, I next > > executed: > > > > > pywin32-201.win32-py2.3.exe > > > > as downloaded from SourceForge, in the belief that it was the appropriate > > companion for Python-2.3.4 (perhaps this is my mistake?). In both cases, > > the installed Pythonwin outputs the following error messages and does NOT > > run: > > > > > File > > >"C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", > > line > > >163, in InitInstance > > > import interact > > > File > > >"C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\interact.py", > > line > > >26, in ? > > > import winout > > > File > > "C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\winout.py", > > >line 26, in ? > > > from pywintypes import UnicodeType > > > File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 69, > > in > > >? > > > __import_pywin32_system_module__("pywintypes", globals()) > > > File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 62, > > in > > >__import_pywin32_system_module__ > > > raise ImportError, "Can not locate " + filename > > >exceptions.ImportError: Can not locate pywintypes23.dll > > > > On checking, the NEW 'pywintypes23.dll' IS in c:\windows\system > > > > > 77824 May 28 11:10 c:\windows\system\pywintypes23.dll > > > > If this file is copied to C:\Windows then Pythonwin starts without the > error > > messages and appears to work. > > > > In previous Windows 98SE installations, the pythonwin dlls have worked OK > > from > > c:\windows\system where they are installed so I don't understand what's > > happening here? > > > > (Note: I've installed Python-2.3.4.exe and pywin32-201.win32-py2.3.exe on > a > > Windows XP sytem without this problem.) > > > > -- > > > > "Roger Upole" wrote in message news:40b93ee2_5 at 127.0.0.1... > One workaround is to copy pywintypes23.dll to your \windows directory. > http://sourceforge.net/tracker/index.php?func=detail&aid=917702&group_id=780 18&atid=551954 > > Roger > That's what I did but I was curious why this is required. Up to, at least, Build 163, win32all was able to start under Windows 98SE with pywintypes23.dll located in c:\windows\system (where it is installed). And, as previously mentioned, this work around is not required under Windows XP -- go figure. -- From klachemin at home.com Mon May 31 12:00:55 2004 From: klachemin at home.com (Kamilche) Date: 31 May 2004 09:00:55 -0700 Subject: How to list all functions in an imported module? References: <889cbba0.0405270506.3cd91d26@posting.google.com> Message-ID: <889cbba0.0405310800.63158bff@posting.google.com> Thanks guys. It DOES work, as you stated... my problem was I had a module called the same name as a variable I was using, yeesh. I'm used to C, where you have to declare variables before use, and the compiler catches stuff like this. I might have to go back to a Hungarian-like naming conventions for variables, it appears. --Kamilche From irmen at -nospam-remove-this-xs4all.nl Sat May 29 12:00:40 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 29 May 2004 18:00:40 +0200 Subject: Looking for a TCP/IP networking library/module/whatever ... In-Reply-To: <6c64de9a.0405290755.6a366d77@posting.google.com> References: <6c64de9a.0405290755.6a366d77@posting.google.com> Message-ID: <40b8b3a8$0$37789$e4fe514c@news.xs4all.nl> Storm wrote: > ... that I would like to use in a client/server application that would > : > > 1) detect reliably when connection is lost and try automatically to > reconnect to the server and the link is declared dead (i.e. the > client/server is notified) if only a reconnect was not possible for > 3-4 minutes > > 2) perhaps have the whole link encrypter, but I see this most as a > bonus > > Anyone knows if something like this exists ? Yes, it's called Pyro: http://pyro.sourceforge.net/ Pyro supports automatic reconnection, and SSL. As your bonus, so to speak, you get drastically simplified distributed application development. --Irmen From adonisv at REMTHISearthlink.net Sun May 30 16:46:36 2004 From: adonisv at REMTHISearthlink.net (Adonis) Date: Sun, 30 May 2004 20:46:36 GMT Subject: Question about exec() Message-ID: I wrote a small webserver and a small html parser to parse some elements, in which contain python code, now before I go any further your thinking "not another web application server" and before being routed to Twisted, Zope, Webware, Mod_Python, etc., this is a learning project, it is for my amusment and better understanding. Nevertheless, inside the html document I have python enclosed in tags, and it executes fine, but if I have a few of those tags I would like that prior executions stay in memory of the same document, instead of having to load X module everytime I wish to execute the code in the same document. To ellaborate further: (same document) Any help is greatly appreciated. Adonis From bstoyanov at dspace.de Tue May 4 07:34:08 2004 From: bstoyanov at dspace.de (questioner) Date: Tue, 04 May 2004 07:34:08 -0400 Subject: Processing content (extract cross-references) of MS Word Message-ID: <91b05f07036a8bb30893719a9523e54f@localhost.talkaboutprogramming.com> Hi everyone, I coudnt google anything about extracting/finding cross-references (in my case placed in table) in a MS Word file. Does anyone know how to get access to these word features? Best regards, From sean_berry at cox.net Thu May 13 20:58:14 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 13 May 2004 17:58:14 -0700 Subject: I need newbie help References: <10a83t8qku40d44@corp.supernews.com> Message-ID: "Joseph Davidson" wrote in message news:10a83t8qku40d44 at corp.supernews.com... > I am an experienced perl programmer learning python ( no commente please > ). > > In looking at a sample script at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708 > > I found the following code snippet. > -------------------------------------------------- > location = 'myHome' > fileLocation = {'myHome' :path1, > 'myOffice' :path2, > 'somewhere':path3}[location] > > ----------------------------------------------------- > fileLocation takes the 'value' of the 'key' "location" equilvalent to: location = 'myHome' files = {'myHome' :path1, 'myOffice' :path2, 'somewhere':path3} fileLocation = files[location] > It seems that this is setting up fileLocation as a dictionary, but what > is the "[location]" doing? > > Joe Davidson > > -- From detlev at die-offenbachs.de Sat May 8 05:07:25 2004 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 08 May 2004 11:07:25 +0200 Subject: ANN: eric3 3.4.2 released Message-ID: Hi, I just uploaded version 3.4.2 of eric3. This is mainly a bug fix release. It is available via http://www.die-offenbachs.de/detlev/files/eric-3.4.2.tar.gz What is it? ----------- eric3 is a Python IDE written in Python using PyQt and QScintilla. It has all the features one expects from a modern IDE. For details please see http://www.die-offenbachs.de/detlev/eric3.html Detlev -- Detlev Offenbach detlev at die-offenbachs.de From alvarof at freeshell.org Wed May 26 13:42:01 2004 From: alvarof at freeshell.org (Alvaro Figueiredo) Date: Wed, 26 May 2004 14:42:01 -0300 Subject: How do I read compressed (.Z) files In-Reply-To: <81D14648D6BD694CBDB4F45536E81CBC3FD085@aquarius.diversa.com> References: <81D14648D6BD694CBDB4F45536E81CBC3FD085@aquarius.diversa.com> Message-ID: <200405261442.01588.alvarof@freeshell.org> Em Qua 26 Mai 2004 14:29, Mark Wall escreveu: > If I have a UNIX compressed text file 'python.txt.Z' with > contents: "Python > " > > How do I read this data without uncompressing the file? > > Thank you, > Mark I am not sure, but the standard library module zlib may help you. If not, try something like: os.popen('zcat python.txt.Z') -- Alvaro Figueiredo alvarof at freeshell.org From fumanchu at amor.org Tue May 11 15:47:14 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 11 May 2004 12:47:14 -0700 Subject: Cash Register Message-ID: Ryan Q. wrote: > It works, i'm just posting it hoping someone could do better. > > print '' > print ' *** CASH REGISTER ***' > print ' PRESS 0 AND THEN ENTER TO TOTAL' > b = 1 > t = 0 > v = 0 > while b != 0: > a = 1 > s = 0 > print '' > while a != 0: > a = input(' ITEM $ ') > s = s + a > print ' TOTAL $',s > v = v + s > cash = input(' CASH $ ') > change = cash - s > print ' CHANGE $',change > print ' ' > print ' TOTAL SLAES $ ',v Some thoughts: 1. You never modify 'b'. So instead of 'b = 1' and 'while b != 0:', just say 'while True:'. 2. You really shouldn't use input()--it isn't safe. Use raw_input() and some value-coercion instead. 3. More-descriptive variable names would help others understand your code more easily and quickly; for example, use "subtotal" instead of "s". 4. Is there any difference between "print ''" and "print"? 5. Where does 't' get used? 6. You can write "s += a" instead of "s = s + a", if you like. I do. 7. Minor nit (as if they aren't all minor nits): abusing whitespace to line up arguments is frowned upon by Guido, according to PEP 8. 8. SLAES is misspelled. ;) Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From seefeld at sympatico.ca Tue May 18 14:48:46 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 18 May 2004 14:48:46 -0400 Subject: using the C API to access objects derived from builtin classes [Was: Re: error converting list to tuple] In-Reply-To: References: Message-ID: Terry Reedy wrote: > It is easy to mess up in C ;-). You are most likely to get an answer (from > another C extension writer) if you post a short as possible code snippet > that exhibits the error, and the actual and complete error message. I found the problem, and I'd like to share my new insight, as I don't think it is obvious: I hold an object reference that is a dictionary, and I modify it with the PyDict_* family of functions. However, the real object is not a builtin 'dict', but instead it is derived from it: class Dictionary(dict): ... I just realized that PyDict_SetItem (et al.) don't lookup the methods in the object's __dict__, so the method that gets really executed is not the overloaded I wrote, but the method from the base class. Replacing 'PyDict_SetItem' by 'PyObject_SetItem' did the trick. I guess 'PyDict_SetItem' is a shortcut to circumvent the lengthy method lookup. Fair enough, but the python C API documentation could be a bit more clear about that... Kind regards, Stefan PS: for the curious: the missing link between the dict and the list / tuple issue is that I derived my own dictionary precisely to be able to use a list as key. From me at privacy.net Mon May 24 03:33:23 2004 From: me at privacy.net (Duncan Booth) Date: 24 May 2004 07:33:23 GMT Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: Message-ID: "Neil Hodgson" wrote in news:vY8sc.6634$L.2827 at news-server.bigpond.net.au: > Technique 2: > > #define private public > #include > #undef private > > C c; > c.x = 1; > > In both of these it is obvious that the encapsulation rules are > being > broken which is exactly the same situation as when someone uses the > mangled name in Python. I have used technique 2 in production code > where a library could not be altered and access to private methods was > required. > To me, this is one of the greatest arguments against use of private variables in C++. I have also been reduced to using exactly this technique when faced with a library where the implementation was visible to the whole world, but the public interface didn't make enough of it accessible. I can think of numerous times when private names have been a real pain, but I have never had a problem which would have been solved by making a public name private. In C++ private doesn't hide the implementation at all, it simply restricts access. In Python, the __ prefix for private variables does some (rudimentary) hiding but doesn't really restrict access. In a language where the implementation can be hidden there may perhaps be reason to use private although defining the public part as an interface is a better way to go. Even in C++ you can use interfaces to hide the implementation, and for those (rare) cases where you need to get into the internals you may safely cast to the specific implementation and get at its internals (provided nobody used private) without having to resort to unsightly kludges. Sadly many C++ programmers fail to grasp this concept. From linux_python_lover at yahoo.com Sat May 1 12:42:24 2004 From: linux_python_lover at yahoo.com (Ali) Date: Sat, 1 May 2004 09:42:24 -0700 (PDT) Subject: lost sys.stderr Message-ID: <20040501164224.88740.qmail@web90108.mail.scd.yahoo.com> hello, ive tried to run Mozpython 0.1.1(source attached) on my i386 with Python 2.3.3 and Mozilla 1.6. While the program works perfectly well for windows , but when i try to run it on linux it gives me an error as "lost sys.stderr" I think the problem lies in the pythontohtmlconv module wherein the python script output is written mistakenly onto the standard o/p rather than the file. ny help is most welcome. Ali __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From mwh at python.net Fri May 7 12:19:03 2004 From: mwh at python.net (Michael Hudson) Date: Fri, 7 May 2004 16:19:03 GMT Subject: Interfaces in python References: <409a7bf9@news.broadpark.no> Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > Any links to good material related to interfaces in python would be > appreciated. Come to EuroPython! There are going to be several talks on this topic. Look here for a start: http://www.europython.org/conferences/epc2004/info/talks/acceptedTalksOverview Cheers, mwh -- I'm not particularly fond of singing GSTQ because she stands for some things I don't, but it's not really worth letting politics getting in the way of a good bawling. -- Dan Sheppard, ucam.chat From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat May 15 15:49:15 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 15 May 2004 20:49:15 +0100 Subject: bug in inspect (was cgitb vs traceback) In-Reply-To: References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> <40A5D206.3000901@jessikat.fsnet.co.uk> <40A5D94D.6010708@jessikat.fsnet.co.uk> Message-ID: <40A6743B.7050500@jessikat.fsnet.co.uk> Fernando Perez wrote: > Robin Becker wrote: > > >>Robin Becker wrote: >> >>..... >> >>>No I'll mosy on over and see if it's known. I have a fix in place in our >>>code, but we had to modify it yesterday as we're delivering for 2.1. >> >>I didn't find anything similar there so I submitted a bug report and the >>patch I used. I think it's far too late for 2.3.4. > > > Do you have the SF bug number handy? I'd like to track this one in detail, in > case it really is what is giving my ipython users problems. Push comes to > shove, I could always patch inspect.py 'live' for the users at import time, > that's the beauty of python :) > > Regards, > > f It's bug 954364. Your method is exactly what I did ie inject the patched functions into inspect at run time. Python may not be so easy to patch in future if altering other module's name spaces becomes harder. -- Robin Becker From fractalgfx at ameritech.net Thu May 27 14:07:28 2004 From: fractalgfx at ameritech.net (Michael Robinson) Date: Thu, 27 May 2004 18:07:28 GMT Subject: Sporadic problems importing xml.dom.minidom In-Reply-To: References: Message-ID: Michael Robinson wrote: > Sometimes when I run a program I get the message "Import:Error No Moduel > named dom.domino", sometimes it imports OK. It seems to depend on the > working directory when I star the program. > > /home/mike/projects/xml_test/test.py: > > Gives an erroor, the same file luanched from > > /home/mike/projects/xml1/test.py: > > runs without a problem > > I am running the python 2.3 package, bundeld with Fedora Core 2. I think i solved the problem. I had another file in those directorys called xml.py, I guess that was interfeering From user at domain.invalid Sun May 2 08:56:32 2004 From: user at domain.invalid (user at domain.invalid) Date: Sun, 02 May 2004 22:56:32 +1000 Subject: Pass a list to diffrerent variables. Message-ID: When trying to pass the contents from one list to another this happens: list = [1,2,3] list1 = list print list1 [1,2,3] list.append(7) print list1 [1,2,3,7] Whats the easiest way to pass the data in a list, not the pointer, to another variable From heikowu at ceosg.de Mon May 17 16:28:27 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 17 May 2004 22:28:27 +0200 Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: <200405172228.27449.heikowu@ceosg.de> Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks: > >>> locals().update(vars) From the documentation: """ locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ Heiko. From dave at pythonapocrypha.com Thu May 13 12:33:09 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 13 May 2004 10:33:09 -0600 Subject: classes vs dicts References: Message-ID: <035701c43907$fa9e5010$6600a8c0@YODA> David wrote: > My problem is similar, with the additional requirement that I need a > convenient way to access data deep within a hierarchy of parameters. > I chose classes over dictionaries because the syntax to access items > in a deeply nested dictionary is awkward. > > dict[window1][plot2][xaxis][label][font][size] = 12 > > vs > > statefiles.window1.plot2.xaxis.label.font.size = 12 > > The problem is I can't easily save the whole hierarchy to disk. > Pickle doesn't work with classes. Also, I worry about the overhead of > classes when I am just needing a simple container. A typical > statefile will have 1000 parameters in 300 classes nested up to ten > levels deep. As a structure of nested classes this takes about 74KB > on disk. Importing the file creates a .pyc file that is 157KB !! It > does seem to import quickly, however, so speed may not be a problem. > > Seems like Python could use a "container" structure which would be > like a class, but without the overhead and with the ability to > "pickle" the whole structure. Forgive me if I don't understand the problem, but why can't you just do: class Bag: def __init__(self, **kwargs): self.__dict__.update(kwargs) Then if your data is like: settings network ip = '10.20.30.40' port = 1234 logging level = 3 you would construct it by hand like: settings = Bag(network=Bag(ip='10.20.30.40', port=1234), logging=Bag(level=3)) and you can access members like: print settings.network.ip or settings.network.useSSL = 1 etc. and you can easily pickle _instances_ so persistence isn't really a problem: from cPickle import dumps, loads q = dumps(settings) newSettings = loads(q) Unless I'm misunderstanding the problem, the only remaining issue is the overhead. If that really is a problem (most likely not, but maybe if you're transferring it over a slow network connection or something), then simply use the built-in gzip or bz2 modules. -Dave From vineet at eswap.com Sat May 15 10:27:39 2004 From: vineet at eswap.com (Vineet Jain) Date: Sat, 15 May 2004 10:27:39 -0400 Subject: Help with large data set and fatal python error Message-ID: I'm running a process which uses python numeric arrays extensively and also does some calculations in c. All objects are created in python or through the Numeric library and then passed to the c routines. I'm dealing with very large sets of data. I'm getting the following exceptions in the early part of the program: Exception exceptions.AssertionError: in ignored ...and then after about at the 1060 iteration of the main processing loop I get the following error: Fatal Python error: deallocating None Questions: 1. Is there any way to catch this error and close my database connection so my uncommitted transactions get saved to the db 2. When I profile the larger dataset the .prof file does not get generated. Is there any way to incrementally build the .prof file 3. Any ideas what the errors means and how can I debug/catch them? vinj From fishboy at spamspamspam.com Mon May 31 07:44:00 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 31 May 2004 11:44:00 GMT Subject: binhex problem References: <40bb012e$0$136$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: On Mon, 31 May 2004 11:55:59 +0200, "MaximusBrood" wrote: >binhex.HexBin(file2, filename2) #translate hexed file 2 binary I think you meant binhex.hexbin(..) HexBin is a class inside Lib/binhex.py, which is why you're getting that __init__ error. hexbin() is the function to translate infile to outfile. ><{{{*> From ngps at netmemetic.com Mon May 31 20:59:29 2004 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 1 Jun 2004 00:59:29 GMT Subject: exceptions References: <40bb96e2$1@nntp0.pdx.net> Message-ID: According to Scott David Daniels : > Calvin Spealman wrote: > > ... > > Have to admit tho, a continue feature might be useful. Some languages have > > this, don't they? The thing is, Where exactly to continue? Should you retry > > whatever raised the exception, continue just after it, at the beginning of > > that line, or what? > > > See this older thread: > > > Xerox's experience (in deliberately removing the "continue from > exception" language feature) I found very instructive. Are the bugs mainly in the implementation of that feature, or in user code attempting to use said feature? (I notice the older thread was one year ago. Is this an annual topic? ;-) BTW, Common Lisp has this, called "restarts". There are about half a dozen Common Lisp implementations and none appear to have gotten restarts terribly wrong. Cheers. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Firewall Change Management & Version Control http://sandbox.rulemaker.net/ngps -+- ZServerSSL/Zope Windows Installers From bitbucket at safe-mail.net Fri May 7 04:49:45 2004 From: bitbucket at safe-mail.net (poiboy) Date: 7 May 2004 01:49:45 -0700 Subject: mod_python problem References: Message-ID: > Here is my server signature: > > Apache/2.0.48 (Unix) PHP/4.3.4 mod_python/3.0.3 Python/2.3.3 > mod_ssl/2.0.48 OpenSSL/0.9.7c Server at arwen.msnet Port 80 > > This is what I have in httpd.conf: > > LoadModule python_module libexec/apache2/mod_python.so > AddHandler mod_python .py > AddType applcation/x-http-python .py Try: AddHandler python-program .py The "AddHandler mod_python .py" version is intended to work with mod_python 3.1.3 and higher. Check out http://www.modpython.org/FAQ/faqw.py?req=all. For sympathy's sake, I've been using the manual released with 3.1.0a which also uses "AddHandler mod_python" and doesn't mention python-program at all. Aloha, the poiboy From skip at pobox.com Thu May 13 16:08:00 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 May 2004 15:08:00 -0500 Subject: PEP: import version In-Reply-To: References: Message-ID: <16547.54688.862968.98397@montanaro.dyndns.org> Chris> Skip Montanaro wrote: >> Somehow that version has to map to a different file being loaded, so >> it seems to me the proper place to record this information is in >> sys.path (or before the program runs, PYTHONPATH). Voila! No syntax >> changes required. Chris> This really needs to be done at runtime, not ahead of time with Chris> PYTHONPATH. Chris> We have been discussing this over at wxPython-users, Perhaps I'm missing something... If you need to futz around at runtime, futz around with sys.path. Can you summarize the wxPython discussions for those of us who don't use that toolkit (and have apparently never run into this problem in such an intractable way that we felt the need to change Python because of it)? In particular it would be helpful to understand why you don't know what version of wxPython you want to use before running the program. Thanks, Skip From __peter__ at web.de Thu May 27 15:51:38 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2004 21:51:38 +0200 Subject: Can someone help me with this bug? References: Message-ID: Duncan Smith wrote: > I'm probably missing something that should be obvious, but can > anyone tell me what's wrong with the following? > > temp.py > --------------------------------------------------------------------- > > class Item(object): > def __init__(self, id, data): > self.id = id > self.data = data > > > class KeyedSet(dict): > def __init__(self, items=None): > if items is not None: > for item in items: > self[item.id] = item > > def __iter__(self): > return self.itervalues() > > def __repr__(self): > return '%s(%r)' % (self.__class__.__name__, self.keys()) > > def __contains__(self, item): > return self.has_key(item.id) > > def intersection(self, other): > res = self.__class__() > for item in self: > if item in other: > res[item.id] = item > return res > > def __and__(self, other): > return self.intersection(other) > > def intersection_update(self, other): > self &= other > > def __iand__(self, other): > self = self.intersection(other) > return self > -------------------------------------------------------------------- > >>>> from temp import Item, KeyedSet >>>> a = Item(0, 'W') >>>> b = Item(1, 'X') >>>> c = Item(2, 'Y') >>>> d = Item(3, 'Z') >>>> aset = KeyedSet([a, b, c]) >>>> bset = KeyedSet([b, c, d]) >>>> aset &= bset >>>> aset > KeyedSet([1, 2]) >>>> aset = KeyedSet([a, b, c]) >>>> aset.intersection_update(bset) >>>> aset > KeyedSet([0, 1, 2]) >>>> > > I can't figure out why 'aset' is unchanged? Thanks. Your problem stripped down to the bare bones: __iand__() creates a new instance instead of modifying the current one. self = something doesn't copy something's data to self, it just rebinds self to something for the rest of the method. A minimal example of what went wrong: >>> class A: ... def __init__(self, value): ... self.value = value ... def __iand__(self, other): ... return A(self.value + other.value) ... def __repr__(self): ... return "value=%s" % self.value ... >>> a = b = A(1) >>> a &= A(2) It looks like inplace modification, but isn't: >>> a, b (value=3, value=1) a is rebound to the newly created instance, which tricks you into believing it was modified. The backup reference b reveals the error. Here's the correction (I'm lazy, so I reuse the unaltered parts of A): >>> class B(A): ... def __iand__(self, other): ... self.value += other.value ... return self ... >>> a = b = B(1) >>> a &= B(2) >>> a, b (value=3, value=3) Once you understand the basic principle, it should be no problem to apply it to your KeyedSet class. If in doubt, use the sets.Set implementation as a template. Peter From newsgroups at jhrothjr.com Thu May 20 14:56:57 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 20 May 2004 14:56:57 -0400 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: <10apvt23i03ek85@news.supernews.com> "Ivan Voras" wrote in message news:c8itrm$epg$1 at bagan.srce.hr... > Peter Otten wrote: > > > Skip Montanaro wrote: > > > > > >>Try > >> > >> u"".join(r) > >> > >>instead. I think the join operation is trying to convert the Unicode bits > >>in your list of strings to strings by encoding using the default codec, > >>which appears to be ASCII. > > > > > > This is bound to fail when the first non-ascii str occurs: > > Is there a way to change the default codec in a part of a program? > (Meaning that different parts of program deal with strings they know are > in a specific different code pages?) Does the encoding line (1st or second line of program) do this? I don't remember if it does or not - although I'd suspect not. Otherwise it seems like a reasonably straightforward function to write. John Roth > > > -- > C isn't that hard: void (*(*f[])())() defines f as an array of > unspecified size, of pointers to functions that return pointers to > functions that return void. From topmas38hotmailcom Sun May 30 08:16:27 2004 From: topmas38hotmailcom (MaximusBrood ({[AT]} {[DOT]})) Date: Sun, 30 May 2004 14:16:27 +0200 Subject: Hexbin Message-ID: <40ba1ca5$0$119$3a628fcd@reader3.nntp.hccnet.nl> Hi, Im a newcomer to Python and I've got some error that I totaly dont understand. I've made a program that is made to extract a couple of binhex files. Here is my sourccode: import binhex, os current = os.getcwd() #Gets current cwd files = os.path.join(current, "files") #joins current path with path files for filename in os.listdir(files): #checks every file in DIR: files os.chdir(files) #changes dir 2 files file2 = win32file.CreateFile(filename, win32file.GENERIC_READ, \ 0, None, win32file.OPEN_EXISTING, 0, None ) #opens hexbin file filename2 = filename+".exe" #changes filename to .exe extention binhex.HexBin(file2, filename2) #translate hexed file 2 binary If I run this one, an exeption is raised: Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 407, in ImportFile exec codeObj in __main__.__dict__ File "", line 1, in ? File "C:\WINDOWS\temp123\Stuf\all2.py", line 9, in ? binhex.HexBin(file2, filename2) #translate hexed file 2 binary TypeError: __init__() takes exactly 2 arguments (3 given) I've got only 2 arguments, but python thinks I've got there 3... Can anybody help me? (maybe its a stupid question but i'm only a newbie =) ) I'm running on Win XP Home From lbates at swamisoft.com Fri May 21 19:05:13 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 21 May 2004 18:05:13 -0500 Subject: Passing options between modules References: <939f49f8.0405210907.4f12a613@posting.google.com> Message-ID: <99idnVQ7XNy0FjPdRVn-tw@comcast.com> One suggestion would be: Create small class, something like: class globaloptions: pass Then assign your options to attributes of this class: globaloptions.option1=value globaloptions.option2=value ... globaloptions.optionn=value Then pass globaloptions class to everyone else: a=Aclass(opt1, opt2, globaloptions) bFunction(globaloptions) ... Larry Bates Syscon, Inc. "Chris" wrote in message news:939f49f8.0405210907.4f12a613 at posting.google.com... > I'm trying to come up with a not-so-ugly manner of passing many > command-line options between modules. > > I have a Steering.py file, which contains my main() and handles the > getopts getting of several command-line options. Since having 5-6 > additional parameters for every class instantiation or function call > is obviously an ugly way to handle this, what would you folks > recommend as a superior option? Maybe passing a dict of options to > each object/function? > > Help on this topic is greatly appreciated. > > Go Sox, > -cjl From Mike at DeleteThis.Geary.com Wed May 26 13:18:07 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 26 May 2004 10:18:07 -0700 Subject: re best way to enumerate something in Python References: Message-ID: <10b9kago5tehbc1@corp.supernews.com> David Stockwell wrote: > I'm going to try using the range function. > > as in: > > ID_COL, ANIMAL_COL, HOUSING_COL = range(3) > > This appears to assign assign those vars as 'constants' with values of 0,1,2 Yes, this is exactly the same as if you'd written: ID_COL = 0 ANIMAL_COL = 1 HOUSING_COL = 2 Earlier in the thread you asked: > In the os.stat there is aparrently a list of things you can refer to eg: > ST_SIZE, ST_ATIME, etc. > > How are these defined? They appear to be related to 0,1,2,3,.... some > sort of enumeration. It's easy to answer a question like that by searching the Python installation directory (at least if the names are defined in Python source code, not C code). You can either do a search, or since these are defined in the stat module (not os.stat), you can look in stat.py, where you'll find: # Indices for stat struct members in tuple returned by os.stat() ST_MODE = 0 ST_INO = 1 ST_DEV = 2 ST_NLINK = 3 ST_UID = 4 ST_GID = 5 ST_SIZE = 6 ST_ATIME = 7 ST_MTIME = 8 ST_CTIME = 9 -Mike From romanschlegel at hotmail.com Mon May 10 10:32:10 2004 From: romanschlegel at hotmail.com (Roman Schlegel) Date: 10 May 2004 07:32:10 -0700 Subject: cvs2svn.py can't access cvs db References: Message-ID: I found the problem. :-) romanschlegel at hotmail.com (Roman Schlegel) wrote in message news:... ... > line 293, in hashopen > d.open(file, db.DB_HASH, flags, mode) > bsddb._db.DBInvalidArgError: (22, 'Invalid argument -- DB_TRUNCATE > illegal with locking specified') > ... This is caused by a minor version conflict of the Python Bindings (bsddb3-4.2.4) and the Berkeley DB itself (db-4.2.52)! The change log of Berkeley DB 4.2.52 says "9. Fix a bug to now disallow DB_TRUNCATE on opens in locking environments, since we cannot prevent race conditions. In the absence of locking and transactions, DB_TRUNCATE will truncate ANY file for which the user has appropriate permissions. [#7345]". I believe the module dbshelve.py of the pybsddb tries with "open" in mode 'n' exactly this disallowed truncate. There are two possible ways to solve the problem: Solution One: Download an older Version of the Berkeley DB and install everything again. Solution Two (the short way): just don't use mode 'n' to open a db. This can be avoided easily in the script cvs2svn.py at line 188: replace the variable "mode" with the constant "'c'": 187 class Database: 188 def __init__(self, filename, 'c'): #mode): 189 self.db = anydbm.open(filename, mode) From newsgroups at jhrothjr.com Thu May 6 12:53:20 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 6 May 2004 12:53:20 -0400 Subject: Private identifiers - naming References: <930ba99a.0405060600.17e076bc@posting.google.com> Message-ID: <109krdf7s8mm1ff@news.supernews.com> "Sridhar R" wrote in message news:930ba99a.0405060600.17e076bc at posting.google.com... > In python, to hide (from direct access) identifiers from outsiders > (not current module), we usually prefix the variables with '__'. > > But this is usually _difficult_ to read. Imagine a module (which is a > common one) containing more private variables than public variables. > > How cryptic it would be to see text with lot of __ in front of them !! > > Any thoughts? The double underscore triggers name mangling, while a single underscore is more of a hint that this variable is protected (rather than private.) My take on it is that if you have that many private variables, maybe the class is too big and needs to be split into several classes with clearer responsibilities. There is also a school of thought that says that classes ought to contain more private members than public ones, some being more than none. I don't subscribe to it, but it's part of the landscape. John Roth From russblau at hotmail.com Thu May 27 15:11:57 2004 From: russblau at hotmail.com (Russell Blau) Date: Thu, 27 May 2004 15:11:57 -0400 Subject: remove item from list based on name References: Message-ID: <2hmss0FehkoqU1@uni-berlin.de> "Bart Nessux" wrote in message news:c95e2g$nm2$1 at solaris.cc.vt.edu... > Hi, > > I am generating a list of file names... some of the files are locked by > the OS (Windows XP) and I know the names of these files (NTUSER.DAT, > ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is > there a way that I can delete these items from the list based on their > names? Have you tried this? for name in systemfiles: filelist.remove(name) -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From dmq at gain.com Mon May 24 19:01:32 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 16:01:32 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <2hd4ufFbgv5oU1@uni-berlin.de> Message-ID: On Mon, 24 May 2004 14:28:28 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> On Sat, 22 May 2004 12:10:51 -0600, "Dave Brueck" >>>But the above explanation misses one very important point: one is used 99.9% of >>>the time, the other 0.1% of the time, if that. >> >> I can't comment on the usage statistics you cite, but it seems to me >> that unbound methods are more important than these statistics would >> imply. ... Learning Python also treats unbound methods as >> much more "normal" than your argument would imply. > >The only time you really need to deal with unbound methods >is when making super calls, and that accounts for maybe >1% or less of all method calls in the code I write. > >I haven't seen what Learning Python says about unbound >methods, but if it puts any more emphasis on them than >this, it's putting too much emphasis on them. It's about 2% if you just count pages. The problem with just counting pages or number of calls is that doesn't tell you whether those few calls are really important, or just a little sugar for something that could be done with more normal methods. If you want to count something, I would say the percentage of programs which make use of a particular feature is more meaningful than the number of times it is used in the program. You still have the problem of finding a representative sample of programs. Even the Python libraries would give you skewed stats if you are looking at a new feature. The number of 'global' statements is probably less than 1% of all lines of code ( just guessing ), but I don't think anyone would assume they are unimportant. >> Sure, we could move the load function >> outside of the Bag class, but that would disrupt the natural structure >> of the program. The load function is unique to Bags, and it belongs >> in the Bag class. > >The Pythonic way to handle this is to create a module >to hold the Bag class and any functions related to it, >e.g. > > # module bags > > class Bag: > ... > > def load(infile): > ... > > # in some other module > import bags > my_bag = bags.load("my_settings.ini") I would rather not use modules to package individual classes just because we are trying to avoid static methods. I'm using modules for a much larger grouping of classes and data (e.g. everything related to a particular simulator or display tool). Much easier to just add the staticmethod line wherever needed, and be done with it. >> Seems like my challenging statement was misleading. I have no >> intention of bringing up strange binding problems in an introductory >> class. This was a challenge to those who think that Python's binding >> syntax is simple. > >But seeing as your example did something you're not meant to >be doing in the first place, I don't see how any conclusions >can be drawn from it about simplicity or complexity in >everyday programming. How can we say that this little snippet wasn't distilled from a larger program in which the structure makes sense? I've posted this question in the thread from which the example came, since this appears to be an important question to many in this thread, and only the OP knows for sure if it was something real or just an attempt to throw a curve ball using Python's binding syntax. My only conclusion is that even wierd examples like this are no problem with a simpler syntax. A good language has a simple syntax that is so versatile, you can put things together in many unanticipated ways, and they work exactly as you would expect. In my original solution to the statefile problem, I had classes nested ten levels deep -- no methods, just "bags" of data. It started the expert I was working with, but it worked surprisingly well. Simple, versatile building blocks is what I like about Python. I can figure out the high-level stuff myself. I don't need somebody's "design pattern". -- Dave From jjl at pobox.com Thu May 27 18:49:36 2004 From: jjl at pobox.com (John J. Lee) Date: 27 May 2004 23:49:36 +0100 Subject: jython 2 cpython bridge References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> Message-ID: <87lljdiiyn.fsf@pobox.com> Steve Menard writes: [...] > Alternately, you can look at JPype ( http://jpype.sourceforge.net ). > > It is still a very early release, but I would welcome any feeback. And > version 0.1 should allow you to use JDBC without problem. > > It currently only works on Windows, but if there is interest, I could > make a linux release pretty quickly. I assume you've seen JPE? How does / will JPype differ from that? I *think* JPE hasn't been maintained for quite a while, but I'm not certain what its current state is. John From loic at fejoz.net Wed May 26 11:09:18 2004 From: loic at fejoz.net (Yermat) Date: Wed, 26 May 2004 17:09:18 +0200 Subject: re best way to enumerate something in Python In-Reply-To: References: Message-ID: David Stockwell wrote: > I'm going to try using the range function. > > as in: > > ID_COL, ANIMAL_COL, HOUSING_COL = range(3) > > This appears to assign assign those vars as 'constants' with values of > 0,1,2 You should get an eye on http://www.python.org/cgi-bin/moinmoin/EnumerationProgramming It may give you some ideas... -- Yermat From noemail at noemail4u.com Mon May 10 08:22:04 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Mon, 10 May 2004 12:22:04 GMT Subject: classes vs dicts References: <409b9a3f_5@newsfeed.slurp.net> Message-ID: On Fri, 07 May 2004 10:15:11 -0400, Steven Rumbalski wrote: >Daniel 'Dang' Griffith wrote: > >> On 06 May 2004 07:22:05 -0400, Heather Coppersmith >> wrote: >> ... >>>In the end (and in the implementation), classes are just syntactic >>>sugar for dictionaries. >>> >>> object.attribute is equiv. to dictionary[ 'key' ] >> >> I think you're overgeneralizing, or I'm reading overgenerality into >> your response. I assume you mean that manipulating an instance of a >> class attribute is syntactic sugar for manipulating a single >> dictionary entry? >> >> You can't arbitrarily add or remove attributes to an instance of a >> class (without using "magic", which kinda puts a major sour in the >> syntactic sugar!). Classes are not syntactic sugar for dictionaries. >> --dang > >>>> class Foo: >... def __init__(self): >... self.x = 'x' >... self.y = 'y' >... >>>> foo = Foo() >>>> foo.x, foo.y >('x', 'y') >>>> dir(foo) >['__doc__', '__init__', '__module__', 'x', 'y'] >>>> foo.z = 'zeeeeee' >>>> del foo.x >>>> foo.y, foo.z >('y', 'zeeeeee') >>>> dir(foo) >['__doc__', '__init__', '__module__', 'y', 'z'] > > >I'm not sure what you mean by magic. I just used basic python to >"arbitrarily add or remove attributes to an instance". > >You can even muck around with classes: > >>>> def new_init(self): >... self.a = 1 >... self.b = 2 >... >>>> Foo.__init__ = new_init >>>> bar = Foo() >>>> bar.a, bar.b >(1, 2) >>>> dir(bar) >['__doc__', '__init__', '__module__', 'a', 'b'] Yes, you're right. I mis-spoke what I meant. Maybe this is closer, "You can't add or remove arbitrary attributes to an instance of a class... without magic." What I mean is that with a dictionary, the keys can come from external/arbitrary data and be added to the dictionary with a simple assignment: d = dict() k, v = raw_input(), raw_input() d[k] = v w = d[k] You can't do that to classes or instances without some kind of magic. class Foo: pass foo = Foo() k, v = raw_input(), raw_input() setattr(foo, k, v) w = getattr(foo, k) Maybe its just me, but I consider getattr/setattr magic (although in this simple example, they don't appear too magical, so maybe others wouldn't consider it so). Still, I think it is an overgeneralization to say that classes are just syntactic sugar for dictionaries. --dang From klappnase at web.de Fri May 7 07:12:06 2004 From: klappnase at web.de (klappnase) Date: 7 May 2004 04:12:06 -0700 Subject: How to change tkinter GUI look-and-feel? References: Message-ID: Jonathon McKitrick wrote in message news:... > I saw some screenshots of mayavi. Is there any way we can set tkinter to > use the motif (or some other toolkit under Unix) rather than the default? > > jm Hi Jonathon, you cannot make Tkinter use another toolkit (of course); if you mean just to change the look and feel you can use the tk_strictMotif() method to get a quite "native" motif look and feel: from Tkinter import * root = Tk() root.tk_strictMotif() or use an optionDB file if you just want to do an application wide change of tk's sometimes ugly defaults on unix: from Tkinter import * root = Tk() root.option_readfile(path-to-your-optionDB) The contents of the optionDB may look like this: ########-file optionDB-############################## *font : Helvetica -12 *Entry*background : white *Listbox*background : white *Listbox*exportSelection : 0 *selectBackground : #a0a *selectForeground : white *Scrollbar*Width : 12 *Scrollbar*troughColor : #aaa *Scrollbar*takeFocus : 0 *Checkbutton*selectColor : green *Radiobutton*selectColor : green *Menu*tearOff : 0 *Menu*relief : ridge *Menu*borderWidth : 2 *Button*Width : 10 ###################################################### That's an optionDB I've been using, I think you'll see the point how to change the default values of configuration options for different widgets. I hope this helps Michael From donn at u.washington.edu Thu May 6 14:48:08 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 06 May 2004 11:48:08 -0700 Subject: classes vs dicts References: <7id65haegq.fsf@enark.csis.hku.hk> Message-ID: In article <7id65haegq.fsf at enark.csis.hku.hk>, Isaac To wrote: > >>>>> "Charlie" == Charlie writes: > > Charlie> Greetings, I am pretty new to Python and like it very much, but > Charlie> there is one thing I can't figure out and I couldn't really > Charlie> find anything in the docs that addresses this. > > Charlie> Say I want to write an address book program, what is the best > Charlie> way to define a person (and the like): create a class (as I > Charlie> would do in Java) or use a dictionary? I guess using > Charlie> dictionaries is fastest and easiest, but is this recommended? > > I read the answers already in the list, which are rather unidirectional: all > advocate for classes. But I'm unconvinced. I still believe that there is > no clear-cut winner, and what you should do dopend on how you view the > person. > > If you want to associate actions to the person, say associate two persons in > some way; and you want to create various types of persons (subclass it) such > that each of them have different behaviour, then the extra complexity added > by representing the person as a class will definitely pay off. > > But, on the other hand, if your application simply treat the person as some > data, turning every access of the person into a getter or a setter or even a > combination will only make code more clumsy and harder to write. I agree - for plain data, use a plain data structure. One advantage, beside just the obviousness of it all, is that your data structure will support data structure operations, like iteration for example. Donn Cave, donn at u.washington.edu From ville at spammers.com Fri May 14 01:35:06 2004 From: ville at spammers.com (Ville Vainio) Date: 14 May 2004 08:35:06 +0300 Subject: perl to python References: Message-ID: >>>>> "Andy" == Andy Baker writes: Andy> Here is a small feline amongst the pigeons... Surely Andy> support for regular expressions is 'un-pythonic'? Of course it isn't. Andy> If you like regex's then any missing awk/sed functionality Andy> could be a Python module too? Indeed. Now we just need to know what the missing functionality is. What is easy in awk or sed and hard in Python? Regexps, at least, are arguably *better* in Python. Andy> (If you don't like regex's and never use them in Python then Andy> you have earned the right to be consistent in your dismissal Andy> of awk and sed too!) I don't really understand what you are saying. I just don't see the point in awk and sed. If implementing something in a general purpose language takes 20% longer than doing the same thing in a specialized language, and there exists even a remote possiblity of having to extend/reuse the solution, I wouldn't give the special purpose language a second thought. -- Ville Vainio http://tinyurl.com/2prnb From tdelaney at avaya.com Mon May 24 04:12:35 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 24 May 2004 18:12:35 +1000 Subject: iterator expression - please explain Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0187FCD0@au3010avexu1.global.avaya.com> Erik Max Francis wrote: > Helmut Jarausch wrote: > >> myfun(x^2 for x in xrange(10)) > ... >> I expected the sequence 0,1,4,9,.... >> What am I missing and what's going on here? > > ^ is the bitwise xor operator. You wanted **. (Although what you > wrote above isn't legal anyway.) Note that Helmut is using 2.4 - that's a valid generator expression in the function call. Tim Delaney From svein+usenet01 at brage.info Tue May 18 05:56:37 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Tue, 18 May 2004 11:56:37 +0200 Subject: Python compilers? References: Message-ID: Leif K-Brooks wrote: > Svein Ove Aas wrote: >> Is anyone working on a python-to-native compiler? >> I'd be interested in taking a look. > > What are you trying to achieve? > > If it's faster code execution, the primary slowdown with a very > high-level language like Python is caused by high-level data structures > (introspection, everything being an object, etc.), not the code itself. > A native compiler would still have to use high-level data structures to > work with all Python code, so the speed increase wouldn't be very much. I'd like to point out the usual suspects: Lisp compilers. *They* somehow manage to get within 2x of C++ speed, so why can't Python? > If it's ease of distribution you're looking for, I think distutils can > make standalone programs on Windows, and most Linux distros have Python > installed by default. Nope. > If you just think a compiler would be cool (or would like to see how it > would be done), check out Psyco, Pyrex, and probably some other > projects. Pyrex even combats the speed issue by allowing native C types > to be used in addition to Python high-level types. Erk. Seems to me that you want 'smarter', not 'worse'. I can't take a language seriously if it says that 1/3 is 0.33333... . From nomail at nospam.no Sat May 15 16:40:39 2004 From: nomail at nospam.no (Dominic) Date: Sat, 15 May 2004 22:40:39 +0200 Subject: raise exceptions in generators/functions from other tasks/functions Message-ID: Just in case someone is interested. I came up with this solution since my previous posting. Maybe you've got some other ideas or critcism. I'll listen ;-) Ciao, Dominic P.S. Python is really powerful! Use-Case: def driveTask(handler): print " enter drive" yield "current speed" while 1: try: handler.register(driveTask, (NoPower, WallHit)) while 1: print " adjust engine" yield "current speed" print " steer" except WallHit: print "hit the wall :-(" except NoPower: print "need some fresh batteries :-)" ==================================================================== Full-Source code: from types import GeneratorType class TaskHandler(object): def __init__(self): self.tasks = [] def addTask(self, task): self.tasks.append(task) def removeTask(self, task): del self.tasks[task] def loop(self): for t in self.tasks: # generator task if type(t) == GeneratorType: if not t.next(): # generator is done, remove it self.tasks.remove(t) else: # normal method/function t() from sys import settrace class SignalingTaskHandler(TaskHandler): def __init__(self): super(SignalingTaskHandler, self).__init__() self.function2signal = {} self.activeSignals = () self.newSignals = [] self.loopTask = self.__loop() def register(self, aFunction, signals): self.function2signal[id(aFunction.func_code)] = signals def signal(self, aSignal): if not aSignal in self.newSignals: self.newSignals.append(aSignal) def loop(self): self.loopTask.next() def __loop(self): while 1: settrace(self.__intercept) tmp = len(self.newSignals) try: super(SignalingTaskHandler, self).loop() finally: settrace(None) # if we've reached "steady state", we make a step # I think Esterel-language has similar signaling semantics if tmp == len(self.newSignals): self.__step() yield True def __step(self): # switch to new signal set, discard old ones self.activeSignals = tuple(self.newSignals) self.newSignals = [] def __intercept(self, frame, event, arg): def _i(frame, event, arg): # we could return _i to trace inside function # and not only calls to it if self.activeSignals: signals = self.function2signal[key] # check if there is one signal to raise for s in self.activeSignals: if s in signals: raise s # every function gets it's own tracer, otherwise # exceptions cannot be catched :-( Why? key = id(frame.f_code) if key in self.function2signal: return _i return None # A Use Case : class WallHit(Exception): pass class NoPower(Exception): pass def driveTask(handler): print " enter drive" yield "current speed" while 1: try: handler.register(driveTask, (NoPower, WallHit)) while 1: print " adjust engine" yield "current speed" print " steer" except WallHit: print "hit the wall :-(" except NoPower: print "need some fresh batteries :-)" counter = 0 def miscTask(): global counter if counter == 4: handler.signal(WallHit) if counter == 5: handler.signal(NoPower) counter += 1 # "special" tasks with signaling handler = SignalingTaskHandler() tmp = driveTask(handler) handler.addTask(tmp) # main loop mainTaskHandler = TaskHandler() # well, there could be a lot more mainTaskHandler.addTask(miscTask) mainTaskHandler.addTask(handler.loop) for _ in range(10): mainTaskHandler.loop() # enter drive # adjust engine # steer # adjust engine # steer # adjust engine # steer # adjust engine # hit the wall :-( # adjust engine # need some fresh batteries :-) # adjust engine # steer # adjust engine # steer # adjust engine # steer # adjust engine From roy at panix.com Tue May 11 08:47:53 2004 From: roy at panix.com (Roy Smith) Date: Tue, 11 May 2004 08:47:53 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: Oliver Fromme wrote: > FWIW, sed _is_ a state machine, although not really "general > purpose". It is a programming language with variables, loops > and conditionals, and I believe it is turing-complete. Most > of the time it is abused to perform simple search-and-replace > tasks, though. ;-) I would disagree that the "simple search-and-replace" usage is abuse. It's just using the tool to do what it's best at. Sure, there are some more complex things you can do in sed, but the syntax is so baroque it quickly becomes trying to bash a screw with a hammer. In the old days, when the task became too complicated for sed, you switched to awk. When things got even more complex, you pasted sed, grep, awk, and shell together in various ways, and perl was invented to cover all those functionalities in a single language. In a sense, perl suffers from the same disease that C++ does; a desire to maintain backwards compatability with its parents (thus the absurdly eclectic syntax) while at the same time adding every new feature you could imagine (and some that you can't). Anyway, I think there's a lot of value in learning tools like grep and sed, and using them when appropriate. The example that started this thread is the canonical example of what sed does best. Sure, you can make a general-purpose tool like Python do that job, but other than proving that you can do it, I don't see any reason to bother. From tjreedy at udel.edu Thu May 13 13:33:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 May 2004 13:33:11 -0400 Subject: classes vs dicts References: Message-ID: "David MacQuigg" wrote in message news:nj57a01tqsvtufcur2gqu3enbjll5l95id at 4ax.com... > My problem is similar, with the additional requirement that I need a > convenient way to access data deep within a hierarchy of parameters. > I chose classes over dictionaries because the syntax to access items > in a deeply nested dictionary is awkward. > > dict[window1][plot2][xaxis][label][font][size] = 12 > > vs > > statefiles.window1.plot2.xaxis.label.font.size = 12 > > The problem is I can't easily save the whole hierarchy to disk. > Pickle doesn't work with classes. Also, I worry about the overhead of > classes when I am just needing a simple container. A typical > statefile will have 1000 parameters in 300 classes nested up to ten > levels deep. As a structure of nested classes this takes about 74KB > on disk. Importing the file creates a .pyc file that is 157KB !! It > does seem to import quickly, however, so speed may not be a problem. I believe you could write a class whose instances would correspond to (wrap) a dictionary with possible subdicts. It would have a getattribute method that turned the attribute name into a dict key and either return a new instance or a 'raw' object depending on whether the corresponding value was a nested dict or something else. You would start with one instance representing the top level dict and work down from there. I'll leave implementation to you. I also believe you could instead do this as a subclass of dict itself. I might have even seen such somewhere. Terry J. Reedy From tim.one at comcast.net Mon May 17 22:27:57 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 17 May 2004 22:27:57 -0400 Subject: This program makes Python segfault - no other does In-Reply-To: Message-ID: ... >> There may or may not be other C bugs here, but for starters change the >> last line to >> >> sout = (char *)PyMem_Malloc(slen + 1); [Juho Saarikko] > YES ! It works ! That's only because it was broken . Really, that's a common C coding error when working with C strings. > After making this change and recompiling the module, the segfaults > stopped. Thank you, you saved me days of work. I'll send the > fix to the pyPgSQL project. >From Michael's posts, it sounds like they already fixed this in their CVS. >> BTW, running under a debug-build Python would have told you that the >> program wrote beyond the bounds of the memory allocated for sout. > It didn't. But, as I said, it was the first time I tried using a debugger. > And I only read enough instructions to figure out how to get a stack > trace. No, "running under a debug-build Python" != "using a debugger". A debug-build Python requires compiling Python itself in a different way, and a debug-build Python (among other things) wraps malloc() and free() with special, more-expensive code that checks for over- and under-writes. I'll repeat that it would have caught the overwrite in this case: it would have. Everyone writing Python extension modules in C should learn how to build and run them, and Python, in debug mode -- it will, over time, save them literally months. The Python core is routinely built and tested in debug mode. That's a large part of why the kind of segfault you saw here almost never gets blamed on core Python code. From insert at spam.here Wed May 12 13:20:06 2004 From: insert at spam.here (Doug Holton) Date: Wed, 12 May 2004 12:20:06 -0500 Subject: Real-time graphs In-Reply-To: References: Message-ID: snrkiwi-lists at yahoo.com wrote: > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? Unfortunately there is not anything designed specifically for real-time graphs in python. You could create a custom control. My suggestion is to use a Timer (like wx.Timer in wxpython) set to a particular "frame rate" - how many times the graph should be refreshed per second. Everytime it fires it updates the graph (if it is a scrolling plot, or else if the data has changed). Meanwhile in a background thread your time-stamped data points are collected, perhaps into two lists. If it is a scrolling plot you could discard (or log) data that is old. From peter at engcorp.com Mon May 17 20:55:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 May 2004 20:55:38 -0400 Subject: Python compilers? In-Reply-To: References: Message-ID: Svein Ove Aas wrote: > Is anyone working on a python-to-native compiler? > I'd be interested in taking a look. > > Come to think of it, is anyone working on a sexpr-enabled version of > Python, or anything similar? I really miss my macros whenever I try to > use it... Lots of past threads on this, including this one: http://groups.google.com/groups?&th=8f7b4867334c3d07 (Short answers: no, maybe, look at Psyco, PyPy, and others...) -Peter From phrogeeb at hotmail.com Sun May 23 03:27:10 2004 From: phrogeeb at hotmail.com (Uri) Date: 23 May 2004 00:27:10 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> <5sl4o1-crf.ln1@eskimo.tundraware.com> <10avdpe73rnj20d@corp.supernews.com> Message-ID: <8a0bb987.0405222327.78ef180e@posting.google.com> > Tim Daneliuk wrote: > > Say you have read a line in the above format into variable 's'. > > Then, > > > > l = s.split() > > > > will return a list containing each of the fields of the line as > > an entry with the whitespace stripped out. Then, > > > > VarName = l[0] > > VarDate = l[1] > > VarTime = l[2] > > VarCo = l[3] > > VarEmp = l[4] > > D'oh! That's much better than the regular expression solution I posted. > > The regular expression split is good to know about for more complicated > patterns, but for simple whitespace splitting there's no need for it. > > Thanks, > > -Mike Thanks guys! Tim's idea seems like the easiest for a newbie to implement, but I'll play around with Mike's pre-compiling thing, too. I don't really understand what the compile part does, could you expound upon that? Thanks for all your help guys! From NOmanlio_perilloSPAM at libero.it Sun May 30 12:25:49 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sun, 30 May 2004 16:25:49 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> <87hdtzeanw.fsf@pobox.com> Message-ID: On 29 May 2004 12:26:59 +0100, jjl at pobox.com (John J. Lee) wrote: >Manlio Perillo writes: > >> On 27 May 2004 22:52:10 +0100, jjl at pobox.com (John J. Lee) wrote: >[...] >> >You can just say: >> > >> >ClientCookie.urlopen("http://www.example.com/") >> > >> >and be done with it. >> > >> >> I have seen the module, but it is too complicated. > >Having written it, I agree, but I don't think it's my fault . > Well, it is too complicated for me. > >> Standard Cookie module (with my corrections) plus httplib module is >> really all I need. > >Cool. > Yes, there exists programs that are simple (as there exist programming languages that are simple)! Actually what I do is to download several files from a server. Some files/pages are generated by a script (so I have to post an x-www-form-urlencoded string). I don't want to use urllib2 because it (as I think) for every request connects to the server, do the request and disconnect. I need cookies because the server (as many other) authenticate user with cookies. So the simple algorithm is: -connect to the server -read a cookie from a file -send the cookie to the server -if the server send a cookie, the old one must be updated: with standard Cookie this is simple: cookie.update(newcookie) - ... - save the cookie to a file This is very simple to do with httplib and Cookie modules, so why to use more involved modules? Regards Manlio Perillo From moma at example.net Tue May 18 18:18:29 2004 From: moma at example.net (moma) Date: Wed, 19 May 2004 00:18:29 +0200 Subject: Making items visible in wxPython wxListCtrl In-Reply-To: <39cbe663.0405181208.1065933d@posting.google.com> References: <39cbe663.0405181208.1065933d@posting.google.com> Message-ID: Piet wrote: > Hi there. > I am trying to display tabular data in a wxListCtrl. What I get from > the script below are only the headers, not the items themselves. The > documentation didn?t help me much; instead I was lost in ListItemId?s > and different possibilities of inserting items and strings. I am sure > the solution is only one step away, but I need somebody to point in > the direction. Heres the script: > > from wxPython.wx import * > class MainWindow(wxFrame): > def __init__(self,parent,id,title): > wxFrame.__init__(self,parent,-1, title, > style=wxDEFAULT_FRAME_STYLE) > self.panel = wxPanel(self,-1) > self.Lctrl = wxListCtrl(self.panel,-1,size=(200,200),style = > wxLC_REPORT) > for i in range(2): > self.Lctrl.InsertColumn(i,"Column"+str(i),format=wxLIST_FORMAT_LEFT,width=100) > self.Lctrl.SetStringItem(i,1,"Hi") > self.Lctrl.SetStringItem(i,2,"there") > self.Lctrl.SetItemData(i,1) > > > app = wxPySimpleApp() > frame = MainWindow(None, -1, "List Control Test") > frame.Show(1) > app.MainLoop() > > Best regards > > Peter Mixing rows and columns ? > for i in range(2): >> self.Lctrl.InsertColumn(i,"Column"+str(i),format=wxLIST_FORMAT_LEFT,width=100) >> self.Lctrl.SetStringItem(i,1,"Hi") >> self.Lctrl.SetStringItem(i,2,"there") >> self.Lctrl.SetItemData(i,1) >> # Create 2 columns for i in range(2): self.Lctrl.InsertColumn(i,"Column"+str(i), format=wxLIST_FORMAT_LEFT,width=100) # Add 6 rows of data for i in range(6): self.Lctrl.InsertStringItem(i,"Hi") # Col 0 self.Lctrl.SetStringItem(i,1,"there") # Col 1 self.Lctrl.SetItemData(i,1) http://wiki.wxpython.org/index.cgi/ListControls Cheers, // moma http://www.futuredesktop.org From jbors at mail.ru Thu May 20 16:50:18 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Fri, 21 May 2004 00:50:18 +0400 Subject: ANN: PyMedia 1.2.1 Message-ID: PyMedia 1.2.1 is out. What is it ? ---------------------------------------------------------------- PyMedia is a media library for Python based on following libraries: libavcodec libavformat. libdvdcss libdvdread PyMedia has simple interface and suply data simple data types. Features ---------------------------------------------------------------- 1. Audio decoding/encoding for the following audio types: - mp2 - mp3 - ac3 - ogg - wma 2. Video decoding/encoding for the followin types: - mpeg1,2 ( dvd, vcd, svcd ) - mpeg4, xvid - asf - mov 3. Direct access to sound device 4. Sound manipulation classes such as Resampler 5. Direct access to cdda tracks for easy grabbing and encoding Audio CDs 6. Direct access to dvd tracks for playing DVD movies( all types ) 7. Simple interface and portability( Windows/Linux ) Downoad ---------------------------------------------------------------- Just check the http://pymedia.sourceforge.net and download the latest version( 1.2.1 ). How to use ---------------------------------------------------------------- You may find some really handy scripts in examples directory. These are: Video player( vplayer.py ) requires pydfb( http://sourceforge.net/project/showfiles.php?group_id=86491&package_id=107482 ) or pygame 1.6 patched with Overlay support( http://66.159.221.186/pygame-1.6-overlay.patch.gz ) Audio player( aplayer.py ) CDDA grabber( read_cdda_track.py ) Video recoder( encode_video.py, recode_video.py ) Audio recoder( recode_audio.py ) Plans ----------------------------------------------------------------- - usb support for easy handling the usb devices ability to write drivers in Python for devices that does not require fast speed - more sound handling classes( SpectrAnalyzer, Equalizer ) - more codecs for audio playback( ape, flac ) Thank you, Dmitry/ From sean_berry at cox.net Thu May 27 14:36:17 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 27 May 2004 11:36:17 -0700 Subject: CGI newb... redirect page Message-ID: Hi there. I am relativly new to Python CGI and need a question answered. I have made custom 404 error pages and have them in various web directories. I have not been able to figure out a way to have apache use a file not within it's own home directory, so I was going to have a .py file in cgi-bin forward the user on to the correct error page. So I have say, /usr/www/client1/not-found.shtml and... /usr/www/client2/not-found.shtml I found that cgi.print_environ() gave me the SERVER_NAME, which is what I want. But, this is part of a long html formatted string that cgi.print_environ() returns. Is there something builtin to deal with these name, value pairs as a dictionary? I looked throught the docs, but did not see this functionality. Also, when I do extract this info... how do I actually do a redirect to a certain page Example. User goes to www.client1.com/page_not_on_server.html The apache conf file sends the redirect to /cgi-bin/redirect.py Redirect.py extracts the requesting server, client1.com, then redirects them to www.client1.com/not-found.shtml. Thanks for your help. From josh at mri.com.au Thu May 20 22:49:26 2004 From: josh at mri.com.au (Joshua Burvill) Date: Fri, 21 May 2004 12:49:26 +1000 Subject: textwrap for python 2.1? Message-ID: <000001c43ede$3b86d350$f002a8c0@sydney.mri.com.au> Hello, How can I use the textwrap (new in 2.3) module if I have to use python 2.1? Rgds, Josh From alloydflanagan at comcast.net Sun May 9 06:38:55 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 9 May 2004 03:38:55 -0700 Subject: What I don't like about wxPython References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xr7tu5un8.fsf at ruckus.brouhaha.com>... [snip..] > If wxPython really depends on Windows, that's a huge obstacle for > those wanting a portable system. If it doesn't literally depend on > Windows, but uses Windows-centric interfaces and approaches, that's > still pretty annoying for non-Windows developers. Couple of points: wxPython is very cross-platform, I've used the same program on Windows and Linux and it looks fine on both. The Mac OS X port appears to be coming along very well. wxPython is (deliberately) a thin wrapper of the C++ classes in the wxWidgets package (used to be called wxWindows). So it supports all the platforms wxWidgets does. And, yes, it's not pythonic; the wax package is supposed to fix that, though I personally don't have experience with it. From fperez528 at yahoo.com Sat May 15 19:40:45 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 15 May 2004 17:40:45 -0600 Subject: Idea: PYTHONPATH_VER References: Message-ID: Peter Hansen wrote: > Check the source in site.py first, then, as it is fairly straight- > forward about what it does. Thanks for the pointer, I didn't know what part of python was responsible for these manipulations. Knowing where to look, it will be much easier now to deal with this issue. Regards, Fernando From derek at hiredgoons.org Tue May 18 08:53:52 2004 From: derek at hiredgoons.org (Derek Thomson) Date: Tue, 18 May 2004 22:53:52 +1000 Subject: Calling Jython code from Java In-Reply-To: <1a26ae5d.0405180403.db0e069@posting.google.com> References: <1a26ae5d.0405180403.db0e069@posting.google.com> Message-ID: <40aa0701$1@duster.adelaide.on.net> Raja wrote: > I have a java class thats trying to call something in python. This > works fine when i do a jythonc on the python script. [snip] > > class testconfig(java.lang.Object): > > def __init__(self): > """@sig public testconfig()""" > self._cfg = configuration.configuration("/sources/jmxproto") [snip] > class configuration: > > def __init__(self, runtimeDir=None): > """@sig public configuration(java.lang.String dir)""" > """ Some code in here """ > > When i call testconfig.py, i get the error mentioned above. Any clues? In Python, you just use the class name to create instances. So I think that perhaps: self._cfg = configuration.configuration("/sources/jmxproto") Should be: self._cfg = configuration("/sources/jmxproto") IIRC the "@sig" declaration only comes into play when attempting to use the class from *Java* code. That's why there is no "configuration" attribute. Regards, Derek. From winexpert at hotmail.com Wed May 26 10:21:31 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 26 May 2004 14:21:31 +0000 Subject: Best way to enumerate something in python Message-ID: Thanks for the help. I found out range creates lists not tuples, so apparently they can get changed (for an enum type approach). I'm going to use them in SQL statements that get generated on the fly. I need to be able to refer to a particular column in a meaningful way which is why if i had an enumerated type it might be easy to do so. i did some reading and if i interpreted this correctly, dictionaries are hashed, correct? If so i might be able to get away with referencing the dictionary and passing the hashkey in this case a number to retrieve the column name. However, I'd like to do this mnemonically so I can refer to the column name with a short cut name that makes sense instead of saying something like insrtCommand = ' select ' + columns[1] + ',' + columns[2] + ' from ' blah....... from a maintenance standpoint, the programmer can't tell what column 1 is supposed to refer to. however if i had something like columns[HOUSING_ID] instead of the '1' then the programmer would later at a glance be able to follow the code. David ------- tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: "Larry Bates" >To: python-list at python.org >Subject: Re: Best way to enumerate something in python >Date: Wed, 26 May 2004 08:54:10 -0500 > >David, > >You may have to give us more detail about what >you want to do, but here goes: > >listofcolumns=('field1','field2','field3') >for column in listofcolumns: > > >Most of the time I find that putting the names >in a dictionary with the column name as key and >offset as the value seems to work better. > >dictofcolumns={'field1':1, 'field2': 2, 'field3':3} > >value_for_field3=row[dictofcolumns['field3']] > >For your second question I think you should >take a look at os.path.getatime, .gmtime, getsize >they are easier to use. > >Larry Bates >Syscon, Inc. > > >"David Stockwell" wrote in message >news:mailman.311.1085575108.6949.python-list at python.org... > > Hi Everyone, > > > > I'm wondering about the best way to enumerate something. > > > > I have a list of columnames for a db and I decided to put them in a >giant > > tuple list for two reasons: > > 1) its unchangeable > > 2) I was hoping that creating an enumeration of those names would be >easy > > > > In the os.stat there is aparrently a list of things you can refer to eg: > > ST_SIZE, ST_ATIME, etc. > > > > How are these defined? They appear to be related to 0,1,2,3,.... some > > sort of enumeration. > > > > I would like to create an enumeration with 'friendly names' that map to >the > > particular offset in my column name tuple. > > > > Thanks, > > > > > > > > David > > ------- > > tracfone: http://cellphone.duneram.com/index.html > > Cam: http://www.duneram.com/cam/index.html > > Tax: http://www.duneram.com/index.html > > > > _________________________________________________________________ > > FREE pop-up blocking with the new MSN Toolbar ? get it now! > > http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ > > > > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From lbates at swamisoft.com Tue May 11 14:41:52 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 11 May 2004 13:41:52 -0500 Subject: Ideas about optional filter on for loop statements References: Message-ID: <2a6dnVtE-sR-Tj7dRVn-vg@comcast.com> Brian, How about writing: for x in [i for i in range(10) if i%2 is 0]: print x or in your other examples: for x in [i for i in l if i]: ... for x in [i for i in l if not i]: ... All seem exteremely close to your proposal but don't require any changes to current language implementation (e.g. just use list comprehensions). Regards, Larry Bates Syscon, Inc. "Brian L." wrote in message news:c186c44d.0405110926.5eead044 at posting.google.com... > After following the discussion on Generator expressions on python-dev > for the last few weeks, and finally getting used to list > comprehensions as opposed to map/filter, it occurred to me that the > for loop statement lacks the filtering feature when compared to the > listcomp/genexp. For instance, > > (real code) > for x in range(10): > if x%2 is 0: > print x > > Could be reduced to: (fake code) > > for x in range(10) if x%2 is 0: > print x > > Which is comparable to iterating and printing the elements of the > listcomp: > [x for x in range(10) if x%2 is 0] > > or the genexp: (this syntax isn't real yet, but I'd imagine this to be > fairly accurate based on python-dev) > > (x for x in range(10) if x%2 is 0) > > Note the perfect consistency between all three iterator usages. > > This change would not break any compatibility that I can think of, but > would improve self-consistency within python. Furthermore, if > listcomps and genexps are a direction that python is moving in, then > it would probably make sense that the for loop statement has an > optional filtering clause as well. > > The strongest argument I can think of against it is that for loop > statements should be reserved for iteration only, and that they > shouldn't have functional features (for instance, the for loop can not > and will not ever have 'map' like semantics, so why should it have > filter?). I don't think, however that this is a problem, and > considering the number of times that I've written loops in the > following patterns: > > for x in l: > if x is None: continue > ... > > or > > for x in l: > if x is not None: > ... > > I think that a more pythonic syntax may be in order. > > for x in l if x is not None: > ... > > is certainly cleaner and easier to read. This clause should of course > be optional > > Thoughts? > > If this receives enough positive attention on comp.lang.python, then > I'll write it up and submit a PEP. > > Brian From dmq at gain.com Thu May 20 14:46:56 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 20 May 2004 11:46:56 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> Message-ID: <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote: >> I've made your program, Animals_JM.py at >> http://ece.arizona.edu/~edatools/Python/Exercises/ the next example >> *after* Animals_2. The topic of techniques to make a program robust >> and maintainable is worth a whole chapter, but it would be a >> distraction in the introductory chapter. >> >> I would still like to see a way to gain the benefits of both Animals_2 >> and Animals_JM in one program. My attempts to follow up on >> suggestions in this discussion have only added complexity, not >> improved the program. > >Simple method - choose a different example. However, you do not >appear to be open to this suggestion. If I were not open to suggestions, I would not be spending all this time patiently extracting the good suggestions from this long thread, and putting up with dogmatic statements and personal attacks. I could repond by saying most of what I'm reading is hot air, but that would be equally provocative. Let's see if we can bring this to a better conclusion. I like your example, but not as a *substitute* for Animals_2. It's just too complex for non-CIS students at this point in the course. I think I understand your concerns about Animals_2. I think the best way to deal with those concerns is not by complicating the example, or by taking out everything that could lead to problems, but rather by pointing out the problems, and showing subsequent examples that fix those problems, even at the expense of more complexity. If you have a simple all-in-one alternative to Animals_2, show me. Meanwhile, what I have understood as problems and suggested solutions includes: 1) Class variables like numMammals that are not intended to be directly altered by the user should be made private variables, by adding a leading underscore. _numMammals. 2) Direct calls to a function from a parent class (super calls) might not get updated if a programmer adds a new class in the hierarchy. Calls like Animal.__init__(self) should be replaced by a general call to the __init__ function from whatever class is directly above the current class. Mammal.__bases__[0].__init__(self) Note: Calls like Mammal.talk(self), which really *are* intended to use a function from a specific class, should be left as is. 3) Variables like _numMammals which depend on variables in other classes could get out-of-sync with those other variables ( e.g. if a programmer adds a new class and forgets to call __init__). These variables could be replaced by functions which re-calculate the dependent values from the original independent data. Note: This is a trade-off of simplicity and efficiency vs robustness against future programmer error. I've implemented these suggestions in Animals_2c.py at http://ece.arizona.edu/~edatools/Python/Exercises/ Here is a snippet from one of the classes: class Animal(object): _numAnimals = 0 def numAnimals(): return ( Animal._numAnimals + Mammal.numMammals() + Reptile.numReptiles() ) numAnimals = staticmethod(numAnimals) I've re-defined _numAnimals to hold only the count of Animal instances. To get the total count of all animals, I've got a new function numAnimals. This function does not walk the entire hierarchy, as I suspect you might require, but it does add up the totals from all subclasses directly below Animal. In each of those subclasses, we define a function which totals the numbers from all of its subclasses. In this way we get a simple recursive re-calculation of all totals anywhere in the hierarchy, and the only actual data is the count in each class of instances of that class. We still have an inter-dependency problem when adding classes to the hierarchy. We need to remember to add the appropriate num... function for the new class to its parent class. For example, when we added a Reptile class between Animal and Snake, we modified the function above to include Reptile.numReptiles() in the total. We also need to make sure we include *all* children of Reptile in the new numReptiles function. class Reptile(Animal): -numReptiles = 0 def numReptiles(): return ( Reptile._numReptiles + Snake.numSnakes() + Lizard.numLizards() ) Oops. We forgot Geckos !! To avoid these errors in programming, we may need a function that automatically searches for subclasses, and calls their num functions. I'm not sure how to do this without making it excessively complex. Suggestions will be appreciated. -- Dave From mwh at python.net Thu May 13 07:57:00 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 13 May 2004 11:57:00 GMT Subject: Printing formatted strings from a dictionary References: Message-ID: tkpmep at hotmail.com (Thomas Philips) writes: > I want to print "1 spam 4 you" using a formatted string that gets its > inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, > I write > > >>> x="%('n1')d %('s1')s %('n2')d you" > >>> x % d > > Traceback (most recent call last): > File "", line 1, in -toplevel- > x % d > KeyError: "'n1'" > >>> > > However, I get what I want if I edit x to remove the quotes around n1, > s1 and n2 and write > >>> x="%(n1)d %(s1)s %(n2)d you" > >>> x % d > '1 spam 4 you' > > The syntax that works seems to run counter to the way dictionaries > work: > >>> d['n1'] > 1 > >>> d[n1] > > Traceback (most recent call last): > File "", line 1, in -toplevel- > d[n1] > NameError: name 'n1' is not defined > > What is the error in my logic? Um. If the n1 is already inside a string literal, adding more quotes would be redundant? CHeers, mwh -- A difference which makes no difference is no difference at all. -- William James (I think. Reference anyone?) From andrew-pythonlist at puzzling.org Thu May 13 04:07:27 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 18:07:27 +1000 Subject: PEP: import version In-Reply-To: References: Message-ID: <20040513080727.GD20388@frobozz> On Thu, May 13, 2004 at 07:46:51AM +0000, Manlio Perillo wrote: [...] > A possible syntax is this: > import wxPython version '2.4' I'd like to see versioned imports too, but it looks like a tricky problem to me. Some questions that immediately spring to mind reading your proposal: How would this work with from X import Y? How would this work with packages (e.g. import X.Y.Z)? e.g. how would you add version requirements to these statements: from gtk import main from twisted.web import server For the first one, "from gtk version '2.0' import main" doesn't look too bad. But what about the second one -- can only top-level modules/packages have versions? e.g. what if the "twisted.web" package has a version that's independent of the top-level "twisted" container package? Would "from twisted.web version '1.3.0'" mean Twisted version 1.3.0, or Twisted Web version 1.3.0? What happens if the same program tries to import different (and possibly conflicting) versions of the same module, e.g.: import gtk version '2.0' import gtk version '1.2' Should an ImportError be raised? Should it succeed (assuming both versions are available)? Is it even possible to have two different versions of the same library/module installed in parallel, and if so, how? I'd love to see a proposal that addresses all of these points :) > Another case is when the module is implemented also in C: > import picke version 'C' Alternative implementations of the same module for reasons of optimisation is a different problem, and I don't think it's a good idea to try solve it the same way. -Andrew. From zunbeltz at wm.lc.ehu.es.XXX Mon May 31 09:35:20 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 31 May 2004 15:35:20 +0200 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: Peter Hansen writes: > Zunbeltz Izaola wrote: > > Peter Hansen writes: > >>Zunbeltz Izaola wrote: > >> > >>>I've the following problem with try/exception. > >>>I've a try block that will raise some exceptions. > >>>I want the program to ignore this exceptions completely. Is it > >>>possible? > >> > >>In the following, all exceptions will be ignored: > >> > >>try: > >> # something that raises exceptions > >>except: > >> pass > > I've trid this, but the problem is that this finished the try block. > > I want to continue executing the try block from the point the > > exception was raised. > > Not possible except, perhaps, with a significant amount of > working involving sys.settrace(). I think you need to find > another way to solve the problem. > > What you are trying to do is not something that other people > who do unit testing seem to have to do. Why do you think > you need to actually *disable* exceptions entirely in order > to test this code? Perhaps the code needs to be restructured? Possibly the code should be restructered, and re-designed; there is always room for imporovement. But what I'm doing is not unittest. My program is controling and instrument (an x-ray powder diffractometer) and some parts of the instrument are not working for the moment, so i want to disable all error i get from this instrument (are coded like exceptions) Zunbeltz > > -Peter -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From cghiban at gmx.net Thu May 13 03:52:20 2004 From: cghiban at gmx.net (Cornel Ghiban) Date: Thu, 13 May 2004 10:52:20 +0300 Subject: Smalles Possible Browser to display python cgi program In-Reply-To: References: Message-ID: <20040513105220.135d115f.cghiban@gmx.net> try this one: http://jan.kneschke.de/projects/lighttpd/ On 12 May 2004 23:11:14 -0700 matthiasjanes at gmx.net (matthiasjanes) wrote: > Dear everyone, > > I would like to know what would be the smalles possible WebBrowser for > displaying Python CGI application. > -- "Doamne, da-ne macar de cateva ori in viata, puterea de a folosi comanda <> !" -- Mircea Cartarescu From gregory.lielens at fft.be Thu May 13 05:09:42 2004 From: gregory.lielens at fft.be (Gregory Lielens) Date: Thu, 13 May 2004 11:09:42 +0200 Subject: controlling input behavior of embedded python with PyOS_ReadlineFunctionPointer Message-ID: Hello all, I am not sure this is the correct list to ask as my problem is really related to python low level implementation, but as I do not have found a python.dev list, here it is :-) We are curently developing python bindings to make a MPI parallel application (Finite element solver) script driven. I have written a main interpreter, able to execute scripts or interractive commands,in // , based on the following techniques: *file execution: all python interpreter processes run the file using PyRun_SimpleFile (file must be available to all processes) *file execution using broadcast: process 0 read input file and store it in a file, broadcast it to all processes and the script is run using PyRun_SimpleString (file must be available to process 0 only) *interractive execution: All processes listen to user input using a PyRun_InteractiveLoop. Process 0 read stdin and broadcast the line to all process, the other process listen to this broadcast. This is implemented using the (very usefull in this case :-) ) PyOS_ReadlineFunctionPointer , reassigning it to an input function which wrap the default PyOS_ReadlineFunctionPointer (to be able to reuse nice readline functionalities) and add the broadcasting mechanism... All of this work perfectly, but I had to modify the python sources, Parser/myreadline.c to be precise... Indeed, the behavior of PyOS_Readline is to use the user-modifiable PyOS_ReadlineFunctionPointer as input mechanism, except when input is non-interractive in which case it fall back to the non-user-modifiable PyOS_StdioReadline...As my processes are non-interractive except for proc 0 (launched in background), proc 0 broadcast but the other ones do not listen. I thus had to remove this test, so that the user-modifiable function is called in all cases. /*Python code snipped from Parser/myreadline.c*/ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { char *rv; if (PyOS_ReadlineFunctionPointer == NULL) { #ifdef __VMS PyOS_ReadlineFunctionPointer = vms__StdioReadline; #else PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; #endif } } Py_BEGIN_ALLOW_THREADS /* This is needed to handle the unlikely case that the * interpreter is in interactive mode *and* stdin/out are not * a tty. This can happen, for example if python is run like * this: python -i < test1.py */ /* my modif: comment out the use of PyOS_StdioReadline for non-interractive input...*/ /*if (!isatty (fileno (sys_stdin)) || !isatty (fileno(sys_stdout))) rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); else*/ rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, prompt); Py_END_ALLOW_THREADS return rv; } } /*end of snipped code*/ This is a small modif, but annoying because we would prefer to use the plain python distribution, and anyway I wonder if the current behavior of python is desirable, because basically it removes part of the functionality of PyOS_ReadlineFunctionPointer: flexibility dissapear for non-interractive input. In addition, this seems not so robust, it seems to me that it is not correct for vms, where PyOS_StdioReadline will be used in non-interractive case while vms__StdioReadline will be used for interractive one....maybe this is the intended behavior, but then the function naming is strange :-) So basically, shouldn't it be the resposability of the code which change PyOS_ReadlineFunctionPointer to check if the function given is adapted to interractiveness of input? this seems the more flexible approach, and probably involve only minor modif of the readline module. In addition, wouldn't it be nice to initialize PyOS_ReadlineFunctionPointer to a default value (suitable reading function) at declaration, instead of defining it to NULL and let PyOS_Readline do the initialization when needed? This way, user code can get back a meaningfull reading function storing the old value of PyOS_ReadlineFunctionPointer, use it to write an extended input function, and reasign it to PyOS_ReadlineFunctionPointer... This seems to me like the most flexible way to add user-tunable input method... So, to all experienced python developers, having used this PyOS_ReadlineFunctionPointer function or implemented this code, what do you think of these possible slight modifications? Or is there a better way to use it than my current method? Sorry for the long (and possibly strangely written, english is not my native language :-) ) post, Best reagards, Greg. From grante at visi.com Wed May 19 01:06:23 2004 From: grante at visi.com (Grant Edwards) Date: 19 May 2004 05:06:23 GMT Subject: alternatives to making blocks like { } or other ?? References: Message-ID: On 2004-05-18, CYBER wrote: >> Of course there is another way! >> >> Just use # in front of your favourite block separator. >> >> I'm too lazy now to search the archives on who first suggested this, >> but it works: >> >> def something(x): >> #{ >> return x >> #} > > Thank you. You realize that was a joke, right? Please, please don't write code like that. You'll be shunned just like the BASIC programmers who switched to C and pulled crap like #define IF if ( #define THEN ) { #define ELSE } else { #define ENDIF } #define WHILE while ( #define DO ) { #define DONE } ... I once saw a very complete set of macros like that used to make a C program look surprising like some brand or other of structured BASIC. It was impressive in a sick sort of way. The program didn't actually work right since the author was trying to impliment a recursive descent parsing algorithm without using recursion (he didn't know what recursion was, since BASIC didn't have it), and was attempting to keep a "stack" in a user space data structure without realizing that's what he was doing. -- Grant Edwards grante Yow! Now KEN is having at a MENTAL CRISIS beacuse visi.com his "R.V." PAYMENTS are OVER-DUE!! From drlinux at columbus.rr.com Tue May 4 22:07:03 2004 From: drlinux at columbus.rr.com (Dave Reed) Date: Tue, 4 May 2004 22:07:03 -0400 Subject: Python sets. In-Reply-To: References: Message-ID: <200405042207.03205.drlinux@columbus.rr.com> On Tuesday 04 May 2004 21:04, Shalabh Chaturvedi wrote: > Grzegorz Dostatni wrote: > > I've got a problem. > > > > Some time ago (I'm a bit fuzzy about the date) I read about sets in > > python. I even tried the code. I remember it was something fairly simple - > > just a base data type (like list or dictionary). I vaguely remember it > > had a syntax similar to creating dictionaries. > > > > Problem is I can't find it anymore. I've searched around, but it doesn't > > seem to exist. I know of "import sets" and creating classes like that, but > > I'm sure it was a base data type. No import necessary. There were > > operators for basic set operations like set difference, division, etc. > > You might have read "What's New in Python 2.4" which, as of now, really > explains what is *going* to be new in Python 2.4. > > -- > Shalabh There's also a Set type in Python 2.3 although it may be changing in 2.4. > python Python 2.3 (#1, Jul 30 2003, 11:37:39) [GCC 3.2.3] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sets >>> dir(sets) ['BaseSet', 'ImmutableSet', 'Set', '_TemporarilyImmutableSet', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'ifilter', 'ifilterfalse'] >>> s = sets.Set([1, 2, 3]) >>> s Set([1, 2, 3]) >>> From kylotan at hotmail.com Sat May 29 06:50:43 2004 From: kylotan at hotmail.com (Kylotan) Date: 29 May 2004 03:50:43 -0700 Subject: mod python confusion References: Message-ID: <153fa67.0405290250.5661432a@posting.google.com> "Robert Brewer" wrote in message news:... > Given that webserver advocacy comes and goes, I always recommend > abstracting the webserver interface, so rewrites like the one you're > talking about hurt less: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/225299 Hi Robert. You've recommended this recipe to me in the past when I asked a similar question on this newsgroup. However, I must admit that I really don't understand 90% of it, since there are so many layers of abstraction and it spans several classes - and indeed, 2 recipes! Surely there has to be something simpler? I read somewhere today that mod_python made Python as simple to use for web apps as PHP etc, but if this is any indication of the amount of code you need to simply redirect execution to separate places based on the URI, then I'd have to disagree with that! -- Ben Sizer From jbors at mail.ru Tue May 25 16:44:00 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Wed, 26 May 2004 00:44:00 +0400 Subject: programming video manipulation In-Reply-To: <200405252128.37808.tim.jarman@lineone.net> Message-ID: > On Tuesday 25 May 2004 20:33, "Dmitry Borisov" wrote: > > > Hi Olivia, > > Not sure which interface your microcontrollers are using, if it is USB, > > then you might look at PyUSB which seems should work. > > If the OP is using a regular serial interface, rhere's always: > http://pyserial.sourceforge.net/ > And correspondingly for parallel: > http://pyserial.sourceforge.net/pyparallel.html > > Sounds like a fun project! Forgot link to PyUSB: http://armoid.com/pyusb/ PyMedia: http://pymedia.sourceforge.net Have fun. Dmitry/ From jjl at pobox.com Sun May 30 20:56:10 2004 From: jjl at pobox.com (John J. Lee) Date: 31 May 2004 01:56:10 +0100 Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> <87hdtzeanw.fsf@pobox.com> Message-ID: <87y8n9bej9.fsf@pobox.com> Manlio Perillo writes: [...] > >> Standard Cookie module (with my corrections) plus httplib module is > >> really all I need. > > > >Cool. > > > > Yes, there exists programs that are simple (as there exist programming > languages that are simple)! > > Actually what I do is to download several files from a server. > Some files/pages are generated by a script (so I have to post an > x-www-form-urlencoded string). > > I don't want to use urllib2 because it (as I think) for every request > connects to the server, do the request and disconnect. Yes, that's true. I should fix it... > I need cookies because the server (as many other) authenticate user > with cookies. > So the simple algorithm is: > > -connect to the server > -read a cookie from a file > -send the cookie to the server > -if the server send a cookie, the old one must be updated: with > standard Cookie this is simple: cookie.update(newcookie) > - ... > - save the cookie to a file > > > This is very simple to do with httplib and Cookie modules, so why to > use more involved modules? No reason at all if you're happy with it, of course. That was what my "Cool" was meant to communicate. *Using* urllib2 is less involved even than your little algorithm above, of course (neglecting bugs, of course, including the persistent connection bug, which -- though it could certainly be a problem -- I confess has never actually troubled me, despite having used it to repeatedly fetch tens of millions of records in the past). Why use modules whose *implementation* is more involved? Because they're even easier to use, and because, even for simple scripts like your's, not every case is as simple as the one you happen to have met. I know from experience that it can quickly get *very* tiresome to do some of this stuff by hand (even if only a few things like redirections and cookies are involved). And personally, I don't even like to *think* about it, or to have to maintain it in future if I can avoid it, regardless of how simple (ignoring for the moment that I have to maintain the library itself ;-). As for why the complications... well, if you want to know, read the code (no, don't :-). John From frithiof.jensen at die_spammer_die.ericsson.com Tue May 11 05:38:12 2004 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Tue, 11 May 2004 11:38:12 +0200 Subject: What I don't like about wxPython References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xr7tu5un8.fsf at ruckus.brouhaha.com... > If wxPython really depends on Windows, that's a huge obstacle for > those wanting a portable system. It depends on Win32 - on a Windows system. On f.ex. Linux it depends on whatever X11 it is running under. In practice, the user gets the same interface as all the other stuff on the screen merely by running the aplication - which is what I would call "portable" and it is probably what the user expects too. (The real miracle is that this actually *works*, unlike in Java....) > If it doesn't literally depend on > Windows, but uses Windows-centric interfaces and approaches, that's > still pretty annoying for non-Windows developers. I haven't noticed anything different - but then again, I may be using just a subset of the interface so I have not hit any of the edges yet. From admin at na.org Fri May 28 05:04:34 2004 From: admin at na.org (admin at na.org) Date: Fri, 28 May 2004 02:04:34 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:00223988061728402398) Message-ID: <0f4801c44492$cba0e610$b0a8a8c0@na.org> Subject of the message: something for you Recipient of the message: NAWS Customer Service From __peter__ at web.de Thu May 27 03:36:18 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2004 09:36:18 +0200 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: Ville Vainio wrote: >>>>>> "Ryan" == Ryan Paul writes: > > Ryan> the line. It's a good OO strategy. I do understand your > Ryan> dislike of 'self'. It does seem like clutter. In my code, I > Ryan> shorten it to 's'. In ruby, class variables are prefixed > Ryan> with an '@', which makes them easier to discern in code, and > Ryan> it is easier than typing 'self'. I wish python had something > > Prefixing names with symbols like $ and @ is a great idea - it makes > the "nouns" (variables) stand out from "verbs", and makes the code > flow like a natural language, making reading it easy and writing it > fun! As a preliminary measure you might want to apply the following patch: *** this.py 2002-02-08 21:41:34.000000000 +0100 --- $this.py 2004-05-27 09:34:01.000000000 +0200 *************** *** 18,24 **** Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. ! Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" d = {} for c in (65, 97): --- 18,24 ---- Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. ! $Flzoby $cersvkrf @ner &bar !@ubaxvat &terng $vqrn -- /yrg'f @qb &!zber &bs $gubfr!""" d = {} for c in (65, 97): As you can see I didn't find the proposed distinction between nouns and verbs always convenient. A little randomness immediately leads the eye to the really unimportant stuff - just like the ugly new hat of a friend you haven't seen for some time. Yet another case where practicality beats purity :-) Peter From irmen at -nospam-remove-this-xs4all.nl Wed May 5 17:29:15 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Wed, 05 May 2004 23:29:15 +0200 Subject: Web programming ... In-Reply-To: References: <40990fd8$0$567$e4fe514c@news.xs4all.nl> Message-ID: <40995cab$0$560$e4fe514c@news.xs4all.nl> Chris Herborth wrote: > I guess it depends on what you mean by "web application"... I've never > been able to find decent SOAP support, or something that can grok a WSDL > file, for example. Web Application = an application that is accessed by the users through a web interface in a browser. I think you're referring to a "Web Service"... whatever that may be. --Irmen From jjl at pobox.com Mon May 24 15:20:25 2004 From: jjl at pobox.com (John J. Lee) Date: 24 May 2004 20:20:25 +0100 Subject: urllib.urlretrieve error References: Message-ID: <87pt8t1vk6.fsf@pobox.com> "Sam Sungshik Kong" writes: > Hello! Hello! > I'm trying to download PDF files from web to my computer using urllib. > Some pdf files are fine but other files are downloaded only 6kB which is > wrong. > It didn't show any error message. > > I use urllib.urlretrieve(url, fn). > > So I tried to download with Internet Explorer and it worked fine. > > Anyone knows why? What was the content of the 6kb file? Don't assume it was the first 6kb of the PDF file: for instance, it may be an HTML page. > My another question is how I can retrieve "mms:..." files. > urllib.urlretrieve doesn't work with that protocol. IIRC, that's a proprietary Microsoft scheme that's designed for 'streaming' (ie. downloading and playing back the contents at the same time). I think there's a dodgy C program around somewhere which is just about able to grab them, but I don't know of a Python-accessible implementation. John From peter at engcorp.com Sun May 23 09:12:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 May 2004 09:12:37 -0400 Subject: Freeze and Resume execution In-Reply-To: References: <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> Message-ID: <1MSdnc6R_LPYPi3dRVn-ig@powergate.ca> Miki Tebeka wrote: >>>I'd like to use generators but can't see any "nice" way of doing it. >> >>That would be the approach I would take. What can't you see >>with using yield this way? > > The output function is way down the call stack. The function that handles > the "freezing" and need to be saved is about 3-5 stack frames up > (depends on the scenario). > > Propagating the output return value all the way back is tedious and > error prone. This is why I'd like to use raise/catch and not "if error > ..." I start to understand, a bit. Sounds like the suggestions to use Stackless (and tasklets) are on the right track. Alternatively, could you just use threads and have the output function block (and force a context switch) when the buffer is full? If you can't use threads, and you can't use Stackless, and if exceptions don't allow restarting, and if generators preserve only the current frame and not the entire stack (i.e. you can't hand the generator state up to a higher level function, then resume from there, which would be more like a coroutine I guess), then it looks like handling this with classes/state machines is your only option. -Peter From P at draigBrady.com Fri May 21 06:54:29 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Fri, 21 May 2004 11:54:29 +0100 Subject: i18n/localization-- easily?? In-Reply-To: <10aqgdj5kkkmo9e@corp.supernews.com> References: <10aqgdj5kkkmo9e@corp.supernews.com> Message-ID: <40ADDFE5.5020301@draigBrady.com> Ixokai wrote: > I want to add internationalization to the software i'm writing now, but have > run into a bit of a snag. > > It seems so darn complicated! Importing gettext, forcing it to grab the .mo > from the correct location(nessecarily a bit non-standard in this situation), > and using _() around my strings, those are all easy. > > But generating the .pot's seems impossibly complicated. Am I wrong or do I > need to run pygettext on every single file in my system, manually? Then > msgfmt? I was hoping that I could run it once, have it scan all of the > python files referenced, and have it generate some global 'messages.pot', > that I could then append to with subsequent executations (on different > files). > > This doesn't appear to be the case. Did I miss something terribly? :) Yes there are a lot of things to worry about. I summarised a few things here: http://www.pixelbeat.org/docs/i18n.html In summary pygettext is redundant now as the standard xgettext supports python code. The handiest way to do all this is in a Makefile. I would suggest downloading my python program and referencing the Makefile in the po directory: http://www.pixelbeat.org/fslint/FSlint-2.06.tar.gz P?draig. From ivoras at __geri.cc.fer.hr Wed May 5 13:32:29 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Wed, 05 May 2004 19:32:29 +0200 Subject: the dreaded double fork In-Reply-To: References: Message-ID: John Hunter wrote: > I am using python to run an xml rpc daemon using SimpleXMLRPCServer. > Following a cookbook recipe, I am trying to do a double fork so that > when I exit the shell the daemon remains running. But it doesn't. > Here is how I start the script > > >>ssh somehost >>sudo python mydaemon start& try: nohup sudo python mydaemon start & From lbates at swamisoft.com Wed May 5 10:51:25 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 5 May 2004 09:51:25 -0500 Subject: Need Help in Python References: <77632a66.0405041826.37568aef@posting.google.com> Message-ID: Line drawing characters can be used: topleftbox=chr(218) bottomleftbox=chr(192) bottomrightbox=chr(217) toprightbox=chr(191) vertical=chr(179) horizontal=chr(196) HTH, Larry Bates Syscon, Inc. "Mahmood Mashal" wrote in message news:77632a66.0405041826.37568aef at posting.google.com... > Hello everyone. I started programming in Python like a month ago and i > have a problem. I want the program that I am writing to use a > character to draw a box. How can i declare that character as a > variable? If anyone could help me. Thanks From grante at visi.com Wed May 19 12:38:13 2004 From: grante at visi.com (Grant Edwards) Date: 19 May 2004 16:38:13 GMT Subject: alternatives to making blocks like { } or other ?? References: Message-ID: On 2004-05-19, Williams, Timothy J Mr RDECOM CERDEC NVESD wrote: > Here again indentation doesn't matter. A smart editor could do a > "pretty-print" for you using the braces. I agree that *visually* indentation > w/o the braces are nice, but as a check for having code in the right logical > block, it's just too easy have a stray extra or missing space (for me > anyway) that would throw everything off. Isn't just one space needed in > Python to signify a different block? Yes, but an accidental extra space or deleted space _usually_ causes a syntax error. -- Grant Edwards grante Yow! I think I'll make at SCRAMBLED EGGS!! They're visi.com each in LITTLE SHELLS... From aahz at pythoncraft.com Mon May 10 10:34:25 2004 From: aahz at pythoncraft.com (Aahz) Date: 10 May 2004 10:34:25 -0400 Subject: Processing huge datasets References: <79Knc.15953$k4.322398@news1.nokia.com> Message-ID: In article <79Knc.15953$k4.322398 at news1.nokia.com>, Anders =?UTF-8?B?U8O4bmRlcmdhYXJk?= wrote: > >I'm trying to process a large filesystem (+20 million files) and keep the >directories along with summarized information about the files (sizes, >modification times, newest file and the like) in an instance hierarchy >in memory. I read the information from a Berkeley Database. > >I'm keeping it in a Left-Child-Right-Sibling instance structure, that I >operate on recursively. > >First I banged my head on the recursion limit, which could luckily be >adjusted. Well, Don't Do That. ;-) I don't understand the data structure you're describing; you'll either need to choose something more appropriate for recursive processing or switch to iterative processing (probably using generators). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From deetsNOSPAM at web.de Sun May 16 09:47:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 16 May 2004 15:47:21 +0200 Subject: CORBA Python Query References: <789bf36d.0405160531.2b6a991e@posting.google.com> Message-ID: Akhilesh S. Shirbhate wrote: > --------------------------------- > Traceback (innermost last): > File "./msg-server.py", line 20, in ? > servant = POA.MESSAGING.mail(mail()) > NameError: POA > --------------------------------- No wonder, as you don't import a module named POA. As you seem to look for the generated class of your dynamically loaded idl, you might try to use the rootpoa, thus writing servant = poa.MESSAGING.mail(mail()) notice the lower case. If thats no help, look into the examples from orbit python, I bet you can find something working there. -- Regards, Diez B. Roggisch From roy at panix.com Mon May 31 15:13:39 2004 From: roy at panix.com (Roy Smith) Date: Mon, 31 May 2004 15:13:39 -0400 Subject: Regexp: unexspected splitting of string in several groups References: <39cbe663.0405310341.430d2035@posting.google.com> Message-ID: pit.grinja at gmx.de (Piet) wrote: > vartypePattern = re.compile("([a-zA-Z]+)(\(.*\))*([^(].*[^)])") > [...] > simple one-string expressions like > vartypeSplit = vartypePattern.match("float") > are always splitted into two strings. The result is: > vartypeSplit.groups() = ('flo', None, 'at'). I think I see your problem. Let's take a simplier pattern, "(a*)(a*)", that says to match "zero or more a's followed by zero or more a's". If you feed it a string like "aaa", it's ambigious. Any of the following matches would satisfy the basic pattern: ()(aaa) (a)(aa) (aa)(a) (aaa)() This is sort of what's going on here. Your regex is: ([a-zA-Z]+)(\(.*\))*([^(].*[^)]) which breaks down into three groups: ([a-zA-Z]+) # one or more letters (\(.*\))* # any string inside ()'s, zero or more times ([^(].*[^)]) # any char not '(', any string, any char not ')' In your case, the first group matches "flo", the next group matches nothing, and the third group matches "at". It's not what you expected, but you've got an ambigious RE, and this is one of the (many) ways the group matches could be satisfied. Looking at your english description of the pattern: > vartype is a simple string(varchar, tinyint ...) which might be > followed by a string in curved brackets. This bracketed string is > either composed of a single number, two numbers separated by a comma, > or a list of strings separated by a comma. After the bracketed string, > there might be a list of further strings (separated by blanks) I don't think you described it right. If the bracketed string is missing, and "list of further strings" is present, there needs to be whitespace between the vartype and the beginning of the list, right? I'm not completely sure this can be expressed in a single regex. I suspect it can, but I also suspect it's more trouble than it's worth. I think it would be simplier (and clearer) to break this up into a couple of steps. First match the vartype and remove it from the string (re.split, slicing, whatever). Then see if what you've got left starts with a '('. If if does, match everything up to the ')' and remove it from the string. What's left is the "list of further strings". It's a bit more verbose than one huge regex, and most likely slower too, but it'll be a lot easier to read and debug. You should only worry about it being slower if profiling shows that this is a critical section of code. From missive at frontiernet.net Wed May 26 16:19:38 2004 From: missive at frontiernet.net (Lee Harr) Date: Wed, 26 May 2004 20:19:38 GMT Subject: Help:What does this mean? References: Message-ID: On 2004-05-25, kr wrote: > Hello, > I am new to PytonWin. I have a simple script, just one line-- print "hello". > It runs OK when I use File/Run > But in command line >>> Script1.py > I got the error msg: > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'Script1' is not defined > > What's wrong with it? How can I fix it? > THKS > kr > > That is not a "command line" per se. It is the "interactive interpreter" By typing Script1.py You are asking the interpreter to find an object called "Script1" and then find the "py" attribute of that object... kind of like this: >>> class PyScript: ... def __init__(self, pyosity): ... self.py = pyosity ... >>> Script1 = PyScript('mega') >>> >>> Script1.py 'mega' On the other hand, if you have saved a python script in a file called Script1.py and you want to run that script from the interactive interpreter you can (as someone else pointed out) import Script1 Most likely, you will want to create functions in your module instead of just having a script, so that you could do something more along the lines of import Script1 Script1.main() From faisal at nasim.org Sat May 29 01:56:17 2004 From: faisal at nasim.org (Faisal Nasim) Date: Sat, 29 May 2004 00:56:17 -0500 Subject: Email address has changed [auto-generated] Message-ID: [ This is an automatically generated message ] Hey there!! Due to excessive amounts of spam, I've closed this mailbox! My email has changed to WHIZKID at NASIM.ORG Please email me there! Thank you. Regards, Faisal Nasim P.S. This email is sent to everyone who sends a message at faisal at nasim.org. If you didn't send a message, please check your system for viruses. From chris.cavalaria at free.fr Wed May 5 13:46:14 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Wed, 05 May 2004 19:46:14 +0200 Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> Message-ID: <40992866$0$12738$636a15ce@news.free.fr> Brian Quinlan wrote: > The problem is that we now have a migration problem. Most of our > develoeprs are using VIM which, AFAIK, is not intelligent enough to > detect the current indentation style of a file. Modifying all of our > source files at once to use spaces and then getting everyone to change > their .vimrc is a posibility but not desirable because everyone would > have to check in their work (whatever it's state) at the time of > migration. Does anyone have any suggestions? Ideally, there would be > some way to tell VIM to use the file's exsiting indentation style. That > way I could slowly switch to spaces over time. > > Cheers, > Brian Try adding that line at the end of each modified file : # vim:sw=4:softtabstop=4:expandtab It tells vim all the commands it should automatically run when it opens the file and it should get you the correct behaviour for 4 spaces no tab indentation. From eriksp at attbi.nospam.com Fri May 21 19:10:22 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 21 May 2004 23:10:22 GMT Subject: Python Newbie References: <3c0a04e4.0405211434.6667f727@posting.google.com> Message-ID: Just a random question; do you go to Amherst College in the summer for cybercamps? From guettli at thomas-guettler.de Wed May 26 10:43:45 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 May 2004 16:43:45 +0200 Subject: sys.stdout linebuffered References: Message-ID: Am Wed, 26 May 2004 09:40:01 -0400 schrieb Peter Hansen: > Thomas Guettler wrote: > >> I start a long running script like this (unix): >> >> nohup foo.py > foo.log & > [snip] >> The "-u" switch is not an option. > > That statement is suspect, and like Benjamin I wonder whether > it really is true. I like to use #!/usr/bin/env ===> cat minus-u.py #!/usr/bin/env python -u ===> ./minus-u.py /usr/bin/env: python -u: No such file or directory > Nevertheless, in the unlikely case that you > absolutely cannot use the -u switch, look at the description of > that option in the output of "python -h" and use the environment > variable mentioned there instead. The environment variable has the drawback, that I need to set it before every call to this script. Other scripts should not be unbuffered. Thomas From me at privacy.net Sat May 22 09:13:39 2004 From: me at privacy.net (Heather Coppersmith) Date: 22 May 2004 09:13:39 -0400 Subject: Python compilers? References: <7xzn81rue6.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 22 May 2004 05:54:24 GMT, Carl Banks wrote: > ... There's two questions remaining for me: > 1. These claims that Lisp code can approach 50 percent the speed > of C, is that with or without the optional type declarations? That would be *with* type declarations. > 2. If you don't use the declarations, does compiling Lisp help? > If it does (and nothing I've read indicated that is doesn't), > it definitely casts some doubt on the claim that compiling > Python wouldn't help. That's kind of been my point all > along. In _Common Lisp The Language, Second Edition_, by Guy Steele (CLTL2), on page 686, in section 25.1.3 ("Compilation Environment") there is a lengthy list of assumptions the compiler makes, including: o ... within a named function, a recursive call to a function of the same name refers to the same function [barring notinline declarations] ... o ... a call within the file being compiled to a named function that is defined in that file refers to that function [barring notinline declarations] ... o ... the signature (or "interface contract") of all built-in Common Lisp functions will not change ... o ... the signature (or "interface contract") of functions with ftype information will not change. o ... any type definition made with defstruct or deftype in the compile-type environment will retain the same definition in the run-time environment. It may also assume that a class defined in the compile-time environment will be defined in the same run-time environment in such a way as to have the same superclasses and metaclass ... o ... if type declarations are present in the compile-time environment, the corresponding variables and functions present in the run-time environment will actually be of those types ... So compiled Lisp is a less dynamic than Python, and the built-in functionality is large and guaranteed to match its textbook definitions, which gives Lisp Compilers more than a fighting chance. I'm pretty sure I've seen that summary on c.l.p before. > I think (and I'm wrapping this up, cause I think I made my > point) compiling Python could help, even without type > declarations, but probably not as much as in Lisp. It could > still make inferences or educated guesses, like Lisp compilers > do; just maybe not as often. I agreem, with emphasis on "could" and some hesitation on how much guessing I want my compiler to do. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From __peter__ at web.de Thu May 6 03:44:45 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 09:44:45 +0200 Subject: Ideas for Python 3 References: Message-ID: Josiah Carlson wrote: > How about this for a manual page for lambda... > > In other languages, Python's lambda would be considered an 'anonymous > function', that is, a function that does not require a name.: > > >>> (lambda arg: arg*arg)(9) > 81 > > Certainly you can give lambdas names with standard assignments.: > > >>> square = lambda arg: arg*arg > >>> square(9) > 81 > > The equivalent function definition is below.: > > >>> def square(arg): > ... return arg*arg > ... > >>> square(9) > 81 > > Generally, lambdas are functions with a single expression in its body > whose value is returned. Just like normal function definitions, lambdas > can take multiple arguments, contain keyword arguments, return any > Python type, etc., as long as the function body is a single expression, > and whose parameters match standard function definition syntax, the > lambda is valid. (leave annotation and/or link to what an expression is) I suggest that you submit the above as a patch for the tutorial http://www.python.org/doc/current/tut/node6.html. Currently there is an example with a nice trick which has nothing to do with lambda. Your more straightforward example demonstrates how simple lambda really is. > An ugly example of this is as follows.: > > >>> f = lambda a, b=1, *args, **kwargs: (a, b, args, kwargs) > >>> f(1,2,3,c=4) > (1, 2, (3,), {'c': 4}) > > Which is equivalent to: > > >>> def f(a, b=1, *args, **kwargs): > ... return (a, b, args, kwargs) > ... > >>> f(1,2,3,c=4) > (1, 2, (3,), {'c': 4}) At this point of learning the language a newbie may or may not be comfortable with the *args, **kw special arguments. As their usage is completely orthogonal to functions/lambdas I wouldn't mention them here. Peter From davidf at sjsoft.com Mon May 17 06:48:47 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 17 May 2004 12:48:47 +0200 Subject: trouble!!! In-Reply-To: <20040516150615.21491.00001513@mb-m10.aol.com> References: <20040516150615.21491.00001513@mb-m10.aol.com> Message-ID: Strappo wrote: > Please help!!! our news feed server is down after redhut up2date bugfixes > applied This is because you need to reinstall the postgres database module PyGreSql, you may need to check for an RPM for it or upgrade it. But ask for help here if you don't come right... David > > iLia Anossov > http://trueFresco.Org > > > [root at 216-55-133-44 root]# /etc/init.d/webppliance start > Traceback (most recent call last): > File "", line 2, in ? > File "virtualhosting/virthost.py", line 50, in ? > File "virtualhosting/modules/__init__.py", line 47, in ? > File "telnet/virthost_actions.py", line 6, in ? > File "virtualhosting/virthost.py", line 50, in ? > File "virtualhosting/modules/__init__.py", line 47, in ? > File "telnet/virthost_actions.py", line 9, in ? > File "virtualhosting/db/__init__.py", line 3, in ? > File > "/home/build/qa/webppliance/3.5.18/23/lwp/prakash23/WebGui/common/appldb.py", > line 7, in ? > File "/usr/lib/python2.2/site-packages/pgdb.py", line 56, in ? > ImportError: No module named _pg > Starting webppliance: [FAILED] > Traceback (most recent call last): > File "", line 2, in ? > File "virtualhosting/virthost.py", line 50, in ? > File "virtualhosting/modules/__init__.py", line 47, in ? > File "telnet/virthost_actions.py", line 6, in ? > File "virtualhosting/virthost.py", line 50, in ? > File "virtualhosting/modules/__init__.py", line 47, in ? > File "telnet/virthost_actions.py", line 9, in ? > File "virtualhosting/db/__init__.py", line 3, in ? > File > "/home/build/qa/webppliance/3.5.18/23/lwp/prakash23/WebGui/common/appldb.py", > line 7, in ? > File "/usr/lib/python2.2/site-packages/pgdb.py", line 56, in ? > ImportError: No module named _pg > From yuba at cyberback.com Tue May 25 17:24:17 2004 From: yuba at cyberback.com (yuba at cyberback.com) Date: Tue, 25 May 2004 16:24:17 -0500 Subject: SQL Server Message-ID: <22cd9806fec34793877c4662b185a3d1.yuba@cyberback.com> Greetings, All- About 2 months ago I was laid off and in the process of being walked to the door I lost most of my Python tips and tricks. Looks like I'm back on the air with a great job and am ready to start coding again. I'd like to know what I have to do to connect to a Microsoft SQL server database. I did it at my old job but forgot the process. Thanks for your help. BTW, I'm the first full-time programmer in this particular shop and they are quite interested in using Python as their language of choice! This could be a lot of fun. Greg Lindstrom From ptmcg at austin.rr._bogus_.com Tue May 18 17:06:24 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 18 May 2004 21:06:24 GMT Subject: alternatives to making blocks like { } or other ?? References: Message-ID: "Larry Bates" wrote in message news:FJCdnVqIN7iG8TfdRVn-vg at comcast.com... > Blocks in Python are defined not with {} but rather > with indention. You indent to start a block and > stop indenting when you wish to end it. Seems odd > at first, but turns out to be excellent way to > handle blocks (and to properly format you code). > > HTH, Larry Bates > > "CYBER" wrote in message > news:c8do0u$9fb$1 at news.atman.pl... > > Hello > > > > Is there any other way under python to create blocks ?? > > > > instead of > > > > def sth(x): > > return x > > > > > > > > could i use something else like > > > > def sth(x): > > { > > return x > > } > > > > > > ??? > > ... and no religious wars on where the braces are supposed to go, HOORAY!!! And I'll second Larry's comment - it takes about 10-20 minutes to get used to, but then you just focus on indentation, and it seems *very* natural - liberating, even! -- Paul From gabor at z10n.net Mon May 24 05:09:07 2004 From: gabor at z10n.net (gabor) Date: Mon, 24 May 2004 11:09:07 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <1085389747.13786.12.camel@dubb> On Sun, 2004-05-23 at 21:46 +0000, Neil Hodgson wrote: > gabor: > > > hmmm...i understand that you can cast away const, > > but what about... > > > > class C > > { > > private x; > > }; > > Technique 1: > > class D { > public: > int x; > }; > > C c; > (reinterpret_cast(&c))->x = 1; > > Technique 2: > > #define private public > #include > #undef private > > C c; > c.x = 1; > thanks...very interesting. > In both of these it is obvious that the encapsulation rules are being > broken which is exactly the same situation as when someone uses the mangled > name in Python. I have used technique 2 in production code where a library > could not be altered and access to private methods was required. look...i am not asking for a way in python to COMPLETELY RESTRICT the access to a variable... i hint is enough... now...if i know correctly that means that i have to prefix my wanto-to-be-private variables with a "_"... that restriction would be enough for me. my problem is with the syntax. i HATE anything that even remotely resembles perl/hungarian notation. why cannot i do it somehow as we create static-methods .... class C: def __init__(self): self.lenght = 5 self.lenght =private(self.length) or something like it. the point is: i only want to WRITE that the variable is private once... i don't want to deal with _prefixed variables in my whole code... this is imho of course gabor From dominpe at dominpe.com Wed May 19 07:48:15 2004 From: dominpe at dominpe.com (=?ISO-8859-1?Q?Juan_Antonio_Dom=EDnguez_P=E9rez?=) Date: Wed, 19 May 2004 13:48:15 +0200 Subject: PERT for python Message-ID: Can anoyone let me know if there is a standar PERT algorithm implementation in python? Thanks in advance. -------------------------- Juan Antonio Dom?nguez P?rez http://www.dominpe.com From nicksjacobson at yahoo.com Sun May 23 17:54:24 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 23 May 2004 14:54:24 -0700 Subject: Downloading SCXX References: Message-ID: Peter Hansen wrote in message news:... > Nick Jacobson wrote: > > > I've been trying to download SCXX, but the website > > http://www.mcmillan-inc.com/ has been down for the last few days. > > Where else can I find it? Thanks in advance. > > I believe attempts to reach mcmillan-inc.com have failed for the > last few *months*, not just the last few days. I don't recall > seeing any comment about it except (or did I just imagine it?) a > comment from someone that Gordon was indeed alive, but occupied > with other things... > > -Peter Is there anywhere else I can get SCXX from? Thanks. From peter at engcorp.com Sat May 1 22:07:24 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 May 2004 22:07:24 -0400 Subject: Efficient string concatenation methods In-Reply-To: References: Message-ID: Oliver Crow wrote: > http://www.skymind.com/~ocrow/python_string/ > > I'd be happy to hear if anyone else has done similar tests and if > there are any other good candidate methods that I missed. You left out the StringIO module (having done only the cStringIO version of that). Note also that, for any of the ones which do method calls, you can speed up the call by saving a reference to the bound method in a local variable. For example, in method 4 you can do "app_list = str_list.append" and then use "app_list(`num`)" instead of str_list.append(`num`). This saves an attribute lookup on each loop iteration. It's not "idiomatic" to do so except in (a) cases of optimization obsession, or (b) benchmarks. ;-) Interesting and useful results. Thanks! :-) -Peter From apardon at forel.vub.ac.be Tue May 25 05:46:46 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 May 2004 09:46:46 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> Message-ID: Op 2004-05-24, David MacQuigg schreef : > On Mon, 24 May 2004 14:39:11 +1200, Greg Ewing > wrote: > >>David MacQuigg wrote: >> >>> Nobody seems to understand that lambda functions, static methods, etc. >>> are clutter. >> >>On the contrary, lambda has long been regarded as a wart >>for various reasons. The best way to fix it is probably >>to just drop it altogether. Nothing essential would be >>lost. > > If "lambda functions" were nothing but functions with the name left > off, they would serve their current purpose, and they would not be > such a problem that there is talk of actually taking them *out* of the > language. They aren't essential, but they do serve a purpose which > some feel is important. The only "importance" is that you are not obligated to write down a proper function definition when you only want to provide an expression as a function argument. >>We don't see static methods as clutter, because for the >>most part we don't see them (i.e. we don't normally use >>them). It would be no great loss if they were dropped, >>too. > > I would see it as a loss. The next best alternative is to move the > static method outside of the class, and that puts an arbitrary > restriction on how I can structure my programs. If the person writing > the program feels that the function belongs in the class, let's not > say it can't be done because either a) The syntax doesn't allow it. or > b) We assume he is wrong in thinking his function belongs inside his > class. > > My perspective may be different, because I have not yet absorbed the > Python traditions, and I don't have any instictive avoidance of static > methods. I never felt the need for static methods, and I still don't think of my self as having absorbed the python traditions. Maybe the questions is, where do you get your instinct from to use static methods? -- Antoon Pardon From tim.one at comcast.net Thu May 13 16:09:10 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 13 May 2004 16:09:10 -0400 Subject: struct doesn't handle NaN values? In-Reply-To: Message-ID: [Grant Edwards] > Perhaps I'm doing something wrong: Not really. > the struct module docs say it's IEE 754, but I can't figure out > how to get it to handle NaN values correctly (either packing or > unpacking). All Python behavior in the presence of 754 special values (infs, NaNs, signed zeroes) is a platform-dependent accident. There's a growing list of these in PEP 42 (under "Non-accidental IEEE-754 support"), but nobody even bothers to keep that up to date. > >>> x = float('nan') It's even an accident that this line didn't raise an exception (it does, for example, under the Windows Python). > >>> struct.pack(" Traceback (most recent call last): > File "", line 1, in ? > SystemError: frexp() result out of range An accident of what your platform C's frexp() happens to do with a NaN. > >>> struct.unpack(" References: <2698610F.45B3F62@mail.gmail.com> Message-ID: <26BAFE56.6D64E159@mail.gmail.com> I am surprised no one has mentioned Dive Into Python, a free, "open-source" Python book by Mark Pilgrim. It doesn't take the typical approach of going through each language feature one at a time, but I found that his approach was easily digestible and the information is presented very deliberately. It is written for a programmer audience, so it doesn't spend any time going explaining basic concepts like inheritance and introspection. I spent a few days reading through it a few months ago and quickly got up to speed with Python. http://www.diveintopython.org Ken On Thu, 29 Apr 2004 20:13:40 GMT, Sarge wrote: > > Hi, > I'm newbe of python, but not of programming (a lot of Matlab, some > C, a bit of C++), I want a *good* book on python for self-study. > I'm short of money, I don't want to make any mistakes, so does > anybody have any suggestions (buy this-don't buy that)? > > Thanx, > Sarge > -- > http://mail.python.org/mailman/listinfo/python-list > From mhuening at zedat.fu-berlin.de Fri May 28 07:13:16 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 28 May 2004 11:13:16 GMT Subject: py2exe encoding Message-ID: Hello, I have got a Tkinter application which works just fine (Python 2.3.4, WinXP). I made a standalone version of it by using py2exe (0.5.0). Everything seems okay, but when running this application I am confronted with the following error: "no codec search functions registered: can't find encoding". Any suggestions? Matthias From dave at pythonapocrypha.com Fri May 14 15:22:01 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 14 May 2004 13:22:01 -0600 Subject: RELEASED Python 2.3.4, release candidate 1 References: Message-ID: <041e01c439e8$bbb95de0$6b1e140a@YODA> Chris wrote: > >WINDOWS > >... Windows users may also be > >interested in Mark Hammond's win32all, a collection of > >Windows-specific extensions including COM support and Pythonwin, an > >IDE built using Windows components. > > > > > PS... I have moral and ethical arguments against this. Really? What are they? > I believe it's just plain WRONG to use a language like > Python or Java or even C#/.NET and RELY on platform specific "extensions". Because _____? That seems silly to me, but to each his own, I guess. Hands down, some of the most amazing uses of Python I've seen are in conjunction with platform-specific extensions on both Linux and Windows. But I'm not all that interested in swaying your opinion, because that's often where the most money is as well, so it's good to know I won't lose any business to you. ;-) -Dave From mcherm at mcherm.com Thu May 6 13:07:04 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 6 May 2004 10:07:04 -0700 Subject: Needed: Python IDE for the visually impaired Message-ID: <1083863224.409a70b8d8452@mcherm.com> I received a request from John Guildford, asking whether there is an IDE available for Python development which will work with Window-Eyes, Jaws, or other common screen readers. Unfortunately, IDLE will not work (presumably because the TK widgets are not standard windows widgets). Does anyone have a suggestion about IDEs to use in this circumstance? Advice from other developers with visual impairments would be particularly welcome. In addition to responding to the list, could you please CC John at "jglists at ntlworld.com". -- Michael Chermside ----- John's original email ----- > Greetings, > could you forward this email to the relevant person(s) please? > My name is John and I have just begun learning Python. I am > visually-impaired which means that I use adaptive software on > my computer > in order to gain access to the Windows platform. The program > - window-eyes > - is a very effective tool for fully utilising most > off-the-shelf software > packages albeit problems do pop up occasionally. > Unfortunately, the Python > GUI interpreter falls in the category of the few products > which cannot be > access with Window-Eyes or Jaws - its main rival - for that > matter. the > message from Window-Eyes is that the Python edit window is in > fact a custom > control. Normally the problem can be remedied by, as it > were, re-classing > the control but on this occasion even that does not seem to > be possible. > my question is, is there an alternative to the Python interpreter for > learning and developing programs in Python which use > "standard" controls > or, better still, could the developers of IDLE make the > necessary changes > in the future releases of the program? > So far I have been relying on the Python commandline utility > but as you can > appreciate this has its limitations. so I would be very > grateful if you > could respond to my email with a solution. > All the very best, > John Guildford From michael at foord.net Fri May 14 11:08:30 2004 From: michael at foord.net (Fuzzyman) Date: 14 May 2004 08:08:30 -0700 Subject: Troubles with CSV file References: Message-ID: <8089854e.0405140708.100cf34c@posting.google.com> "Vladimir Ignatov" wrote in message news:... > Hello! > > I have a big CSV file, which I must read and do some processing with it. > Unfortunately I can't figure out how to use standard *csv* module in my > situation. The problem is that some records look like: > > ""read this, man"", 1 > > which should be decoded back into the: > > "read this, man" > 1 > > ... which is look pretty "natural" for me. Instead I got a: > > read this > man"" > 1 > > output. In other words, csv reader does not understand using of "" here. > Quick experiment show me that *csv* module (with default 'excel' dialect) > expects something like > > """read this, man""", 1 > > in my situation - quotes actually must be trippled. I don't understand this > and can't figure out how to proceed with my CSV file. Maybe some > *alternative* CSV parsers can help? Any suggestions are welcomed. > > Vladimir Ignatov I have written a very simple CSV parser which uses a simple function 'unquote' to unquote quoted elements. It would be *very* simple to amend unquote to handle double-quoted elements. http://www.voidspace.org.uk/atlantibots/pythonutils.html Regards, Fuzzy From noemail at noemail4u.com Wed May 12 10:35:34 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Wed, 12 May 2004 14:35:34 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: <8fff3ffd3e29a30d3600ff041cf21056@news.teranews.com> On 11 May 2004 12:05:52 GMT, Oliver Fromme wrote: >Daniel 'Dang' Griffith wrote: > > [on sed] One reason > > to install it is that it's smaller than perl or python; another is > > that it probably performs the task faster, since it isn't a general > > purpose state machine; > >FWIW, sed _is_ a state machine, although not really "general >purpose". It is a programming language with variables, loops >and conditionals, and I believe it is turing-complete. Most >of the time it is abused to perform simple search-and-replace >tasks, though. ;-) I never used sed for anything but "stream editing", aka search and replace. Well, if it's turing complete, my apologies to the sed author(s). :-) --dang From bstoyanov at dspace.de Fri May 14 09:35:20 2004 From: bstoyanov at dspace.de (questioner) Date: Fri, 14 May 2004 09:35:20 -0400 Subject: How do I start from python sth like "MyExe.exe InFile"? Message-ID: <28bcfc204dec5fe9060a7b0d1b0fba47@localhost.talkaboutprogramming.com> Hi folks, Id appreciate if you can help: I want to start an exe which takes as an argument filename. What I tried was: os.spawnl(os.P_NOWAIT,('processor.exe'),'filename.ext')) I also tried: os.execl(r'DRIVE:\WINNT\system32\cmd.exe', '/k',('processor.exe'),'filename.ext')) but is simply the command line and stopped. However I didnt achieve the expected result and got some number like: 788. Can anyone help? Thanx in advance From alex.santos at gmx.net Wed May 5 12:13:18 2004 From: alex.santos at gmx.net (Alex Santos) Date: Wed, 5 May 2004 18:13:18 +0200 Subject: urllib proxy question? Message-ID: i wrote a python prog that reads a url via urlib to find out the public ip of the computer, my problem is that, if someone sets a proxy in teh internet explorer, the urllib works also over a proxy and i dont get the right public ip of my computer? has sombody an idea, how to disable this behavior of the urllib? thanks, alex From tim.one at comcast.net Wed May 12 17:22:35 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 12 May 2004 17:22:35 -0400 Subject: Integer division, surprising results In-Reply-To: <84k6zhsvxi.fsf@tecont.de> Message-ID: [Tim, on Python's floor division] >> It's primarily driven by the desire that i%j have the same sign as j. [Ralf Muschall] > That's the side effect, not the desire (AFAIK). In Python, it was deliberate: Guido and I agreed on this behavior before Python's first public release, and it was indeed primarily driven by the desire to have i%j >= 0 whenever j > 0. Other languages have their own reasons. For example, C99 mandates "the wrong" behavior here (where C89 was silent), and for no reason other than "because that's what Fortran did". ... > [1] I don't know whether it also offers a shortcut for > sign(x)*mod(abs(x),y) for people who insist on the bad result. Python's math.fmod() behaves like the platform C fmod() function. There's special value in that when dealing with floating point inputs, because it's impossible for fmod() to be exact in all cases unless the result has the same sign as the first argument. For example, fmod(-1, 1e300) == -1. If the result had to have the same sign as the second argument, then the true result is the unrepresentable (as a 754 double) 1e300 - 1. Python's % operator applied to integers makes a lot of sense, but not-- alas --when applied to floats. From kirk at strauser.com Wed May 26 15:15:10 2004 From: kirk at strauser.com (Kirk Strauser) Date: Wed, 26 May 2004 19:15:10 GMT Subject: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <1X4tc.71833$hH.1301889@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <87d64rq9v0.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-05-26T18:00:29Z, "Andrew Koenig" writes: > $Prefixing @names with @symbols like $ and @ $is a great @idea - it $makes > the "@nouns" (@variables) $stand out from "@verbs" and $makes the @code > $flow like natural @language, $making $reading it easy and $writing it fun! I ran that through Perl and got a mildly functional spreadsheet application. A few more lines, and I think you could've added the flight simulator. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAtOya5sRg+Y0CpvERAm5OAJ9sjhZPhu2iVU3pdH+jiM2eb3udowCeNpJr O9ca+ZS3J4lFI5gnQKTOOZI= =NXmP -----END PGP SIGNATURE----- From sean_berry at cox.net Mon May 3 20:47:54 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 3 May 2004 17:47:54 -0700 Subject: Question about glob.glob <--newbie Message-ID: >>> r = glob.glob('/*') >>> r ['/dev', '/usr', '/stand', '/etc', '/cdrom', '/proc', '/bin', '/boot', '/mnt', '/modules', '/root', '/sbin', '/tmp', '/var', '/sys', '/COPYRIGHT', '/kernel.GENERIC', '/kernel', '/compat', '/home', '/kernel.old', '/modules.old'] >>> >>> r = glob.glob('/usr/websites/*') >>> r [] I can do a >>> import os >>> dirs = os.system('ls /usr/websites') and that works. Why doesn't glob.glob work on /usr/websites? What I am trying to do is write a simple script that will recursively search for and replace key words in all files. I am doing this mainly for practice since I already can write a shell script or use an awk/sed combo. Does anyone have anything that does a similar task? Thanks From greg at cosc.canterbury.ac.nz Mon May 24 01:25:12 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 17:25:12 +1200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <2hdf9qFbl744U1@uni-berlin.de> gabor wrote: > class C > { > private x; > }; > > so, how can you write to that variable from the outside? You write your own .h file which is exactly the same except that it doesn't say "private". This probably isn't any safer than casting, but the point is, if you're going to these lengths you know what you're trying to do and probably have a good reason for it. Exactly the same thing applies to Python name mangling. You're prevented from accidentally messing with things, not from deliberately messing with them. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From me at privacy.net Mon May 10 22:25:06 2004 From: me at privacy.net (Heather Coppersmith) Date: 10 May 2004 22:25:06 -0400 Subject: Python job opening at GPO in Washington, DC References: <2g9s2hF96nhU1@uni-berlin.de> Message-ID: On 10 May 2004 15:33:58 -0400, Nick Vargish wrote: > This wouldn't be the first place where my fondness for things > that work has gotten me into trouble ... I nominate that as Quote of the Week. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From mark_mitwrong at wrongbellsouth.net Thu May 27 23:15:10 2004 From: mark_mitwrong at wrongbellsouth.net (Mark Mitchell) Date: Fri, 28 May 2004 03:15:10 GMT Subject: Non-programmer needs help with PyGTK-2.0.0 Message-ID: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I have a program written in python that tells me it requires PyGTK, so I DLed, ./configure, make, make install and the process seems to go ok. Some errors but the process finishes so I assumed they weren't fatal errors. So now I attempt to run my python program and I get; $ gccp.py Traceback (most recent call last): File "./gccp.py", line 9, in ? import pygtk ImportError: No module named pygtk I'm running Slackware 9.1 with a 2.6.6 kernel, and I don't know what other information would be helpful. Mark - -- Remove both wrongs to make the email address right. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAtq9mLVmEOl6/PWERAhQlAJ9tftg6Bul2uBsi+4kxUbOQpXKuyACfV9WG zC11tY3NhVmBqye0QPiYwoY= =G1KG -----END PGP SIGNATURE----- From asmirnov1234567890 at yahoo.com Tue May 25 09:18:18 2004 From: asmirnov1234567890 at yahoo.com (Andrei Smirnov) Date: 25 May 2004 06:18:18 -0700 Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: <9ace45f.0405250518.2803e7b0@posting.google.com> Peter Hansen wrote in message news:... > Andrei Smirnov wrote: > > > i do really suffer. i have to use Perl and i know that i have no chance > > to convince my new boss (very smart guy) to switch to Python because of > > braces. > > Clearly your new boss is *not* very smart, or is insane. there are many smart people who are not familiar with any aspect of this discussion (and other way around). so, don't make judgement based on preferences. > No sane, intelligent person would reject Python *solely* because it > doesn't use braces. Maybe that plus some other reasons, but not as the > *only* reason... sure it is not only reason. as usual the only reason: there are a lot of code we wrote on perl and ... well, there is such thing as initial impression. and python initial impression for (smart or stupid) guy who was using C for years is like swap brake and gas pedal in the car. why should anybody do this? the real fact is that C-look is everywhere and it is affecting decision-making process in this way. BTW, people using computer languages not only for full-time job (like myself till recently) or to build stupid websites but also to do some usefull things :) i took me about two days to get used to python indentation. and it is actually not very hard to convince your friend to do it. but things are very different in any industry and when you interacting with your boss. i will be surprised if this arguments will convince anybody here but i need some relief before i get back to perl (that's part of my job). > > -Peter Andrei From buzzard at urubu.freeserve.co.uk Sat May 29 09:40:28 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 29 May 2004 14:40:28 +0100 Subject: UK Social research job to suit Excel programmer (not necessarily VBA) Message-ID: http://www.man.ac.uk/news/vacancies/research.html#581 Duncan Smith From rstephens at vectron.com Sun May 2 23:43:05 2004 From: rstephens at vectron.com (Ron Stephens) Date: 2 May 2004 20:43:05 -0700 Subject: Embedded Python Tutorials References: Message-ID: Wow, looks like great tutorials! I have just one suggestion though: perhaps you could put a link to Part Two at the end of the Part One Tutorial, so folks could just continue to follow on. Maybe its there already, and I just can't find it, but if not, a learner might finish Part One and not realize there is a Part Two, or where to find it. Ron Stephens the Python Learning Foundation From has.temp2 at virgin.net Mon May 3 05:27:43 2004 From: has.temp2 at virgin.net (has) Date: 3 May 2004 02:27:43 -0700 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> <8ef9bea6.0405020828.5eafbd5c@posting.google.com> Message-ID: <69cbbef2.0405030127.65aaa9b4@posting.google.com> hungjunglu at yahoo.com (Hung Jung Lu) wrote in message news:<8ef9bea6.0405020828.5eafbd5c at posting.google.com>... > When one has not even tried, and starts to make criticisms like > "unification means elimination, I will have to use my shoes to store > my soup", it brings nothing but regrets. ROTFLMAO! I shall frame and mount this line at once! has (green with envy...;) From jacek.generowicz at cern.ch Mon May 10 11:10:24 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 May 2004 17:10:24 +0200 Subject: What I don't like about wxPython References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: Ryan Paul writes: > now i'm curious. are there ANY gui toolkits that arent blatantly > windows-centric? Personally, I HATE the windows user interface paradigm, > but it seems to be pretty much ubiquitous regardless of your operating > system. GTK, Photon, Aqua, QT, Swing, VCL... all of them have toolbars, > menus, checkboxes, etc. They are all just variation on a theme, so to > speak. If you know of a command oriented graphical interface, i'd love to > hear about it. ;-) If you want to _hear_ (or read) about a different style of graphical user interface, then maybe CLIM is of interest to you. If you want to _use_ one in Python tomorrow ... then CLIM is probably not what you want. From jjl at pobox.com Sat May 29 07:26:59 2004 From: jjl at pobox.com (John J. Lee) Date: 29 May 2004 12:26:59 +0100 Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <87y8ndilmd.fsf@pobox.com> <0tteb013e1vb8frmt1phakm5oi5635sh0m@4ax.com> Message-ID: <87hdtzeanw.fsf@pobox.com> Manlio Perillo writes: > On 27 May 2004 22:52:10 +0100, jjl at pobox.com (John J. Lee) wrote: [...] > >You can just say: > > > >ClientCookie.urlopen("http://www.example.com/") > > > >and be done with it. > > > > I have seen the module, but it is too complicated. Having written it, I agree, but I don't think it's my fault . > Standard Cookie module (with my corrections) plus httplib module is > really all I need. Cool. John From ssvendsen at atmel.com Tue May 11 05:07:37 2004 From: ssvendsen at atmel.com (Svenn-Ivar Svendsen) Date: 11 May 2004 02:07:37 -0700 Subject: msscript & python: problems accessing objects inserted by msscript->AddObject Message-ID: <67c8710b.0405110107.f87f581@posting.google.com> I'm implementing a windows application with generic support for scripting, and I'm using the microsoft script control (msscript). For vbscript/jscript I'm happy, but with python I got problems accessing COM objects that have been inserted in the script runtime by the msscript->AddObject function. Have anybody had similar problems? To be more specific the code: Monitor.Echo(logTxt, output) where 'Monitor' is a COM object aready inserted by msscript->AddObject(..) results in a runtime error where the top stack trace shows: File "C:\PROGRA~1\Python23\lib\site-packages\win32comext\axscript\client\pyscript.py", line 146, in __getattr__ return self._scriptItem_.subItems[string.lower(attr)].attributeObject AttributeError: 'NoneType' object has no attribute 'subItems' Regards, SIS From fredrik at pythonware.com Wed May 26 16:22:51 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 22:22:51 +0200 Subject: prefix matching References: Message-ID: Christian Gudrian wrote: > I started by composing a regular expression pattern which consists of all > the strings in the list separated by "|" in a for loop. Then I used that > pattern to do a regexp match. > > Seems rather complicated to me. Any alternatives? does it work? is it fast enough? (if the answer is yes and yes, what's wrong with you ;-) From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Wed May 5 19:33:06 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 6 May 2004 01:33:06 +0200 Subject: MySQL vrs SQLite References: Message-ID: >>> doesn't SQLite store its data in memory? No ! It's the database-engine who is in embeddable. The data are stored in one file per database. From greg at cosc.canterbury.ac.nz Thu May 6 23:20:09 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 07 May 2004 15:20:09 +1200 Subject: Unification of Methods and Functions In-Reply-To: References: <16752bcc.0405050817.4ca77017@posting.google.com> Message-ID: <2g0djeF32s1kU1@uni-berlin.de> David MacQuigg wrote: > We disagree on what is "waffle" and what are beneficial extra words. > Your explanation, to me, seems more like a "man page" than a textbook > explanation. The number of words used isn't really the issue here. Any explanation can be expanded or contracted to adjust the pace to the intended audience. What's important is the structure of the explanation, and whether the structure forms a logical flow of ideas that can be easily followed. The original explanation you quoted, it seems to me, is harder to follow than necessary because it takes a somewhat tortuous path to explaining what is going on. It starts out by saying "Some of the variables in this function are prefixed by 'self.'...", as if something very new and mysterious is being introduced. It then spends the next couple of paragraphs explaining this new concept. At the end of all this, the reader, if he/she is sharp enough, will realise that it isn't really a new thing at all, but just a particular application of something already encountered, namely attribute access. If he/she isn't sharp enough, he/she may be left thoroughly confused and still thinking it's some new mysterious feature. I was trying to show how the presentation could be made easier to follow by starting from the other end, and explaining how Python makes use of things already encountered -- parameter passing and attribute access -- to provide instance variables. In other words, your solution to badly-written tutorials appears to be to redesign the language. Mine, on the other hand, would be to re-write the tutorials so that they're better. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jacek.generowicz at cern.ch Tue May 18 07:41:43 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 18 May 2004 13:41:43 +0200 Subject: Python compilers? References: Message-ID: Leif K-Brooks writes: > Svein Ove Aas wrote: > > Is anyone working on a python-to-native compiler? > > I'd be interested in taking a look. > > What are you trying to achieve? > > If it's faster code execution, the primary slowdown with a very > high-level language like Python is caused by high-level data > structures (introspection, everything being an object, etc.), not the > code itself. A native compiler would still have to use high-level data > structures to work with all Python code, so the speed increase > wouldn't be very much. Oh please ! Native compilers for other languages just as dynamic as Python exist. These compilers manage to achieve very significant speed increases[*]. Psyco is a native compiler, of sorts, for Python, and it manages to produce dramatic improvements (in the areas where it works). While it's true that often speed doesn't matter, and many of the criticisms levelled at Python for being too slow are completely unfounded in real world situations, this is no reason for Pythonistas to a) be happy about the fact that Python is slow, b) be convinced that Python _must_ be slow. The sooner "we" stop believing that Python's flexibility comes at the unavoidable cost of piss-poor runtime performance, and the sooner we accept that it would be useful to have a Python which maintains its flexibility but runs like a bat out of hell (ie, the sooner we stop making excuses for Pythons lack of speed), the sooner we will get one. Fortunately there is already a bunch of people who understand this, and is trying to do something about it. [*] A prime example is the Common Lisp implementation CMUCL. Ironically enough, CMUCL's compiler is called ... Python. From skip at pobox.com Wed May 5 00:03:31 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 May 2004 23:03:31 -0500 Subject: doctest: address in output In-Reply-To: References: Message-ID: <16536.26515.655996.119410@montanaro.dyndns.org> >> > >>> mymodule.do_something() >> > >> >> Why not just change your doctest to be >> >> >>> import mymodule >> >>> isinstance(mymodule.do_something(), mymodule.coolObj) >> True >> >> ? That avoids two problems, the issue of addresses and the possibility that >> the repr() of your coolObj class changes. Param> Because the former seems to be *much* easier to read than the Param> latter. Param> The return value of the function is designed to be ignored in Param> normal use. Then make it return None and use a different function on those presumably rare occasions where you need it. Param> Doing something with it, like assigning it to a variable or using Param> isinstance() as you suggest, would make the documentation both Param> unclear as well as harder to read than it should be. My apologies. It was unclear to me that you intended this to be primarily documentation. I thought since you were running doctest it was primarily a test case. Param> Making a doctest hard to read would go against the purpose of Param> having doctests at all. I may as well use the unittest module Param> then. Maybe not if the "test" part of "doctest" is more important than the "doc" part. Skip From paul at grosss.net Sat May 15 13:38:49 2004 From: paul at grosss.net (Paul Gross) Date: Sat, 15 May 2004 12:38:49 -0500 Subject: Palm Address Book Archive In-Reply-To: <1640543.jVXVUEme3l@joefrancia.com> References: <1640543.jVXVUEme3l@joefrancia.com> Message-ID: That's perfect. Thank you. Paul Joe Francia wrote: > Paul Gross wrote: > > >>Does anyone know of a python module or script which can read the Palm >>Address Book Archives? Using Palm Desktop, I can export my addresses to >>a .aba file, but I can't find any code to use this file programmatically. >> >>I know that Palm Desktop can also export to comma and tab delimited >>files, but this isn't as good for a few reasons. One, there's no way to >>know what the custom fields are. Two, this method is dependent on how >>the data is exported (which columns are selected and in which order). >> >>Thanks. >>Paul > > > There's a script here: > http://www.geocities.com/Heartland/Acres/3216/palmrecs.htm > From segphault at sbcglobal.net Tue May 25 21:05:35 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 26 May 2004 01:05:35 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: On Wed, 26 May 2004 00:43:49 +0000, SeeBelow wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since a > strength of Python is rapid application development, it slows one down > to have to put in all those self.'s. The code seems much cleaner to me > without classes that have only one instance. Oh, also, all the methods > of this class will have to have the instance name prepended to them. > > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. > > Mitchell Timin defining a class may be useful if you plan on making more instances down the line. It's a good OO strategy. I do understand your dislike of 'self'. It does seem like clutter. In my code, I shorten it to 's'. In ruby, class variables are prefixed with an '@', which makes them easier to discern in code, and it is easier than typing 'self'. I wish python had something like that. I also think that having to specify the class variable in every function definition is a bit silly. Ruby gets rid of that too. --SegPhault From moughanj at tcd.ie Sat May 22 14:50:18 2004 From: moughanj at tcd.ie (James Moughan) Date: 22 May 2004 11:50:18 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> Message-ID: <16752bcc.0405221050.4f8711fc@posting.google.com> David MacQuigg wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... > On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: > >David MacQuigg wrote: > >> I've made your program, Animals_JM.py at > >> http://ece.arizona.edu/~edatools/Python/Exercises/ the next example > >> *after* Animals_2. The topic of techniques to make a program robust > >> and maintainable is worth a whole chapter, but it would be a > >> distraction in the introductory chapter. > >> > >> I would still like to see a way to gain the benefits of both Animals_2 > >> and Animals_JM in one program. My attempts to follow up on > >> suggestions in this discussion have only added complexity, not > >> improved the program. > > > >Simple method - choose a different example. However, you do not > >appear to be open to this suggestion. > > If I were not open to suggestions, I would not be spending all this > time patiently extracting the good suggestions from this long thread, > and putting up with dogmatic statements and personal attacks. I could > repond by saying most of what I'm reading is hot air, but that would > be equally provocative. Let's see if we can bring this to a better > conclusion. > > I like your example, but not as a *substitute* for Animals_2. It's > just too complex for non-CIS students at this point in the course. I > think I understand your concerns about Animals_2. I think the best > way to deal with those concerns is not by complicating the example, or > by taking out everything that could lead to problems, but rather by > pointing out the problems, and showing subsequent examples that fix > those problems, even at the expense of more complexity. > > If you have a simple all-in-one alternative to Animals_2, show me. > Again, clearly I have not communicated myself well - I mean a *completely* different example to the entire Animals approach. The difficulty with writing a good Animals-type example comes from the things which it is trying to do, which aren't especially well expressed by a class-heirarchy. Why not just take one of your earlier program examples, show the students what it looks like when object-oriented, then extend the class(es)? As I've mentioned, I don't like my example *at all* for your teaching purposes, and I'm not suggesting you use it. It was simply to illustrate that there is another method of doing things, and what the original problems were. (A good solution to the Animals 'problem' would be simple, it just wouldn't demonstrate any of the things you want to show.) > > We also need to make sure we include *all* children of Reptile in the > new numReptiles function. > > class Reptile(Animal): > -numReptiles = 0 > def numReptiles(): > return ( Reptile._numReptiles + > Snake.numSnakes() + Lizard.numLizards() ) > > Oops. We forgot Geckos !! > > To avoid these errors in programming, we may need a function that > automatically searches for subclasses, and calls their num functions. > I'm not sure how to do this without making it excessively complex. > Suggestions will be appreciated. > > -- Dave Hmm, I think perhaps I like your original example better than this. :-\ It's a bit like treating a cut throat with a tourniquet. Searching the subclasses will AFAIK still require some kind of metaprogramming, which is not too suitable for a 4-hour beginner course on OO. From greg at cosc.canterbury.ac.nz Tue May 25 00:24:27 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 May 2004 16:24:27 +1200 Subject: Monty Python reference spotted in Triangle and Robert Message-ID: <2hg03tFcd0kvU1@uni-berlin.de> http://home.comcast.net/~pshaughn/tr1666.gif From apardon at forel.vub.ac.be Thu May 13 04:41:10 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 08:41:10 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> Message-ID: Op 2004-05-12, David MacQuigg schreef : > On 11 May 2004 18:54:56 -0700, moughanj at tcd.ie (James Moughan) wrote: > >>Sure; you have to have some understood conventions. In effect that's >>all any higher-level programming language than assembler is. IMO, in >>the case in point, the explicit self makes OO easier to undersstand; >>YMMV, of course, as it does with Dave. :) > > I really hate to get involved in this "explicit self" debate, as I > know it has been debated ad-nauseum for many years, but I wish people > would not attribute to me a point-of-view that I do not have. For me > the "explicit self" is *not* the issue. I have a slight preference > for .var over self.var or $var, but this is a matter of personal > preference, not an implicit vs explicit question. > > My definition of explicit is that you can tell the meaning of a > statement without reference to the surrounding code. By that > definition all of the above forms are explicit. They are all instance > variables, and there is no other interpretation. The choice between > them is a *minor issue*, and I trust GvR to make these choices. > > The real issue is whether we can unify all forms of functions and > methods. This requires we do something different with 'self'. From a > unification standpoint, an equally acceptable solution is that we add > 'self' to *all* functions and methods, whether they need it or not. One could argue that all forms of methods and functions are unified. It is just that python does some magic so that the method you access from an object is not the actual function but the curried function with the object. If we have the following class: class Incrementor: def __init__(self, first_value): self.value = first_value def next(self): result = self.value self.value += 1 return result We could rewrite it as follows without methods -- except for __init__ -- and get the same object functionality : class Incrementor: def __init__(self, first_value): def next(self): result = self.value self.value += 1 return result self.value = first_value self.next = curry(next)(self) # or self.next = curry(next,self) # depending on the curry version Now if explaining currying functions to your students will help them understand, I don't know, although I don't find it that complicated. -- Antoon Pardon From j.dot.willeke at verizon.dot.net Sat May 1 21:58:12 2004 From: j.dot.willeke at verizon.dot.net (Jon Willeke) Date: Sun, 02 May 2004 01:58:12 GMT Subject: Cross-Language Encryption: Python/Java In-Reply-To: References: Message-ID: Daniel Orner wrote: > I've found implementations of Rijndael/AES for both Java and Python, > but the behavior is not identical (the strings that are produced are > different). I tried porting the Python rotormodule.c to Java, but my C > skills are not quite on the expert level, and I got bogged down trying > to figure out which C types corresponded to Java types (and its behavior > when casting and not casting, etc.). If you're willing to spend the effort to port rotor, it's probably worth the time to understand why the AES implementations don't agree. It's most likely a mismatch in the padding scheme or the interpretation of the key. From theller at python.net Wed May 26 15:41:09 2004 From: theller at python.net (Thomas Heller) Date: Wed, 26 May 2004 21:41:09 +0200 Subject: py2exe mailing list Message-ID: I have created a py2exe mailing list. This list should be used to ask for help using py2exe, and to suggest and discuss new features or other changes to py2exe. The list is public, posting is allowed even for non-members. The web page of the mailing list is: https://lists.sourceforge.net/lists/listinfo/py2exe-users To post a message to this list, send your email to: py2exe-users at lists.sourceforge.net There is also an email-based interface for users of the list; you can get info about using it by sending a message with just the word `help' as subject or in the body, to: py2exe-users-request at lists.sourceforge.net The list is also available with nntp and http at news.gmane.org: * News URL: news://news.gmane.org/gmane.comp.python.py2exe * Web URL: http://news.gmane.org/gmane.comp.python.py2exe I've also sent a request to the friendly ActiveState people to add this list to their ASPN archive, according to them this will take some days. Enjoy, Thomas From steve at ferg.org Tue May 4 19:54:30 2004 From: steve at ferg.org (Stephen Ferg) Date: 4 May 2004 16:54:30 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? Message-ID: I've been wondering how we can improve the quality of the Python documentation. The problem with the Python documentation is that it is not being handled like an open source product. The hallmark of open-source development is that many people contribute. The Python docs in contrast are being maintained by a very small group. I'm sure that many people would like to contribute to the improvment of the documentation... the problem is that there is no way that they can do so easily. The solution is to move to a different model of the documentation process, by developing a way to make it easy for everyone in the Python community to contribute to the documentation. One solution is a documentation wiki: see the request (below) for a "corresponding wikiable page for every page here in the pydocs." A similar but better solution is to follow the model created by the PHP community. If you follow the link to http://us2.php.net/manual/en/function.sort.php you'll see how impressive the results can be. Something like this is clearly what we need. So I put this question to the entire Python community. Can we create an interactive site, and the supporting organizational infrastructure, that will enable everyone in the Python community easily to contribute to the Python documentation? -- Steve (Stephen Ferg ... Steve at Ferg.org) --------------------------------------------------------------- Here are some recent posts on this subject. --------------------------------------------------------------- from: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=6afpj1-qbb.ln1%40home.rogerbinns.com I have found *by far* that the best docs are for PHP. It has little to do with the actual official content (which is fairly complete and well written and almost always includes an example), but a lot to do with how anybody can nnotate the pages, wiki style. Here is an example for the sort function: http://us2.php.net/manual/en/function.sort.php Having all those comments is really helpful, and they also help for updating the documentation. If there are a lot of comments against a page then the main body really needs some more work! ------------------------------------------------------------- from: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=mailman.150.1080693147.20120.python-list%40python.org One thing I like about PHP's docs is that it allows users to post comments, sugestions, extra information, etc to the docs online. Now and then someone goes through and edits the useful bits into the official documentation and flushes the comments all back out leaving them clear for new people to post their own. Several times I've attached comments as to how to compile a module or use some poorly documented feature and have had lots of people write to thank me for how helpful those comments were. I'd imagine the same process could be useful in Python. ----------------------------------------------------------- from: http://www.python.org/cgi-bin/moinmoin/PythonDocumentation Discussion Please!! get a wiki running side-by-side with the docs: e.g. one corresponding wikiable page for every page here in the pydocs. The startup data is simply that of the docs, so just mirror their structure. Then after the wiki docs start offering lots of useful information, the actual doc writers can incorporate this. To summarize, I think Python's documentation (like the library reference) is basically a big melange of api data and some snippets of useful info. This wiki will help replace those places that just use API data to fill up space, and turn it into something better. Like the PHP Manual at http://www.php.net/. I think that's a great idea. But I think it should appear on a separate wiki. We're going to need to do some steering for this wiki: If every python-related project in the world tries to make their wiki a walled garden within this wiki, we're going to run into problems. RecentChanges will be a total mess of a zillion projects. Let's talk. -- LionKimbro 2003-10-02 03:15:01 From grante at visi.com Tue May 25 10:55:00 2004 From: grante at visi.com (Grant Edwards) Date: 25 May 2004 14:55:00 GMT Subject: lists or tuples References: <40b2e203$1_1@news.iprimus.com.au> Message-ID: On 2004-05-24, mr_vocab wrote: > hey what is the many dif with them why bothere using tuples and how do you > edit a list??? See the recent thread on "terminology obscurity" or somesuch. -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com From jepler at unpythonic.net Tue May 25 22:48:06 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 25 May 2004 21:48:06 -0500 Subject: Passing parameters to functions In-Reply-To: References: Message-ID: <20040526024806.GA32066@unpythonic.net> If you want to have a varying number of positional arguments, and require certain keyword arguments, I think you'll be forced to write it in a clumsy way, similar to (untested): def extract_args(funcname, mapping, *names): for i in names: try: yield mapping[i] del mapping[i] except KeyError: raise TypeError, ( "%s requires a keyword argument %s" % (funcname, repr(i)))) def f(parg1, parg2, *pargs, **kargs): karg1, karg2 = extract_args("f()", kargs, "karg1", "karg2") print parg1, parg2, pargs, karg1, karg2, kargs When you write code like def f(a, b=1) Python will accept any of these calls to f: f(0) f(1, 2) f(3, b=4) f(a=5, b=6) and even f(b=7, a=8) .. the call that is relevant to your case is the second one. The value in b can come from a positional argument or a keyword argument. In your case, when you cakk 'f(1, 2, 3, karg=3)' karg gets two values---one from the third positional argument, and one from the keyword argument. Jeff From dmq at gain.com Wed May 5 07:00:29 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 05 May 2004 04:00:29 -0700 Subject: Unification of Methods and Functions References: <4n4d905eflq6ekrutjmrg3t6llk2b8lab7@4ax.com> <95aa1afa.0405042019.5a94e0ed@posting.google.com> Message-ID: On 4 May 2004 21:19:23 -0700, michele.simionato at poste.it (Michele Simionato) wrote: >Greg Chapman wrote in message news:... >> On Mon, 03 May 2004 11:44:06 -0700, David MacQuigg wrote: >> >> >It seems to work in Michele Simionato's 'prototype' module. >> >{ comp.lang.python, 4/28/04, "Prototypes in Python"} It is global >> >only to the called function, but the key requirement is met -- no >> >alteration of the standard function calling sequence. >> > >> >Why can't it be a true global? >> >> If I understand correctly, one drawback of his approach is that methods cannot >> rebind globals. A STORE_GLOBAL opcode will store its value into the globs >> dictionary created when the method was fetched; this dictionary is not the same >> as the module's dictionary, so the changed global will only be visible within >> that method (and within that method call: the next time the method is fetched, a >> new globs will be created). >> >> --- >> Greg Chapman > >I believe you are right (haven't checked yet) but I guess I can always >change the globals from inside the method with something like > >currentmodule=sys.modules["__name__"] >currentmodule.myglobal="something" > >Not that changing globals from a method is good style. The one limitation I see in the prototype module is that I can't save an unbound function and later call it with my choice of bind object. A global __self__ might help in this situation. e.g. ## This works: bf = cat2.talk # Save a bound function. def func(bf): # Pass it to another scope. bf() func(bf) # Call it. ## This does not: uf = Cat.talk # Save an unbound function. uf() #=> # AttributeError: type object 'Cat' has no attribute 'name' I would like to be able to do something like: __self__ = cat2 uf() Maybe there is some other trick to get this to work. It doesn't have to be pretty. This is a seldom-needed call, mostly for debugging. >BTW, I do agree that my hack is an evil hack, the interesting thing >about it (for me) was the fact that inside the method I could use >"super.method(*args)" instead of the ugly >"super(cls,self).method(*args)" syntax. I didn't think that was >possible at all. I don't care how evil the underlying machinery is. It works nicely at the user level. This is something the prototype advocates have missed. They see metaclasses or descriptors and they freak. If the module had been written in C, they would not be complaining. super.func() is cool. I would not bother my students with super(cls,self).func(), but the way super is used, it looks simple, and it is simple. I can have a hierarchy of classes, each one calling a function from its parent, and without modifying anything but the class headers, insert a new class in the middle of the hierarchy. ## New class: class Feline(Animal): ... def show(): super.show() print "Felines:", Feline.numFelines ... >>> cat2.show() Animals: 2 Felines: 2 <== Line added to previous output. Cats: 2 My interest in this "prototype" module is not the ability to clone prototypes, but the simplification and unification of all function and method calling styles. If we leave out the cloning stuff, does it make the implementation problems simpler? -- Dave From rzantow at ntelos.net Mon May 3 10:10:14 2004 From: rzantow at ntelos.net (rzed) Date: Mon, 03 May 2004 14:10:14 GMT Subject: PyOpenGL demo in wxPython demo crashes References: Message-ID: "F. GEIGER" wrote in news:c74oir$jkt$1 at newshispeed.ch: > Hi all, > > I wanted to look at the PyOpenGL demo in the wxPython demo, but > had no luck: > > "Runtime Error > Program: C:\...\pythonw.exe > abnormal program termination" > > Has anyone overcome this problem? > > Many thanks in advance and best regards > Franz GEIGER > > P.S.: Python 2.3.2 on Win2k, wxPython 2.4.2.4u, PyOpenGL (from > PyOpenGL-2.0.1.07.py2.3-numpy23.exe), glut.dll (from GLUT 3.7.6) > copied into \WINNT\System32. > > I have a similar configuration on my system, except that I have a glut32.dll, and I have no problems running the demo. There are evidently several glut32.dll versions around. -- rzed From h.b.furuseth at usit.uio.no Wed May 26 13:40:11 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 26 May 2004 19:40:11 +0200 Subject: Best way to enumerate something in python References: Message-ID: David Stockwell wrote: > I have a list of columnames for a db and I decided to put them in a giant > tuple list for two reasons: > 1) its unchangeable > 2) I was hoping that creating an enumeration of those names would be easy > > (...) > > I would like to create an enumeration with 'friendly names' that map to the > particular offset in my column name tuple. Like this? >>> class tuple_names(tuple): ... def __init__(self, dummy = None): ... self.__dict__ = dict(zip(self, range(0, len(self)))) ... >>> x = tuple_names(('a', 'b', 'c')) >>> x ('a', 'b', 'c') >>> x.c 2 Another approach to enumeration which I've just been playing with: import sys class Named_int(int): """Named_int('name', value) is an int with str() = repr() = 'name'.""" def __new__(cls, name, val): self = int.__new__(cls, val) self.name = name return self def __str__(self): return self.name __repr__ = __str__ __slots__ = 'name' def Enum_dict(_Enum_dest = None, **src): if _Enum_dest is None: _Enum_dest = {} for name, val in src.items(): _Enum_dest[name] = Named_int(name, val) return _Enum_dest def Enum(**mapping): """Enum(var = integer, ...) defines the specified named integer variables. Each variable is set to a Named_int with name 'var' and value 'integer'. Enum() only works in class bodies and at file level, not in functions.""" Enum_dict(sys._getframe(1).f_locals, **mapping) # Test if __name__ == '__main__': x = Named_int('y', 3) print x, str(x), int(x), "(%s = %d)" % (x, x) Enum( debug = 0, info = 1, warning = 2, error = 3, critical = 4 ) print"%s = %d" % (info, info) class foo: Enum (one = 1, two = 2) print foo.two print Enum_dict(three = 3, five = 5) print Enum_dict({None: ()}, seven = 7) -- Hallvard From nav+posts at bandersnatch.org Tue May 18 15:04:15 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 18 May 2004 15:04:15 -0400 Subject: proxy in urlopen() References: Message-ID: "Egor Bolonev" writes: > AssertionError: proxies must be a mapping This is telling you proxies must be a mapping type, in this case, a dictionary. So try replacing: > a=urlopen('url', proxies=('127.0.0.1:3128')) With this: a=urlopen('url', proxies={ 'http': '127.0.0.1:3128' }) HTH, 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 schull at digitalgoods.com Mon May 31 09:35:34 2004 From: schull at digitalgoods.com (Jon Schull) Date: 31 May 2004 06:35:34 -0700 Subject: how to bail if stdin is empty Message-ID: <2621b014.0405310535.38e176df@posting.google.com> I want to write a filter that will take input from files on the command line and/or from stdin. But if nothing has been piped to stdin, I don't want my program to hang--I want it to do something else. This is standard behavior for pipeable-programs I believe, but I can't figure out how to do it...neither by reading from stdin nor by using the fileinput module. Thanks in advance! From http Thu May 6 02:06:45 2004 From: http (Paul Rubin) Date: 05 May 2004 23:06:45 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: <7xbrl2m6mi.fsf@ruckus.brouhaha.com> Andrew Bennetts writes: > comp.lang.python is also a place where you can already most likely > find advice on pretty much any un- or under-documented standard > library module, if you check the archives. So even here we have > everything the PHP docs do. Is that a joke? Yes, you can sometimes find useful info on Python topics through Google searches of newsgroup archives, but to say that's equivalent to PHP's making all the relevant info visible right there on the doc page for the function you're interested in is ridiculous. Python users have many good reasons to like Python, but sometimes they seem to be in denial about areas that could use improvement. From eriksp at attbi.nospam.com Sat May 15 18:01:57 2004 From: eriksp at attbi.nospam.com (EAS) Date: Sat, 15 May 2004 22:01:57 GMT Subject: Good programming site Message-ID: http://www.coderforums.com Has forums for all the big languages, would be a lot better if there were more people. From cookedm+news at physics.mcmaster.ca Mon May 3 15:46:08 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 03 May 2004 15:46:08 -0400 Subject: Need Suggestions for Python/Tk/VTK References: Message-ID: At some point, Yang Wang wrote: > Dear All, > > I am totally new to Python, however had some experience with Tcl/Tk. > Currently I am doing a project that will need Python/Tk as well > as VTK(Visualization Toolkit) for image processing and visualization. > > Have anyone had any experience in this that can give me some suggestions > or references? And I also wonder how Tk is working with Python in > the process of constructing GUI, is it like the way that with Tcl? > > Any help will be greatly appreicated. Thanks. Have a look at the MayaVi project, which uses Tkinter and VTK for data visualization. You should be able to get some ideas from that. http://mayavi.sf.net/ -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From tismer at stackless.com Thu May 27 17:57:35 2004 From: tismer at stackless.com (Christian Tismer) Date: Thu, 27 May 2004 23:57:35 +0200 Subject: Saving recursive objects to disc. cPickle wan't work. In-Reply-To: <20040527204037.GB2175@matijek.plusseven.com> References: <20040526142220.GA2289@matijek.v10a.ath.cx> <20040527204037.GB2175@matijek.plusseven.com> Message-ID: <40B6644F.8060207@stackless.com> Alex Polite wrote: ... > If I up the recusionlimit the testsuit will segfault. Then you need a Python which does not have a stack problem. Use Stackless Python. Just don't care of what else it does, just use it, raise the recursionlimit to whatever, and both pickle and cPickle will run without any limit but main memory. Well, almost true. The current official version is unlimited on pickle.py, becuase the recursive calls in pickle don't involve recursive calls in the C interpreter. Stack protection for cPickle is in my new developer version, which is coming soon. It has Stack spilling for cPickle and the interpreter, so even in the rare cases where deep recursions cannot be avoided, the Stack is always saved and restored before overflow. And, well, I have full thread support since Monday :-)) ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From adalke at mindspring.com Sun May 16 18:37:44 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 16 May 2004 22:37:44 GMT Subject: Guess My Number Game References: <90aea0p1sn3ehbca0tds5uuhj5brrbbdj9@4ax.com> Message-ID: Andrea Griffini: > It also has the same problem about guessing too many times. Mmm, I see your point. When I've played the game the last one is supposed to be "then it must be 7". Here I finessed it by assuming the player was a wit and chose a non-integer value. With a bit more work I could make it test if numbers from either side have been tested and abort early. > It's also funny to see a bisection search called the "heavy > work": the convoluted (and IMO somewhat ugly) code used to > be able to call bisect is much more complex and less > intuitive than the bisection code itself. Yeah, I was smiling too when I wrote it. It was more of a "look at how leet my code is." :) Andrew dalke at dalkescientific.com From __peter__ at web.de Wed May 26 03:25:17 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 09:25:17 +0200 Subject: Cleaner idiom for text processing? References: Message-ID: Michael Ellis wrote: > I have some data files with lines in space-delimited > format. There are multiple name-value pairs per line. > > Is there a cleaner idiom than the following for reading each line into > an associative array for the purpose of accessing values by name? > > for line in infile: > tokens = line.split() > dict = {} > for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1] > do_something_with_values(dict['foo'],dict['bar']) Yet another way to create the dictionary: >>> import itertools >>> nv = iter("foo 1 bar 2 baz 3\n".split()) >>> dict(itertools.izip(nv, nv)) {'baz': '3', 'foo': '1', 'bar': '2'} >>> Peter From peter at engcorp.com Mon May 17 16:54:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 May 2004 16:54:17 -0400 Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: <5Z6dnVdKxPXnuzTdRVn-sQ@powergate.ca> Leif K-Brooks wrote: > Daniel Klein wrote: > >> Is there a way to 'extract' a dictionary into the current namespace? >> That is, if you have >> {'foo' : 23, 'bar' : 42} >> you would get a variable foo with value 23 and a variable bar with >> value 42? Such a function would of course only work on string keys and >> would probably have to check that, but still, it sounds practical >> enough that surely someone else thought of it before. > > > >>> vars = {'foo': 23, 'bar': 42} > >>> locals().update(vars) > >>> foo > 23 > >>> bar > 42 Except note from this page http://docs.python.org/lib/built-in-funcs.html#built-in-funcs that """ locals() Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ So Don't Do That. -Peter From ivan at ivan-herman.net Fri May 28 02:44:27 2004 From: ivan at ivan-herman.net (Ivan Herman) Date: Fri, 28 May 2004 08:44:27 +0200 Subject: XMP in Python Message-ID: <40b6dfa2$0$170$ee9da40f@news.wanadoo.nl> I am looking for an XMP interface to Python, whether it is part/extension of PIL or not. Is there any out there? (XMP is Adobe's metadata format that they use to add metadata to, eg, images in the latest releases of Photoshop. The C (or C++?) modules to extract or to add this metadata to an image has been released publicly by Adobe, so it should be possible to make an interface to Python easily. I just want to avoid reinventing the wheel...) Thanks Ivan From max at alcyone.com Mon May 17 15:48:51 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 17 May 2004 12:48:51 -0700 Subject: bit shifting question References: Message-ID: <40A91723.317BAA0D@alcyone.com> Michael Hudson wrote: > Have you tried this recently? I believe that whether >> sign fills is > undefined by the C standard but most of the time it dos. It's implementation defined, to be more exact. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ But you're not going to be there tomorrow. And it's all about tomorrow. -- Montgomery Brogan From calfdog at yahoo.com Tue May 25 08:50:25 2004 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 25 May 2004 05:50:25 -0700 Subject: Help me. How to open a new IE window? References: Message-ID: "Dave Brueck" wrote in message news:... > Vladimir wrote: > > angel wrote: > > > I want python(win32com) to open a new IE window. > > > Source is: > > > /******/ > > > import win32com.client > > > msie = win32com.client.Dispatch("InternetExplorer.Application") > > > msie.Visible = 1 > > > msie.Naviagte(http://www.python.org) > > > /******/ > > > The problem is the program always grabs a existed IExplorer window or > > > Explorer window. It never opens a new window. > > > > import webbrowser > > webbrowser.open_new("www.python.org") > > > > it will work fine with IE (if IE is the default browser) > > I guess the OP didn't specify, but the above won't work if you need to control > the browser from then on (which is what I assume he was trying to do by > obtaining an IDispatch pointer to it). > > -Dave Here is how you do it: Here is a quick way to do it but it works! If you want to learn more go to pamie.sourceforge.net This has a class file that helps you automate I.E. # DispatchEX allows you to open a new window from win32com.client import DispatchEx import time def wait(ie): # very important!!! you have to wait for each page to load "Given an IE object, wait until the object is ready for input." while ie.Busy: time.sleep(0.1) doc = ie.Document while doc.ReadyState != 'complete': time.sleep(0.1) return doc def ClickLink(ie, mylink): #hrefs = [] for link in ie.Document.links: if link is None: break # needed for browser bug if link.innerText == mylink: link.Click() # Here is what you need ie = DispatchEx('InternetExplorer.Application') ie.Visible = 1 ie.Navigate ('www.python.org') # Some extra wait(ie)# Very Important! ClickLink(ie,'Search') #later #RLM From peter at semantico.com Wed May 26 11:42:47 2004 From: peter at semantico.com (Peter Hickman) Date: Wed, 26 May 2004 16:42:47 +0100 Subject: Why a class when there will only be one instance? In-Reply-To: <40B3E861.29B033D5@shaw.ca> References: <40B3E861.29B033D5@shaw.ca> Message-ID: <40b4baf9$0$2104$afc38c87@news.easynet.co.uk> SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. This is a lot like putting code in functions. "Its only called in one place, why put it in a function, why not just leave it where it is?" I had a conversation with a dBase programmer many years ago on just these lines and what it came down to was this. for x = 1 to length(orderitems) calculate_tax(orderitems[x], .175) next (forgive the pseudo code) is easier to read and the intent of the code is much clearer, and also we had 24 * 80 screens and so you could see much more of the 'flow' of the program than if the code was in lined. Objects just take all that one step further. order.calculate_tax( .175 ) Why read fifty lines of code to work out that tax is being calculated for each item in the order when you can read one line? How you achieve this is not all that important, functions or classes only that the flow of the program can be comprehended quickly. Objects don't just make writing code easier but it makes *READING* code easier too, a very important plus (ever had to maintain APL?) Almost everything that I write becomes an object even the programs themselves. From __peter__ at web.de Wed May 12 16:39:09 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 May 2004 22:39:09 +0200 Subject: max value in list References: Message-ID: C GIllespie wrote: > I have a few lists. What's the best way of finding the maximum number of > all the lists. > > For example, > > [2,3,4],[1,2,3],[4,7] > > The max is 7. For arbitrarily nested sequences: >>> def rmax(seq): ... try: ... return max(map(rmax, seq)) ... except TypeError: ... return seq ... >>> rmax(1) 1 >>> rmax([1,2]) 2 >>> rmax([[1,2], [3,4]]) 4 >>> rmax([[1,2], [3,44], 5, [6]]) 44 >>> rmax([[1,2], [[3,44], 5, [6]]]) 44 >>> Peter From lho at gmx.de Fri May 14 02:28:24 2004 From: lho at gmx.de (Lutz Horn) Date: Fri, 14 May 2004 08:28:24 +0200 Subject: Retrieve Email Attachments In-Reply-To: <7b454334.0405131902.60550e4c@posting.google.com> References: <7b454334.0405131902.60550e4c@posting.google.com> Message-ID: <2gj794F3fd4cU1@uni-berlin.de> > I need to access a POP or mayb IMAP based email account and extract > attachments (probably images) from the email messages. How can this > be done with the current two module libraries? Use poplib or imaplib to get a message as a string. >>> import poplib >>> connection = poplib.POP3("servername") >>> connection.user("username") >>> connection.pass_("password") Then use the email module (new in 2.2) to parse this string into an instance of email.Messsage using >>> import email >>> msg = email.message_from_string(msg_as_string) Use the methods of the resulting email.Message instance to get the contents of the email. Lutz From Chris.Hornberger at blackrock.com Fri May 14 14:53:21 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Fri, 14 May 2004 14:53:21 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 Message-ID: > >I wonder why the Linux installation needs to be more tedious than the >Windows counterpart. The problem is of course not specific to Python. >There are many Linux distributions, running on different kernels, but >maybe binaries that have been tested on the "major" distributions like >Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. Compare >the instructions: > Welcome to an open platform. It all boils down to money and what the "open source movement" is really about. On the money front, no organization is going to step up and try to implement standards if there's no revenue in it. Period. And rightly so. Take RedHat for instance. You can download their distribution for free. But they charge for burned media, distribution of said media and for support. All rightly so. Now, imagine the headaches and woe if, say, RedHat were to step up and introduce a Linux Standardized Platform Specification, granting "Designed for RedHat" certifications to vendors, issuing mandates on standardized directory trees, version coupling, dependency mandates, and all the other fun stuff we all deal with running our linux systems. It'd last all of about 3 days. Personally, I'd love it. As an APPLICATION developer, and not a SYSTEMS developer, the last thing I want to worry about when writing business software or even tinkering around with my own stuff, is which dotted version of some GLIBC file I have. Oh, I have .4, I need .6 pffffffffffft. There are those among us who thrive on that. Me? I just wanna use my computer and write my software. Period. Not to mention, the minute ANY "standards body" starts using words like "mandate" and "control", the Open Source movement will erupt into (more) religious wars and the whole "bill gates, the antichrist" crap will rise (again). *rolls eyes* I just wanna write software. Really. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. From jlearman at cisco.com Thu May 20 14:46:12 2004 From: jlearman at cisco.com (Jeff Learman) Date: Thu, 20 May 2004 14:46:12 -0400 Subject: shell script stdout to python string? Message-ID: <1085078933.436553@sj-nntpcache-3> Hi -- sorry for not searching first, but I get an NNTP error from netscape (a known bug, still looking for workaround). Inside a python script, I want to execute a UNIX command and send the output to a Python string, returning the shell return code value as an integer or exception. I'm sure I could write a function using pipes and whatnot, but I'm hoping this is a solved problem by now, more elegantly and correctly coded than my hack job would be. Thanks, Jeff Python rocks, btw. I've almost broken the #!/bin/ksh habit ;) From asmirnov1234567890 at yahoo.com Thu May 20 10:16:01 2004 From: asmirnov1234567890 at yahoo.com (Andrei Smirnov) Date: 20 May 2004 07:16:01 -0700 Subject: alternatives to making blocks like { } or other ?? References: Message-ID: <9ace45f.0405200616.7e5110ba@posting.google.com> "Paul McGuire" wrote in message news:... > "Grant Edwards" wrote in message > news:slrncalqqf.8f2.grante at grante.rivatek.com... > > On 2004-05-18, CYBER wrote: > > >> Of course there is another way! > > >> > > >> Just use # in front of your favourite block separator. > > >> > > >> I'm too lazy now to search the archives on who first suggested this, > > >> but it works: > > >> > > >> def something(x): > > >> #{ > > >> return x > > >> #} > > > > > > Thank you. > > > > You realize that was a joke, right? > > Joke? On my previous job my boss included smthng like that to local code standard. everybody were supposed to do that. if python would have compatibility mode for braces, please... otherwise perl is everywhere because of braces and most people were taking classes in C or Java or C++. that the only reason besides people like dollar signs :) i do really suffer. i have to use Perl and i know that i have no chance to convince my new boss (very smart guy) to switch to Python because of braces. that means wasted time on debugging perl crap code and listening about Perl 6 future might. Please, Python writers, do provide braces as compatibility mode. Give the chance to the world! Andrei From phleum_nospam at chello.se Thu May 20 12:04:39 2004 From: phleum_nospam at chello.se (Carl) Date: Thu, 20 May 2004 18:04:39 +0200 Subject: python hello.py hello_msg("Hello no", 3)??? Help, please! References: <1O-dnXbH1_NxTzHd4p2dnA@powergate.ca> Message-ID: Peter Hansen wrote: > Carl wrote: > >> This is perhaps a very simple and stupid question! >> >> How do you run a specific function (with actual values for the >> parameters) within a module from the command prompt? That is, with >> "python ..." >> >> For instance, how do I run hello_msg("Hello no ", 3), which is a function >> within the module hello.py, from the console? >> >> def hello_msg(msg, num): >> print msg + str(num ** 3) +'!' >> #hello_msg("Hello no ", 3) > > Use the -c option. > > python -c "import modulename; modulename.hello_msg('test', 5)" Thanks, that was incredibly simple! Carl From bart59 at free.fr Tue May 11 04:01:13 2004 From: bart59 at free.fr (bart59) Date: 11 May 2004 01:01:13 -0700 Subject: Make one GUI containing java and C++ componants ? Message-ID: <26079f73.0405102305.687f19e4@posting.google.com> Hello, I have two application: one in java, which use awt and wing componants as a GUI. one in C++, which is a 3d engine, then it display in a window a 3D modele. I'm looking for a solution to combine these two interfaces in one containing the Java componant + the C++ window . Is there a way to manage with that? JNI doens t seem to be the good approach, it should be difficult to render the c++ output in a java component: moreover, interactions with the mouse are required in the ed engine... I heard about python, but I can t see the real advantage that can give me python. Any solution? thank you very much for your help. Bart From winexpert at hotmail.com Thu May 27 09:50:05 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 13:50:05 +0000 Subject: Best way to enumerate something in python Message-ID: FWIW this is what I'm going to do for enumerated types in python. Its not perfect but it will make it fairly easy to get at column names so I can build SQL statements on the fly and still have fairly easy to maintain code #setup stuff NAME_COL, ADDRESS_COL, CITY_COL, ZIPCODE_COL, \ STATE_COL, COUNTRY_COL, SS_COL, CAT_COL, \ DATE_COL, SALARY_COL = range(10) mycol = { NAME_COL: " NAME ", ADDRESS_COL: " ADDRESS ", CITY_COL: " CITY ", ZIPCODE_COL: " ZIPCODE ", STATE_COL:" STATE ", COUNTRY_COL: " COUNTRY ", SS_COL: " SS ", CAT_COL: " CAT ", DATE_COL: " DATE ", SALARY_COL: " SALARY " } # Use these for indexing by column name # demonstration on how to 'get' print mycol[CITY_COL] David ------- cell phone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From tjreedy at udel.edu Sat May 22 00:39:14 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2004 00:39:14 -0400 Subject: Pyrex - The speed of Python with the clarity of C? References: <40AE2C4E.CE1CE6C0@shaw.ca> <40AE9A5E.8F514E3B@shaw.ca> Message-ID: wrote in message news:40AE9A5E.8F514E3B at shaw.ca... > Terry Reedy wrote: > > > > "Peter Hansen" wrote in message > > news:juidnTjQubr1szPd4p2dnA at powergate.ca... > > > SeeBelow at SeeBelow.Nut wrote: > > > > Am I wrong about this? Perhaps I don't understand how Pyrex works. > > > > > > Look at the primes.pyx example. There's a link just below it > > > (above the Language Details section) showing the C code it is > > > compiled to (and which is in turn compiled to machine code). To repeat: 'and which is in turn compiled to machine code'. > > In particular, lines 5-15 of the Python code, the 'guts' of the algorithm, > > are compiled to pure C with no interface calls. > > But does this C code get compiled into machine code? I don't understand why you are asking this again when Peter answered so clearly. As you said in your first post, there would otherwise be no point to the translation to C. > If so, What compiler does that, and when? Better question. I do not have PyRex, so I do not know the details. Either PyRex call a C compiler itself, automatically, or it leave the C file for you to invoke the compiler. Or perhaps it gives you a choice. *nix systems come with a C compiler. The location should be part of the system data somewhere. On other systems, you might have to buy one and give PyRex the name and location. PyRex is an alternative to writing C code yourself, but not, I believe, an alternative to having a C compiler. Terry J. Reedy From Scott.Daniels at Acm.Org Sun May 2 16:04:03 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 May 2004 13:04:03 -0700 Subject: newbie question on Python tutorial example in section 4.7.1(default arg values) In-Reply-To: References: <56cfb0e3.0405011337.2a8710bc@posting.google.com> Message-ID: <409559a9$1@nntp0.pdx.net> Rich Krauter wrote: > On Sat, 2004-05-01 at 17:37, Porky Pig Jr wrote: >>Anyway, the example is >>def f(a, L=[]): >> L.append(a) >> return L >> >>I still don't understand how the following workaround works: >> >>def f(a, L=None): >> if L is None: >> L = [] >> L.append(a) >> return L >> >>well, it does work, but why? Seems like we initialize L to None Here is the conceptual flaw: We initialize f's default to None. When we call f (with only a value for a), on entry to the function we associate the name L with the default (None). When the L = [] line is executed, we re-associate L with a new empty list. In the original definition, we set the default to a particular new empty list. The default will remain that particular list. L is a name that is associated with objects, not a place a value is stored. Mr. Pig, hopefully either my explanation or Mr. Krauter's (which is also correct) will help you figure this out. The difference between the two is our guess at what you don't understand. If it still does not make sense, ask again. An interesting exercise to show the bit about objects: a = [] b = [] print id(a), a, id(b), b a.append(1) print id(a), a, id(b), b a = b print id(a), a, id(b), b a.append(1) print id(a), a, id(b), b If you can explain the output of the four print statements and are still confused, my explanation is not on point. -Scott David Daniels Scott.Daniels at Acm.Org From junkmail at solumslekt.org Wed May 12 16:16:51 2004 From: junkmail at solumslekt.org (Leif B. Kristensen) Date: Wed, 12 May 2004 22:16:51 +0200 Subject: newbie question: should I learn TKinter or skip it and learnmoreadvanced toolkit? References: Message-ID: Andy Baker rose and spake: > I started with Tk and dropped it on horror when I realised it had no > muti-column list box. Shame coz it is better documented than anything > else. A Tkinter multi-column list box is quite easily implemented by ganging up a collection of single-column listboxes. It's unfortunately not included among the standard widgets. However it's covered by the Python Cookbook, and you'll find Brent Burley's excellent example online here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 If you google for "tkinter multi-column listbox" it will pop up right on top of the list. The ActiveState server seems to be down right now. An alternate source for basically the same code is found at Bob Hauck's home page: http://www.haucks.org/ regards, -- Leif Biberg Kristensen http://solumslekt.org/ Validare necesse est From slawek at cs.lth.se Sun May 23 08:47:00 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Sun, 23 May 2004 14:47:00 +0200 Subject: Freeze and Resume execution In-Reply-To: <20040523131353.GS1916@zoran.com> References: <20040523115548.DF2E.SLAWEK@cs.lth.se> <20040523131353.GS1916@zoran.com> Message-ID: <20040523141548.DF35.SLAWEK@cs.lth.se> On Sun, 23 May 2004 15:13:53 +0200 "Miki Tebeka" wrote: #> Hello Slawomir, #> My problem is that the one raising the error is the generator. Why? Cannot you rewrite your code in such a way that something else is raising an exception? Looks like a simple wrapping function to me... #> Something in the lines of: #> class BufferFull(Exception): #> pass #> #> def send_one_bit(bit): #> pass #> #> OUT_BUFFER_SIZE = 10 #> def output(bits): #> size = 0 #> for bit in bits: #> send_one_bit(bit) # HW call #> size += 1 #> if size == OUT_BUFFER_SIZE: #> raise BufferFull # I'd like to resume just after this point #> size = 0 OK, I think I understand better now. So how about that: ********************************************************************** def output_gen(bits): size = 0 for bit in bits: send_one_bit(bit) # HW call size += 1 if size == OUT_BUFFER_SIZE: yield "BufferFull" # use yield instead of raise here size = 0 generator = None def output(): res = generator.next() if res == "BufferFull": raise BufferFull def sendall(bits): global generator generator = output_gen(bits) while True: try: output() except BufferFull: print "Emptying buffer" except StopIteration: print "Done sending" break def test(): sendall("1234567890123456789012") ********************************************************************** Catching BufferFull and calling output() doesn't need to be in sendall() function, it can basically be anywhere you want it to be. Does this do what you want it to do? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) There are 3 kinds of people: those who can count & those who can't. From N/A Thu May 13 21:22:45 2004 From: N/A (Oten) Date: Thu, 13 May 2004 18:22:45 -0700 Subject: Python Correspondance Message-ID: <10a87s73km2ou0e@corp.supernews.com> Hi I have a question has anyone in the Python Community thought of creating a home study course where people like myself who, want to, can focus entirely on learning Python. Books can only go so far for me. I personally would like to be trained in Python but sense I live out in the boonies there are no schools near me who teach python And also I am not really into going to a college to learn a bunch of languages like Java and C++ although good languages I am not really interested in learning these Does anyone else feel the same way Heres a suggestion I could start an online learning community who's goal is to teach Python. Online lectures every week donations to keep it alive reading material video training. Anybody think this is a good idea From SzeplakiJ at spbinvest.hu Fri May 7 02:51:05 2004 From: SzeplakiJ at spbinvest.hu (Szeplaki Julianna) Date: Fri, 7 May 2004 08:51:05 +0200 Subject: Virus Found in message "Word file" Message-ID: Norton AntiVirus found a virus in an attachment you (python-list at python.org) sent to szeplakij at spbinvest.hu. To ensure the recipient(s) are able to use the files you sent, perform a virus scan on your computer, clean any infected files, then resend this attachment. Attachment: document_word.pif Virus name: W32.Netsky.D at mm Action taken: Clean failed : Quarantine succeeded : File status: Infected -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1643 bytes Desc: not available URL: From shekmalhen at NO.SPAMfastmail.fm Sat May 8 15:57:33 2004 From: shekmalhen at NO.SPAMfastmail.fm (Karl Casavant) Date: Sat, 08 May 2004 15:57:33 -0400 Subject: CGI Proplem displaying image In-Reply-To: References: Message-ID: Hello, The HTTP header needs two newlines: one is provided by the "print" statement but the other one shall be given by the string. Without the second newline, the server returns an error 500 "Internal Error". Karl matthiasjanes wrote: > Hi, > Maybe someone of you can help me. > > I'm trying to display an image in memory(open file) with an cgi script > - but it want work proberly: > > I'm running an Cgi webserver (CgiServerGui.py). > > both files are in the /cgi/ folder > > ################# > #my CGISRIPT: test.py > > #! /usr/bin/env python > > print ("Content-type: image/jpeg"); > print # End of headers! > > filename="cgi-bin//dog.jpg" > infile = open(filename, 'rb') > doginmemory=infile.read() > print doginmemory > > ################## > > ################# > #my html page with the image tag > > > > > > > > > > ################ > > > I can't figure out whats the problem. > > funny: if I use a form with an method='post' I can get the picture > show up in a whole webpage ( method='get' will not work) > > ########### > > > > >
> > > > ############ > > > Any suggestion: (by the way: in the end the whole pictures should be > stored in an sqlite database and also retrieved from it to be > displayed within an html page. > > > Thanks Matthias From __peter__ at web.de Fri May 21 14:29:28 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2004 20:29:28 +0200 Subject: Documentation/Info on this sign References: <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> <40ACED36.5030706@hotmail.com> Message-ID: Bart Nessux wrote: > Both functions produce the same results (33,000 files)... the problem: > the filesystem has twice as many files (66,000) than the actual sums of > these two counts when doing a virus scan or an adaware scan. To make > matters more confusing... the IBM Tivoli backup software that I use > confirms the Python counts when it does a backup. I don't know of a way > to see what the OS has to say what it thinks is correct. Any ideas on > how to do this? Maybe you have a symlink (how are they called in windows?) in the root folder. The number of files would vary depending on whether the software follows symlinks or not. That could explain the factor 2. Peter From piddle at guzzleguts.com Fri May 7 10:21:53 2004 From: piddle at guzzleguts.com (Lisa D. Toshiba) Date: Fri, 07 May 2004 07:21:53 -0700 Subject: Dont spend more on software, Python. Message-ID: <010101c4343e$fd9dc4d9$f220b2e5@guzzleguts.com> Wakey wakey! A good heart is better than all the heads in the world. Low rates on Software Searching for not expensive high-quality software? Our site might be just what you need. http://enthrone.fosraw.biz/OE017/?affiliate_id=233712&campaign_id=601 And more! We can ship worldwide. Good timber does not grow with ease. The stronger the wind the stronger the trees. If you improve or tinker with something long enough, eventually it will break or malfunction. -------------- next part -------------- An HTML attachment was scrubbed... URL: From 2002 at weholt.org Wed May 19 14:23:50 2004 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 19 May 2004 20:23:50 +0200 Subject: n-tier application in Python References: <2h1hljF7u74vU1@uni-berlin.de> Message-ID: <40aba70d$1@news.broadpark.no> I'm currently developing a Web-application server using a 2-tier design; an application layer and a data-layer. I've also seperated design and logic using simpleTal for html templates. It's still pre-alpha so I haven't stress-tested it properly yet and can't say anything about performance. It's built upon Twisted and use MySQL or SQLite for storage. I'm also interested in other n-tier applications so any information somebody might have would be of interest. In general, python has *very* good XML-support and in my experience very good database access support as well. Regards, Thomas "Kornl" wrote in message news:2h1hljF7u74vU1 at uni-berlin.de... > Hello, does anyone has any experience in developing n-tier applications in > python? If yes would you like to share your experience? What turn out good > and bad?? > In your experience, how is a python server capable of handling various > simultaneous connections in the context of a n-tier application? > I'd also like to ask how is the state of database access and XML libraries > on python? > > From Mike at DeleteThis.Geary.com Mon May 24 20:26:29 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 24 May 2004 17:26:29 -0700 Subject: Prothon should not borrow Python strings! References: Message-ID: <10b54lm45adrpab@corp.supernews.com> Mark Hahn wrote: > Wow, thanks, this is some really great stuff. I'm going to have > to go off and study up on it. > > This may be a stupid question, but couldn't I have many "types" > of strings and some be 8-bits, some 16-bits, and some 32-bits? > Couldn't normal method overloading handle the type conversion? > Why is there all this confusion? Isn't this what object-centric > computing is designed for? In fact, there are several different encodings for Unicode strings: UTF-8, UTF-16, and UTF-32. UTF-16 and UTF-32 each come in big-endian and little-endian variations, or a Byte Order Mark (BOM) at the beginning of the string can be used to tell you which it is. UTF-8 is pretty nice for a lot of purposes. It includes the 7-bit ASCII character set unchanged and avoids the endian problems. You could specify that Prothon source code uses UTF-8, although you'd still want to support the other UTFs for data. There's a good FAQ on the UTFs here: http://www.unicode.org/unicode/faq/utf_bom.html -Mike From cookedm+news at physics.mcmaster.ca Mon May 3 23:09:27 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 03 May 2004 23:09:27 -0400 Subject: Question about glob.glob <--newbie References: Message-ID: At some point, "Sean Berry" wrote: >>>> r = glob.glob('/*') >>>> r > ['/dev', '/usr', '/stand', '/etc', '/cdrom', '/proc', '/bin', '/boot', > '/mnt', '/modules', '/root', '/sbin', '/tmp', '/var', '/sys', '/COPYRIGHT', > '/kernel.GENERIC', '/kernel', '/compat', '/home', '/kernel.old', > '/modules.old'] >>>> >>>> r = glob.glob('/usr/websites/*') >>>> r > [] > > I can do a >>>> import os >>>> dirs = os.system('ls /usr/websites') > > and that works. Why doesn't glob.glob work on /usr/websites? Somehow, I doubt that actually works. I'll bet that dirs == 0 -- os.system returns the status code of the command, not the output. You'll want commands.getoutput. What are the permissions on /usr/websites? What does 'ls -l /usr/websites' and 'ls -ld /usr/websites' give? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From wilkSPAM at OUTflibuste.net Thu May 13 04:36:00 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 13 May 2004 10:36:00 +0200 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> Message-ID: <873c64zpu7.fsf@blakie.riol> dlissett0 at yahoo.com (Duncan Lissett) writes: > I'd appreciate any suggestions on how to make faster Python > implementations of Richards benchmark. Perhaps there are obvious > problems that can be corrected? > > http://www.lissett.com/ben/bench1.htm import psyco psyco.full() 2 times faster :-) -- Wilk - http://flibuste.net From burn_hall at yahoo.com Mon May 31 16:27:00 2004 From: burn_hall at yahoo.com (burn_hall) Date: Mon, 31 May 2004 20:27:00 -0000 Subject: XML Parsing problem using DOM Parser: HELP NEEDED Message-ID: Hi, I have a problem and can't figure it out and need your help, please look at the following code and the output also a xml file snippet is down there too. Looking at the output I don't know why it's not according to the code. Following code is pretty much clear: When method starts execution Node is passed it has childNodes Inside for-loop if x.localName == 'id': check for validTine and calls the same method again, now executes elif x.localName == 'validTime': check for the appropriate childNode and calls the method again, now inside if temp_node.localName == 'low': calls the method but instead of just executing elif x.localName == 'low' and x.parentNode.localName == 'validTime': and printing only print " In low" it prints all the rest too i.e. print "In high" print "In high1" print "In high2" print "In high3" print "In high4" print "In high5" then again in the for-loop of validTime this time executes elif temp_node.localName == 'high': but instead of just executing elif x.localName == 'high' and x.parentNode.localName == 'validTime': and printing only print "In high" it prints all the rest too i.e. print "In low" print "In high1" print "In high2" print "In high3" print "In high4" print "In high5" and it continues for the rest. Why it when executing if temp_node.localName == 'low': print " **** low" self.iterate(x) only executes elif x.localName == 'low' and x.parentNode.localName == 'validTime': print " In low" and so on. Why it iterates through all the rest elements too and when the condition for one is being checked. Is it the normal way that xml parsing is handled in python. If so what's the best way to handle this situation using DOM(Parser). As I need to parse the xml-file it's pretty big and each Node can have nested childNodes and so forth as the example shows. But anytime parsing the Node doesn't stops and jumps to the right condition as shown in the following sample: Any help is appreciated def iterate(self,node): print '0 === %s' % node.localName for x in node.childNodes: if x.nodeType == Node.TEXT_NODE: pass else: print "1 **** %s" % x.localName if x.localName == 'id': print " **** id" for temp_node in x.childNodes: if temp_node.localName == 'validTime': self.iterate(x) elif x.localName == 'validTime': for temp_node in x.childNodes: if temp_node.localName == 'low': print " **** low" self.iterate(x) elif temp_node.localName == 'high': print " **** low" self.iterate(x) elif temp_node.localName == 'high1': print " **** high1" self.iterate(x) elif temp_node.localName == 'high2': print " **** high2" self.iterate(x) elif temp_node.localName == 'high3': print " **** high3" self.iterate(x) elif temp_node.localName == 'high4': print " **** high4" self.iterate(x) elif temp_node.localName == 'high5': print " **** high5" self.iterate(x) else: pass elif x.localName == 'low' and x.parentNode.localName == 'validTime': print " In low" elif x.localName == 'high' and x.parentNode.localName == 'validTime': print "In high" elif x.localName == 'high1' and x.parentNode.localName == 'validTime': print "In high1" elif x.localName == 'high2' and x.parentNode.localName == 'validTime': print "In high2" elif x.localName == 'high3' and x.parentNode.localName == 'validTime': print "In high3" elif x.localName == 'high4' and x.parentNode.localName == 'validTime': print "In high4" elif x.localName == 'high5' and x.parentNode.localName == 'validTime': print "In high5" *********** Following is the snippet of the .xml file *************** ************* Following is the output from execution of the method ************ 0 === Pat 1 **** id 0 === id 1 **** validTime **** low 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high1 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high2 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high3 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high4 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 **** high5 0 === validTime 1 **** low In low 1 **** high In high 1 **** high1 In high1 1 **** high2 In high2 1 **** high3 In high3 1 **** high4 In high4 1 **** high5 In high5 1 **** Person 1 **** Organ From jepler at unpythonic.net Sat May 15 14:59:53 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 13:59:53 -0500 Subject: Input Types In-Reply-To: References: Message-ID: <20040515185953.GC2832@unpythonic.net> On Sat, May 15, 2004 at 08:23:51PM +0200, moma wrote: > You can send functions (int, float) and exceptions as parameters? > Amazing. You sure can. numbers, sequences, dicts, functions, exceptions, classes, modules: all these things are objects, and you can pass any object you like as a parameter. Of course, not all object types *make sense* everywhere! One "exception" to this rule is thinking that print is a function, and trying to write def send_to(value, action): return action(value) def f(x): return x*x >>> send_to(3, f) # square the argument: works 9 >>> send_to(3, print) # Print the argument: error File "", line 1 send_to(3, print) ^ SyntaxError: invalid syntax because print is a statement, not a function, this isn't really an exception to the rule at all. Jeff From ajsiegel at optonline.com Wed May 26 20:09:17 2004 From: ajsiegel at optonline.com (Arthur) Date: Thu, 27 May 2004 00:09:17 GMT Subject: modifying mutable list elements in a for loop References: <9d5509fa.0405260439.175797e@posting.google.com> Message-ID: <49cab0597e8horkvlhfihfho075uivgm3j@4ax.com> On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen wrote: >Peter Ballard wrote: > >> The python tutorial tells me "It is not safe to modify the sequence >> being iterated over in the loop". But what if my list elements are >> mutable, such as lists or objects, e.g. > >Treat that as "not safe if you don't know what you are doing". >David's answer is on the mark, but furthermore you *can* modify >the sequence being iterated over, if that's really what you >want to do. OTOH: d={"a":1,"b":2} for k in d: d.pop(k) results in: RuntimeError: dictionary changed size during iteration I don't recall why I ran into this. But was mildly surprised. Art From faizan at jaredweb.com Thu May 13 23:02:40 2004 From: faizan at jaredweb.com (Fazer) Date: 13 May 2004 20:02:40 -0700 Subject: Retrieve Email Attachments Message-ID: <7b454334.0405131902.60550e4c@posting.google.com> Hello, I need to access a POP or mayb IMAP based email account and extract attachments (probably images) from the email messages. How can this be done with the current two module libraries? Thanks for any insight. Faizan. From segphault at sbcglobal.net Wed May 26 11:00:38 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 26 May 2004 15:00:38 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: On Tue, 25 May 2004 21:20:02 -0400, Roy Smith wrote: > Ryan Paul wrote: >> defining a class may be useful if you plan on making more instances down >> the line. It's a good OO strategy. I do understand your dislike of 'self'. >> It does seem like clutter. In my code, I shorten it to 's'. > > Please don't do that. While it's true that the first parameter of a > class method can be named anything, the use of "self" is so > overwhelmingly ubiquitous it might as well be a standard. Using > anything else is just going to make your code more difficult for anybody > else to read and understand. > > Typing is cheap. Thinking is expensive. And, yes Aahz, you can quote > me on that :-) I dont conform to a bad standard just because it's a standard. If I did, I would be using java instead of a dynamic language like python. If other people dont like it, thats too bad- they dont have to use my code. From j_mckitrick at bigfoot.com Sun May 23 18:01:18 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 23 May 2004 15:01:18 -0700 Subject: Problem building pygtk-2.3.92 Message-ID: Hi, I'm trying to build the latest (beta) pygtk 2.3.92 on a FreeBSD system. First, I got these warnings. Are these a problem? Could not write method GtkAccelGroup.activate: No ArgType for 'GQuark' Could not write method GtkAccelGroup.find: No ArgType for 'GtkAccelKey*' Could not write method GtkAccelGroup.query: No ArgType for 'guint*' Could not write method GtkAccelLabel.set_accel_closure: No ArgType for 'GClosure*' Could not write method GtkActionGroup.set_translate_func: No ArgType for 'GtkTranslateFunc' Could not write method GtkIMContextSimple.add_table: No ArgType for 'guint16*' Could not write method GtkSettings.install_property: No ArgType for 'GParamSpec*' Could not write method GtkSettings.install_property_parser: No ArgType for 'GParamSpec*' Could not write method GtkSettings.set_property_value: No ArgType for 'const-GtkSettingsValue*' Could not write method GtkTreeSelection.get_user_data: No ArgType for 'gpointer' Could not write method GtkTreeStore.set_column_types: No ArgType for 'GType*' Could not write method GtkTreeView.set_column_drag_function: No ArgType for 'GtkTreeViewColumnDropFunc' Could not write method GtkTreeView.get_search_equal_func: No ArgType for 'GtkTreeViewSearchEqualFunc' Could not write method GtkTreeView.set_search_equal_func: No ArgType for 'GtkTreeViewSearchEqualFunc' Could not write method GtkTreeView.set_destroy_count_func: No ArgType for 'GtkTreeDestroyCountFunc' Could not write method GtkWidget.list_accel_closures: No ArgType for 'GList*' Could not write method GtkWidget.region_intersect: No ArgType for 'GdkRegion*' Could not write method GtkWidget.style_get: varargs functions not supported Could not write method GtkCellLayout.set_cell_data_func: No ArgType for 'GtkCellLayoutDataFunc' Could not write function accel_group_from_accel_closure: No ArgType for 'GClosure*' Could not write function accel_map_foreach: No ArgType for 'gpointer' Could not write function accel_map_load_scanner: No ArgType for 'GScanner*' Could not write function accel_map_foreach_unfiltered: No ArgType for 'gpointer' Could not write function accel_map_get: No ArgType for 'GtkAccelMap*' Could not write function binding_entry_clear: No ArgType for 'GtkBindingSet*' Could not write function gtk_binding_entry_add_signall: No ArgType for 'GtkBindingSet*' Could not write function binding_entry_add_signall: No ArgType for 'GtkBindingSet*' Could not write function binding_parse_binding: No ArgType for 'GScanner*' Could not write function color_selection_set_change_palette_hook: No ArgType for 'GtkColorSelectionChangePaletteFunc' Could not write function color_selection_set_change_palette_with_screen_hook: No ArgType for 'GtkColorSelectionChangePaletteWithScreenFunc' Could not write function file_paths_sort: No ArgType for 'GSList*' Could not write function item_factory_popup_data_from_widget: No ArgType for 'gpointer' Could not write function init_add: No ArgType for 'GtkFunction' Could not write function get_current_event_state: No ArgType for 'GdkModifierType*' Could not write function stock_add_static: No ArgType for 'const-GtkStockItem*' But here is the build error: source='gdk.c' object='_gtk_la-gdk.lo' libtool=yes depfile='.deps/_gtk_la-gdk.Plo' tmpdepfile='.deps/_gtk_la-gdk.TPlo' depmode=gcc /bin/sh ../depcomp /bin/sh ../libtool --mode=compile gcc -DHAVE_CONFIG_H -I. -I. -I.. -I.. -I/usr/local/include/python2.3 -D_THREAD_SAFE -I/usr/local/include/atk-1.0 -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/X11R6/include/gtk-2.0 -I/usr/X11R6/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/X11R6/include/pango-1.0 -I/usr/local/include/freetype2 -I/usr/local/include -g -O2 -Wall -std=c9x -fno-strict-aliasing -c -o _gtk_la-gdk.lo `test -f 'gdk.c' || echo './'`gdk.c gcc -DHAVE_CONFIG_H -I. -I. -I.. -I.. -I/usr/local/include/python2.3 -D_THREAD_SAFE -I/usr/local/include/atk-1.0 -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/X11R6/include/gtk-2.0 -I/usr/X11R6/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/X11R6/include/pango-1.0 -I/usr/local/include/freetype2 -I/usr/local/include -g -O2 -Wall -std=c9x -fno-strict-aliasing -c gdk.c -Wp,-MD,.deps/_gtk_la-gdk.TPlo -fPIC -DPIC -o .libs/_gtk_la-gdk.o gdk.override: In function `_wrap_gdk_keymap_translate_keyboard_state': gdk.override:3968: syntax error before `state' gdk.override:3973: `py_state' undeclared (first use in this function) gdk.override:3973: (Each undeclared identifier is reported only once gdk.override:3973: for each function it appears in.) gdk.override:3978: `state' undeclared (first use in this function) gdk.override:3984: `modifiers' undeclared (first use in this function) *** Error code 1 Stop in /usr/home/jcm/python/pygtk-2.3.92/gtk. *** Error code 1 Stop in /usr/home/jcm/python/pygtk-2.3.92. *** Error code 1 Stop in /usr/home/jcm/python/pygtk-2.3.92. root:~/python/pygtk-2.3.92# Can I fix this?? From babs at sntteam.org Wed May 26 09:55:18 2004 From: babs at sntteam.org (BaBS) Date: Wed, 26 May 2004 15:55:18 +0200 Subject: Bad interpreter References: Message-ID: Le Wed, 26 May 2004 09:49:09 -0400, Peter Hansen a ?crit?: > Peter Hansen wrote: > >> Benjamin Niemann wrote: >> >>> Peter Hansen wrote: >>> >>>> Remove the hidden CR character which you got at the end of the >>>> lines by moving the file to a Windows system and editing it. ;-) >>>> >>>> This one is pretty tricky to figure out the first few times... >>> >>> Should be the other way 'round: If you edit the file under Windows >>> (e.g. with Notepad), (invisible) CRs are added. >> >> We're saying the same thing. > > Ah, I see you understood me to be saying that "by moving the > file to a Windows system you can remove the CR characters". > > My intended meaning was "you got the CR characters > by moving the file to a Windows system", and I wasn't giving > him any idea how to remove them. :-) > > Confusion solved... > > -Peter 1000 times sory, misunderstand :) I read too fast :) Thanx anyway :) -- Damien ++ I've lost my mind ... But it's on a backup tape ... ... somewhere ... From fgeiger at datec.at Sun May 23 08:14:50 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 23 May 2004 14:14:50 +0200 Subject: wxPython: Looping over all children of a sizer References: <39cbe663.0405200038.3406d131@posting.google.com> Message-ID: Since you are the one who's stuffing all the controls into the sizer, you are the one knowing how much of them have been stuffed into it, i.e. add them all to an internal list, as you add them to a sizer. To remove one of them you have to call wxSizer::Remove(). HTH Franz GEIGER "Piet" schrieb im Newsbeitrag news:39cbe663.0405200038.3406d131 at posting.google.com... > Hello, > I need some help with the design of a "dynamic" wxDialog. > The dialog window is divided into several sizers, the first contains a > wxComboBox. When choosing an entry from this wxComboBox, a second > sizer (RowColSizer) will be populated with some controls, the number > and type of which will depend on the selected ComboBox-Entry. That > works fine for the first selection: The wxDialog is enlarged to give > room for the new controls. But when I make another selection, I get an > error saying that some positions in the sizer are populated twice. It > is obvious that the sizer has to be cleared before I put in the new > controls. I checked the documentation and found the Remove-Method for > sizers. Unfortunately, this method seems only to be able to remove a > sizer completely (which is not want I want, because the sizer will be > repopulated in the next step, and I dont want to recreate it, because > the sizer has to keep its position in the dialog relative to the other > sizers) or to remove the item with the specified position (which is no > alternative as well, because the number of childs or controls in the > sizer will vary). > Now my question: is there a clearall-Method for sizers that removes > all the items in the sizer or is there a function to get the number of > childs in the sizer so that I could write something like > for i in range(sizer.GetNumberOfChildren()): > sizer.Remove(i) > > That would help me a lot. > Thanks in advance > Piet From nospam at dontreply.com Sun May 2 07:33:21 2004 From: nospam at dontreply.com (Peter) Date: Sun, 02 May 2004 07:33:21 -0400 Subject: Pyrex 0.9.1.1 compile problem References: Message-ID: <_-ednU2WDbAcQQnd4p2dnA@comcast.com> Paul Prescod wrote: snip.... > Perhaps this will help: > > http://lists.copyleft.no/pipermail/pyrex/2004-May/000727.html > > Paul Prescod Thx. I appreciate it! From indigo at bitglue.com Sat May 29 14:27:39 2004 From: indigo at bitglue.com (Phil Frost) Date: Sat, 29 May 2004 14:27:39 -0400 Subject: extracting code objects from .pyc In-Reply-To: <001d01c44549$064d12a0$0900a8c0@amr.corp.intel.com> References: <20040529060608.GA23118@unununium.org> <001d01c44549$064d12a0$0900a8c0@amr.corp.intel.com> Message-ID: <20040529182739.GA15164@unununium.org> clarification: I'm looking for something that will give me a PyObject of the code flavor that can be passed to something like PyImport_ExecCodeModule, not a reconstruction of the source code. On Fri, May 28, 2004 at 11:48:59PM -0700, Dmitry Borisov wrote: > Did you try this ? > http://www.crazy-compilers.com/decompyle/ > > ----- Original Message ----- > Subject: extracting code objects from .pyc > > > > Could someone please tell me what should be done to extract a code > > object from a .pyc? Poking through the source I find examples of using > > PyMarshal_ReadLastObjectFromFile to get it, but when I tryed this myself > > it wouldn't work, so I'm wondering what I might be doing wrong. One > > difference is that the files have already been loaded to ram (by my > > bootloader), so I was using PyMarshall_ReadObjectFromString instead. From jbenson at sextans.lowell.edu Fri May 21 12:55:05 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Fri, 21 May 2004 09:55:05 -0700 (MST) Subject: Problem compiling python on RedHat 9.0 In-Reply-To: Message-ID: On Fri, 21 May 2004, KC wrote: > Trying to compile Python-2.3.3 on RedHat 9 and am having problems with > the X11 and tk stuff: > > In file included from /opt/Python-2.3.3/Modules/_tkinter.c:71: > /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory You need: XFree86-devel-4.3.0-2.rpm to get the Xlib.h file. Jim From barfsky at hotmail.com Fri May 7 10:56:35 2004 From: barfsky at hotmail.com (Jack B.) Date: 7 May 2004 07:56:35 -0700 Subject: system command Message-ID: <6f37c65.0405070656.4f00ff08@posting.google.com> I am trying to execute a system command within my python/Tkinter program, but I do not want to wait for it to exit. It will launch a different Tkinter program to be run at the same time. This seems like it should be simple, but I cannot find a way to do it. Help please, thanks! In Perl, this would be very simple. But perhaps it is simple in Python and I just have not found it yet. Ralph P. From nico at logilab.fr Mon May 17 07:57:09 2004 From: nico at logilab.fr (Nicolas Chauvat) Date: Mon, 17 May 2004 11:57:09 +0000 (UTC) Subject: General Ledger/Accounting Libraries References: Message-ID: > Our company is currently evaluating Python as a language for writing > financial/accounting type software (among others). > > What libraries or packages are available in this domain for use? PyCompta works for our (small) company : An accounting tool that reads entries written in a set of XML files and computes all reports including income statements and balance sheet. An accounting tool that reads "double entries" written in a set of XML files and computes the journal, general ledger, work sheet, income statements and balance sheet. Accounting records are outputed as XML files that can be rendered to HTML, XSL:FO and PDF. http://www.logilab.org/projects/pycompta/ -- Nicolas Chauvat logilab.fr - services en informatique avanc?e et gestion de connaissances From jmeile at hotmail.com Tue May 11 05:16:01 2004 From: jmeile at hotmail.com (Josef Meile) Date: Tue, 11 May 2004 11:16:01 +0200 Subject: perl to python In-Reply-To: <40a03b44_3@newsfeed.slurp.net> References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> Message-ID: <40a08893$1@pfaff2.ethz.ch> Steven Rumbalski wrote: > Olivier Scalbert wrote: > > >>Jarek Zgoda wrote: >> >> >>>Olivier Scalbert pisze: >>> >>> >>>>What is the python way of doing this : >>>>perl -pi -e 's/string1/string2/' file >>>> >>> >>>Use sed. >>> >> >>yes, but in python ? > > > print 'Use sed.' Yes, but you're assuming that the users are using Unix/linux. What's about the windows users? Perhaps there is a sed for windows already, but why to bother installing it? From pxlpluker at cfl.rr.com Sun May 9 08:08:43 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sun, 09 May 2004 08:08:43 -0400 Subject: how robust is (CGIHTTPServer ) In-Reply-To: References: Message-ID: <409E1F4B.4060205@cfl.rr.com> can anyone point out a good example of setting up a cgi capable twisted web? Ryan Paul wrote: >On Sat, 08 May 2004 21:02:29 -0400, pxlpluker wrote: > > > >> i was looking at twisted but it appears to be WAY beyond my megar >>skills at this point. >>so i think CGIHTTPServer will fit my needs if it is pretty stable. >>I have a small python cgi that i was building and i had this great idea >>of having the cgi server kinda rolled into it for various portability >>reasons and maybe some future features that would not have apache to >>realy on. >> >>Fred >> >> > >When faced with a frustrating deployment scenario, I too considered this >possibility. The standard CGIHTTPServer is really more of a >testing/debugging mechanism. I found that the 'Twistd' python network app >framework met my needs better than the CGIHTTPServer module. It really >depends on how much traffic you plan on dealing with. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jarod68 at despammed.com Sun May 9 19:16:54 2004 From: jarod68 at despammed.com (jarod) Date: Mon, 10 May 2004 01:16:54 +0200 Subject: Python for Nokia Series 60 References: <2g7c6lF52kr4U1@uni-berlin.de> Message-ID: <2g7siqF57e6rU1@uni-berlin.de> > Nokia 6600 has symbian OS v.7 yes, I know it Series 60 Developer Platform http://www.forum.nokia.com/main/0,6566,010_40,00.html Series 60 SDK for C++ http://www.forum.nokia.com/main/0,6566,034-4,00.html > I have not see "binary" on the links, but only "news". Sympython - Python Port for Symbian OS 7 (P800/P900) Phones (test binary available on request) ^^^^^^^^^^^^^^^^^^^^^^^^ maybe you can query Enki Boehm if it's compatible with Nokia 6600 and if you can obtain the "test binary" made by Enki. But you haven't answered to my question. Why not think to the use of Jython ? Do you know nothing about Java ? Ciao Jarod From miki.tebeka at zoran.com Mon May 10 10:15:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 10 May 2004 16:15:53 +0200 Subject: Shipping embedded Python project Message-ID: Hello, I've extended a C++ project with Python. I'd like to ship the new project with all the required Python modules but *without* installing Python on client machines. I know that py2exe/Installer/cx_freeze ... know how to find which modules are needed and pack them. Is there a "standard" way to do this? I didn't find anything in the docs. Thanks. Miki From __peter__ at web.de Mon May 24 04:57:01 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 May 2004 10:57:01 +0200 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: Dan Bishop wrote: > What you can do to make your code faster (if you don't change matr > once it's created) is to precompute the 676 possible matrix rows. > > ELEMENT_RANGE = range(26) > MATRIX_ROWS = [[x, y] for x in ELEMENT_RANGE > for y in ELEMENT_RANGE] > for row1 in MATRIX_ROWS: > for row2 in MATRIX_ROWS: > matr = [row1, row2] > > That takes only 532 ms -- almost 3 times faster than the original. Nice. Another speed gain (from 435 to 246ms on my machine) is in for you if you use tuples instead of lists. And if you allow for somewhat less elegant code that builds on your recipe, from itertools import izip, repeat ELEMENT_RANGE = range(26) MATRIX_ROWS = [(x, y) for x in ELEMENT_RANGE for y in ELEMENT_RANGE] for row in MATRIX_ROWS: for matr in izip(repeat(row), MATRIX_ROWS): pass you can bring that down to 138ms. For the record: the straightforward solution (the original with tuples and range() factored out) r = range(26) for a in r: for b in r: for c in r: for d in r: matr = ((a,b),(c,d)) takes 478ms. The "improved" variant is evil performance-wise (1598ms): r = range(26) for (a,b,c,d) in [(x,y,z,t) for x in r for y in r for z in r for t in r] : matr = ((a,b),(c,d)) It might be interesting how much this can be improved with 2.4's generator expressions. Peter From peter.maas at mplusr.de Wed May 26 12:50:51 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Wed, 26 May 2004 18:50:51 +0200 Subject: creating .exe file In-Reply-To: <3f0686ff.0405260841.6deba711@posting.google.com> References: <3f0686ff.0405260841.6deba711@posting.google.com> Message-ID: Q X wrote: > I am wondering what kind of tools are available to wrap python scripts > into just 1 .exe file (with no other files) in windows. I also want > the .exe file to be able to use command line arguments ie. > pythonprogram.exe -classpath d:/temp -file c:/hi.text http://sourceforge.net/projects/py2exe Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From noemail at noemail4u.com Tue May 11 07:38:00 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Tue, 11 May 2004 11:38:00 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> Message-ID: On Tue, 11 May 2004 11:16:01 +0200, Josef Meile wrote: >Steven Rumbalski wrote: >> Olivier Scalbert wrote: >> >> >>>Jarek Zgoda wrote: >>> >>> >>>>Olivier Scalbert pisze: >>>> >>>> >>>>>What is the python way of doing this : >>>>>perl -pi -e 's/string1/string2/' file >>>>> >>>> >>>>Use sed. >>>> >>> >>>yes, but in python ? >> >> >> print 'Use sed.' >Yes, but you're assuming that the users are using Unix/linux. What's >about the windows users? Perhaps there is a sed for windows already, but >why to bother installing it? There's definitely a sed available, possibly even in MingW (I have it on my system, but am not sure if it arrived with MingW or something else I installed). It's definitely available with cygwin. One reason to install it is that it's smaller than perl or python; another is that it probably performs the task faster, since it isn't a general purpose state machine; another is that it's 25% shorter to type than perl and 50% shorter to type than python. --dang From kirk at strauser.com Sun May 2 11:45:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Sun, 02 May 2004 15:45:06 GMT Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: <87llka4z0v.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-04-30T23:43:37Z, Bart Nessux writes: > I need to ping 4 hosts at exactly the same time from the same machine (I > plan to timestamp the pings) to test and measure network conditions over > different routes to different hosts. Putting all the ping hosts in a list > and looping through it is not a fair or balanced way to do this because of > the time differences. In other words, you want to emulate the functionality of fping without using fping. Is that about right? - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAlRaz5sRg+Y0CpvERAt8xAJ4sS+FzCv/Bm57o2b3s3Weh2yTV3gCeM68p JVstKJijYWIQxU9+izWk7hQ= =zCda -----END PGP SIGNATURE----- From kmmcdonald at wisc.edu Wed May 5 22:12:26 2004 From: kmmcdonald at wisc.edu (Kenneth McDonald) Date: Thu, 06 May 2004 02:12:26 GMT Subject: Python documentation: How about structured documentation? Looking for comments/suggestions Message-ID: This seems to tie in with a few other things that have been posted recently... One of the things I'm currently working on is something I call pk, a layer on top of Tkinter which gives a much more object-oriented inteface to Tk. This is relatively complex, and one of the things I'm missing is the lack of good doctools support in Python. Something like Javadoc would be nice. Something like d'oxygen would be even nicer. Both of those depend on a "documentation markup language", which is something Python doesn't have, and which is a pain to define and implement. But, Python can easily define such a markup language, it would seem, simply by defining appropriate functions. So, I spent a few hours today writing a page or so of code, and came up with a little library which, used in the following way: from doct import * t = "To be or not to be; that is the question." print doct( dsection("Section", t, titleunderline="="), dargs(arg1="This is argument 1, with a long description", arg2="Second arg.") ) (doct is both the module name, and the name of a function) prints out this: Section ======= To be or not to be; that is the question. ARGUMENTS --------- arg1: This is argument 1, with a long description arg2: Second arg. (The lines are short because I was testing wrapping and didn't want to type in too much test text.) Doing this has convinced me of a number of things: 1) It'd be very easy to get a useful doct library up and running quickly. 2) Generators greatly ease the writing of this sort of thing, and make it much more efficient. (Well, I only suspect the latter, but it's a suspicion that's easy to justify.) 3) Using Python to write Python documentation is a big plus, because a Python-oriented editor typically is set up in such a way that it aids in the viewing of the documentation as it is written. (For example, my editor is set to bold function apps, and display strings in green; so in the example given, the structure of the document is clearly visible just by looking at the bold elements and, of course, by indenting.) The only minus is that one types perhaps more quotes/parens/commas than would be desirable, but I found that to be an annoyance that was greatly outweighed by being so easily able to work with the structure of the document. 4) This could be used to generate multiple types of output. I don't think it would be much more work to support, say HTML output. The biggest annoyance is the fact that this would not have any support such as enjoyed by docstrings, so instead of saying something like: def foo(x): '''docs''' pass one would have to say something like def foo(x): pass foo._doct_ = doct('''docs''') This is more of a drawback than it might seem; in longer functions/classes, the documentation is no longer near the start of the function/class. I'd appreciate it if people could comment on what they think of such an approach. If there is any interest, perhaps we could define a basic set of documentation functions and implement them, and then see what happens from there. Thanks, Ken McDonald From mva at sysfault.org Fri May 28 14:02:13 2004 From: mva at sysfault.org (Marcus von Appen) Date: Fri, 28 May 2004 20:02:13 +0200 Subject: "Private" Member Variables References: Message-ID: <86k6ywig62.fsf@sysfault.org> "Scott Brady Drummonds" writes: [...] > class C: > ... > def value(self): > return self.__value > ... > The problems that arise from directly relying on the member variable in C++ > (compile-time type dependency, as I said above) don't exist in Python. So > why provide an accessor at all? Why not just allow direct reading and > writing of the member variable? Is there something here I'm missing? Yes. Imagine a class, which's attributes should only be able to hold a specific value range, e.g. a triangle, of which the side length should not exceed 10. If you would use the class as - let's say a third party developer and this class does not contain an accessor nor this 'private' indicator (_ or __), you possibly would not know about that limited value range. You would simply type in triangle.side = 50. Now another calculation method using that triangle object could receive a value overflow, because it cannot calculate with such a 'big' value, but is limited to 10. An accessor and private attribute could avoid this: * You would know, that the author of the class does not want you to modify the attribute directly. * The accessor could test the value range at input. ... etc.pp. You see: It makes sense for other developers, so they can easily see the difference between your private attributes, which are not meant to be used directly and public usable ones. Another advantage is that your private method and attribute documentations are not shown using 'pydoc YourClass' ;-). > What are your thoughts? How much privacy should I build into my code? > Should I be using variables beginning with "__" and accessors? Or is that > simply not necessary (or normal) in Python code? As written above, it can make sense. You have to determine, if it is useful for you :-). Regards Marcus -- We don't understand the software, and sometimes we don't understand the hardware, but we can *see* the blinking lights! From Shubhra_Gupta at infosys.com Thu May 20 08:01:03 2004 From: Shubhra_Gupta at infosys.com (Shubhra Gupta) Date: Thu, 20 May 2004 17:31:03 +0530 Subject: query regarding python script Message-ID: <2B721C6525F0D411B1E900B0D0226BDD04AFDE7A@mohmsg01.ad.infosys.com> > Hi, > > I have the following statement in one my python script :- > > assert not opt_initialize or os.path.exists(initdir), "initialize implies init directory" > > Could u tell please what it is intended to do? > > Regards, > Shubhra Gupta From babs at sntteam.org Wed May 26 06:53:22 2004 From: babs at sntteam.org (BaBS) Date: Wed, 26 May 2004 12:53:22 +0200 Subject: Bad interpreter Message-ID: I've a problem whith my python script, i chmod'ed it to +x, addes the line : #!/usr/bin/python2.3 and i verified that /usr/bin/python2.3 exists but i've something like : bad interpreter: No such file or dir ... What's the matter ?? Thanx From pinard at iro.umontreal.ca Thu May 27 17:56:37 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 27 May 2004 17:56:37 -0400 Subject: Why a class when there will only be one instance? In-Reply-To: <40B3E861.29B033D5@shaw.ca> References: <40B3E861.29B033D5@shaw.ca> Message-ID: <20040527215637.GA2389@alcyon.progiciels-bpi.ca> [SeeBelow at SeeBelow.Nut] > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be > one instance. What is the benefit of this? There are two advantages for me: 1) It helps at keeping related data and actions together within a named concept. This further increases legibility and eases maintenance. 2) The global namespace stays much cleaner. (A side effect is that I never need the `global' declaration in practice.) > It has a disadvantage of a whole lot of "self." being required > everywhere, making the code less readable. While those `self.' are a bit of a clutter indeed, they help me to read that this routine is calling this other one within the same conceptual part of the whole program, and as such, they had documentation value. > Oh, also, all the methods of this class will have to have the instance > name prepended to them. It would be `self.' within the class itself, and the instance name within foreign classes. This habit stresses the relations between the parts of the program and eases a better understanding of the whole. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From greg at thirdstone.net Sat May 15 16:39:06 2004 From: greg at thirdstone.net (Juan Stang) Date: 15 May 2004 13:39:06 -0700 Subject: cmd Library Module trouble References: Message-ID: Thank you Fernando! Solved the problem entirely. Appreciate it. From vineet at eswap.com Thu May 20 17:30:53 2004 From: vineet at eswap.com (Vineet Jain) Date: Thu, 20 May 2004 17:30:53 -0400 Subject: Help with large data set and fatal python error (pysqlite) In-Reply-To: <20040520135937.9C98.SLAWEK@cs.lth.se> Message-ID: > I don't know how much help would it be, but the code below is working > fine for me - for as much as "numInnerLoop = 150" and "k in range(5)". > So it would seem like a problem specific to your system. Thanks. what python version do you have? I tried the code on three different version and it gave the same problem: 1. Windows XP Pro, Dell 8600, Sqlite 0.5.0 2. Windows Advanced Server, Dell Server, Sqlite 0.5.0 3. Windows XP, dell lattitude, Sqlite 0.50 I still get the same problem. I also tried the same thing with sqlite cvs snapshot and that did not help. In the mean time, since I have to get this working, I'm in process on using pyrex to access the sqlite db directly. From adalke at mindspring.com Sat May 15 00:40:08 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 15 May 2004 04:40:08 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> <8gisf1ihvc.fsf@galapagos.bx.psu.edu> <8g4qqik8zd.fsf@galapagos.bx.psu.edu> Message-ID: Scott Schwartz > No effect, because that's not the problem. Ahh, you're right. I keyword matched "buffer" and thought you meant the system buffer and not Python's. Andrew dalke at dalkescientific.com From scott.b.drummonds.nospam at intel.com Fri May 28 12:56:43 2004 From: scott.b.drummonds.nospam at intel.com (Scott Brady Drummonds) Date: Fri, 28 May 2004 09:56:43 -0700 Subject: "Private" Member Variables Message-ID: Hi, everyone, I'm still learning Python as I develop a medium-sized project. From my previous experience with C++, I've burnt into my mind the notion of information hiding. I'm having trouble understanding to what extent I should follow this policy in my Python code so I thought I'd ask the group. I read from a previous post that to attain a private-like status of member variables, I should prefix the variable name with two underscores ("__"). This does work, but in another post someone asked me if this was really necessary. Given that the very nature of the language precludes any compile-time type dependencies I'm wondering if there is any benefit to naming variables with leading underscores and providing accessor functions like this: class C: ... def value(self): return self.__value ... The problems that arise from directly relying on the member variable in C++ (compile-time type dependency, as I said above) don't exist in Python. So why provide an accessor at all? Why not just allow direct reading and writing of the member variable? Is there something here I'm missing? What are your thoughts? How much privacy should I build into my code? Should I be using variables beginning with "__" and accessors? Or is that simply not necessary (or normal) in Python code? Thanks, Scott -- Remove .nospam from my e-mail address to mail me. From ajsiegel at optonline.com Thu May 27 21:21:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 01:21:05 GMT Subject: terminological obscurity References: <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> Message-ID: <0f4db0pogedij0jm6hk6sfh0qn8rgd8bu4@4ax.com> On Fri, 28 May 2004 00:37:39 GMT, Arthur wrote: >Yet you insist, with a fresh start on all this, on using the >terminology "homogenous data". I only see 3 possibilities: 1. You are going further than Donn and Michael Chermside, who maintained that Guido meant exactly what should be meant, but didn't express it well. Are you saying that Guido meant exactly what should be meant, and expressed it as it should be expressedl - and that Donn and Michael are also missing something (perhaps more subtle than what I am missing)? 2. You are using the same terminology, now in a different sense. 3. You are expressing some sense that this issue as to terminology doesn't interest you - as long as you and Guido know what you and Guido mean. Art From moughanj at tcd.ie Tue May 18 20:00:12 2004 From: moughanj at tcd.ie (James Moughan) Date: 18 May 2004 17:00:12 -0700 Subject: Unification of Methods and Functions References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> Message-ID: <16752bcc.0405181600.3b6d6373@posting.google.com> David MacQuigg wrote in message news:... > On Mon, 17 May 2004 16:40:00 +1200, Greg Ewing > wrote: > > >David MacQuigg wrote: > >> James has been telling me it is terribly wrong to keep data as > >> attributes of classes > > [snip] > > This makes a lot more sense than a total ban on data in classes. > Just to clarify, once again - I was not suggesting a ban on data in classes - I was objecting to the specific way in which the data was being passed around and used in the class heirarchy. > I think the generalization to a "multi-zoo" program probably belongs > in the third example, along with perhaps some techniques like James > showed to make the code more robust by generating the classes rather > than writing them. The first and second examples ( Animals_1 and > Animals_2 need to be very simple. > > -- Dave From skip at pobox.com Fri May 14 09:50:38 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 May 2004 08:50:38 -0500 Subject: Troubles with CSV file In-Reply-To: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> References: <012e01c4399b$6066cb00$6b0aa8c0@vladimirpc> Message-ID: <16548.52910.951086.907584@montanaro.dyndns.org> Vladimir> I have a big CSV file, which I must read and do some Vladimir> processing with it. Unfortunately I can't figure out how to Vladimir> use standard *csv* module in my situation. The problem is that Vladimir> some records look like: Vladimir> ""read this, man"", 1 Invalid CSV... Vladimir> Quick experiment show me that *csv* module (with default Vladimir> 'excel' dialect) expects something like Vladimir> """read this, man""", 1 Valid CSV... Here's the rule. If a field contains the separator character (a comma in this case) or the quote character the field must be quoted and any embedded quote characters must be doubled. Your first example doesn't obey this rule. The second one does. Vladimir> Maybe some *alternative* CSV parsers can help? Any Vladimir> suggestions are welcomed. I suggest you either modify the program that wrote the CSV file in the first place and regenerate your CSV file. If that's not possible, perhaps you can manually massage it (or write a smallish Python script to massage it) now that you know how the file must be formatted. Skip From daniel.dittmar at sap.com Thu May 13 04:58:38 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 13 May 2004 10:58:38 +0200 Subject: iterators References: Message-ID: Manlio Perillo wrote: > Python support forward iterators, but what about bidirectional and > random access ones? 'random access iterators' are called 'Sequence' types in Python (http://www.python.org/doc/2.3.3/lib/typesseq.html). You can create your own sequence types by implementing some special methods (http://www.python.org/doc/2.3.3/ref/sequence-types.html). Daniel From fperez528 at yahoo.com Sat May 15 15:38:53 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Sat, 15 May 2004 13:38:53 -0600 Subject: bug in inspect (was cgitb vs traceback) References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> <40A5D206.3000901@jessikat.fsnet.co.uk> <40A5D94D.6010708@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Robin Becker wrote: > > ..... >> >> No I'll mosy on over and see if it's known. I have a fix in place in our >> code, but we had to modify it yesterday as we're delivering for 2.1. > > I didn't find anything similar there so I submitted a bug report and the > patch I used. I think it's far too late for 2.3.4. Do you have the SF bug number handy? I'd like to track this one in detail, in case it really is what is giving my ipython users problems. Push comes to shove, I could always patch inspect.py 'live' for the users at import time, that's the beauty of python :) Regards, f From peter.maas at mplusr.de Thu May 13 03:13:41 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 13 May 2004 09:13:41 +0200 Subject: make faster Richards benchmark In-Reply-To: <6748553f.0405122211.5be5a150@posting.google.com> References: <6748553f.0405122211.5be5a150@posting.google.com> Message-ID: Duncan Lissett wrote: > I'd appreciate any suggestions on how to make faster Python > implementations of Richards benchmark. Perhaps there are obvious > problems that can be corrected? The most obvious problem: how does the Richards benchmark work? Care to post the source code? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From ian.tospamnot at sympatico.ca Fri May 28 12:58:44 2004 From: ian.tospamnot at sympatico.ca (Ian) Date: Fri, 28 May 2004 12:58:44 -0400 Subject: programming video manipulation References: Message-ID: On Tue, 25 May 2004 15:15:39 -0400, Olivia Robinson wrote: >I have been investigating Python as an alternative to using >MAX/MSP/Jitter to program the collection of information from the >sensors and the resulting video manipulation. I have not been able to >find information about manipulating video with Python, or collecting Hi Olivia, I don't have answers for all your questions, but you may be interested in this project: http://aid.interaccess.org/drupal/ We are developing a standard microcontroller module for use by artists, and have developed Python interfaces for it. We've also used Director and Pure Data (similar to Max I understand). Currently the module uses a serial interface, we use usb-to-serial adapters. We have an experimental usb board interface and will be implementing usb support for our Python module. All source will be available on our site, as well as recipes for software and hardware configuration. There are a variety of hardware interface modules available for the board. By the way you can build your own board from the info on our site, or soon buy finished boards as well. We don't have any direct support for video at the moment, but that should change soon. Ian From p at ulmcnett.com Thu May 13 12:14:21 2004 From: p at ulmcnett.com (Paul McNett) Date: Thu, 13 May 2004 09:14:21 -0700 Subject: ANN: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: References: Message-ID: <200405130914.21924.p@ulmcnett.com> David Fraser writes: > My gzip doesn't like your dabo unix source tar.gz files ... > are they OK? No they weren't. My Python upload script was converting them from binary to ascii by adding the linefeeds for the appropriate platform. This 'feature' has been fixed, with good files uploaded. Sorry for the inconvenience. -- Paul From SeeBelow at SeeBelow.Nut Fri May 14 16:08:40 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Fri, 14 May 2004 20:08:40 GMT Subject: Where do I find what colors and fonts are available? References: Message-ID: <40A5275A.F14F7B8C@shaw.ca> "Hornberger, Chris" wrote: > > >> and font names are available on my system. I'm using Windows 2000. > >I'd search for *.ttf (a particular kind of font file), and look at the > >directories where several of these show up. This is, of course, a Win2K > >rather than Python Question. On my installation, the fonts are in > >C:\WINNT\Fonts. > > *nods* You mentioned that's a platform issue and not a Python issue. That's key, depending on what he's looking to do. > > If he's looking for platform independence (and who wouldn't be in Python?), whatever GUI manager he's using will probably have the necessary functions/libraries for enumerating the fonts that *it* knows how to deal with, which would be the more accurate way to find fonts... speaking, again, platform-independently. I didn't mention it in my original post, but I do need platform independence. I want to choose fonts and colors that will work with Windows or linux. So I need a way of knowing what my options are, i.e., what colornames and fonts are available, both on my system and other peoples systems. For example, "blue" is always available, but "salmon" may not be. "courier" is probably always available, but "Bookman Old Style" may not be. At the moment I don't even know what's available on my own system, let alone other people's, and I have not found this info in any documentation. Does Tkinter include its own fonts and colors? If so, where do I find their names? If not, same question anyway. m -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From timr at probo.com Sat May 29 20:16:45 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 29 May 2004 17:16:45 -0700 Subject: pdf2txt References: Message-ID: <3q9ib05a77g436ibh6vdr0hbku7407k0tv@4ax.com> B P wrote: > >Is there a way via Python or even Perl to capture records from a pdf and > output a delimited text file? My work has a situation with a trunk >load of data forms that were scanned as pdfs. SCANNED as PDFs? Do you mean these were paper forms, filled in using printed handwriting, then scanned into a TIFF and wrapped up in a PDF? If so, your job is next to impossible. You can extract the original bitmapped image out of the PDF, and from that you MIGHT be able to use an OCR program to extract the text, but unless the forms were specifically designed for machine reading, that process tends to be error-prone. It might be more efficient to have human beings translate them. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From corrado.clementi at ciaolab.com Fri May 21 12:51:32 2004 From: corrado.clementi at ciaolab.com (corrado) Date: 21 May 2004 09:51:32 -0700 Subject: Help on multithreading and Tkinter; Linux vs Windows Message-ID: Hello I have an application running several thread to display some financial data; basically I have a thread displaying HTML tables by means of Tkhtml, another implementing a scrolling ticker based on a Text widget with embedded windows and a thread running the Tkinter mainloop plus several other thread dealing with the scheduling of the contents and the acquisition of data but not using graphic widgets. I run the same code on Linux and Windows; I have no problems on Linux while on Windows everything get stucked when I tried to scroll the ticker, it looks like I'm blocked in mywidget.xview(SCROLL,1,UNITS); at this time the graphic of the application freezes while all the rest goes on running. I tried several other strategies, like having the ticker thread and the table displaying thread sending event to the mainloop to perform Tkinter methods call in callbacks instead of calling the methods themselves, but nothing seems to change. If I run root.update() after scrolling the ticker, I can see it moving a bit, but after some loops, I get the same frozen status. Is there anyone who can help me? I've already tried the Tkinter-discuss mailing list but I got no answer. I supposed Tkinter worked the same way under Windows and Linux but it does not look like it's so; is there any paper explaining the differences between the behaviour on the two operating systems? For instance on Windows I also had problem with iconify and with the button highlight, which is Windows standard whatever setting you try. Any help is really appreciated. Thanks in advance Corrado Clementi From edvard+news at majakari.net Wed May 26 14:29:47 2004 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 26 May 2004 21:29:47 +0300 Subject: Creating Python class wrapper for a command line tool References: <87aczvxuvr.fsf@titan.staselog.com> Message-ID: <874qq3jb38.fsf@titan.staselog.com> Rico Huijbers writes: > I am by no means a professional Pythonist... but it doesn't seem too bad > to me to check for each kwarg whether it's type is boolean and if so, just > add it to the command line as a flag instead of as a value parameter. And > data arguments can be passed in the *args tuple. Wow - I had to test it and didn't work. Then I remembered it would probably work with Python2.3, and it did. But the thingamajick must work with Python2.2. > obj = Wrapper("MUNGE1:x1:y:z:frob1", "MUNGE2:x2:y:z:frob2", > "MUNGE3:x3:y:z:frob3", optimize=True, use_bar=foo, threshold=10, > name="Alley cat") > > This just wraps everything in the constructor. Alternatively, you could go > for setting each command-line parameter via a method flag. Yes - well, command line options are not necessary a must, so I thought to separate those from data (which *is* compulsory for the thing to work). > Combining the two methods seems ugly to me, though. I admit, it is not as pretty. But the command I'm using takes lots and lots of parameters, flags etc. and one reason in having a Python interface is to avoid very long parameter lists (if constructor is not given any keyword arguments, some sane defaults are assumed for them). But thanks for the follow-up! -- #!/usr/bin/perl -w $h={23,69,28,'6e',2,64,3,76,7,20,13,61,8,'4d',24,73,10,'6a',12,'6b',21,68,14, 72,16,'2c',17,20,9,61,11,61,25,74,4,61,1,45,29,20,5,72,18,61,15,69,20,43,26, 69,19,20,6,64,27,61,22,72};$_=join'',map{chr hex $h->{$_}}sort{$a<=>$b} keys%$h;m/(\w).*\s(\w+)/x;$_.=uc substr(crypt(join('',60,28,14,49),join'', map{lc}($1,substr $2,4,1)),2,4)."\n"; print; From bignose-hates-spam at and-benfinney-does-too.id.au Thu May 27 02:15:38 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 27 May 2004 16:05:38 +0950 Subject: why learn References: <40b58695_1@news.iprimus.com.au> Message-ID: On Thu, 27 May 2004 16:11:39 +1000, mr_vocab wrote: > hey i finished working through alot of python stuff and no a fair bit > bout it Now it's time to improve your English. > now what can i do with it??? That's up to you. -- \ Legionnaire: "We have their leader captive!" C?sar: "Is he | `\ bound?" Legionnaire: "Of his health I know not, sir." -- The | _o__) Goon Show, _The Histories Of Pliny The Elder_ | Ben Finney From calvin at ironfroggy.com Mon May 31 06:25:23 2004 From: calvin at ironfroggy.com (Calvin Spealman) Date: Mon, 31 May 2004 10:25:23 +0000 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: <5908779.OXrkjMP8p8@ironfroggy.com> Peter Hansen wrote: > Zunbeltz Izaola wrote: >> I've trid this, but the problem is that this finished the try block. >> I want to continue executing the try block from the point the >> exception was raised. > > Not possible except, perhaps, with a significant amount of > working involving sys.settrace(). I think you need to find > another way to solve the problem. Have to admit tho, a continue feature might be useful. Some languages have this, don't they? The thing is, Where exactly to continue? Should you retry whatever raised the exception, continue just after it, at the beginning of that line, or what? From ajsiegel at optonline.com Thu May 27 20:37:39 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 00:37:39 GMT Subject: terminological obscurity References: <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> Message-ID: <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> On Thu, 27 May 2004 19:30:40 +0200, "Martin v. L?wis" wrote: > >It is very clear to my why he did not say what Donn said - because >he thought that the notion of homogenous and heterogenous is obvious >to anybody. FIRST ------------------------------------------------------------------------------------------------------- The name of our thread is "terminological obscurity". And I expect that the orignal poster had as good a grasp as you (or I) as to the meaning of homogenous and heterogenous. And it is certainly easy for Martin or Donn to assume that we are talking technically over the head of someone like myself. I'll go fuirther and allow us to assume that is part of what is going on. Another part of what is going on has nothing to do with that at all. It is about lnaguage and it is about logic and it is about the dynamics of groups. My involvement in this discussion began in reaction to a statment made to the typical question about why tuples *and* lists are in the language: Assume """ surrounds *exact* quotes from the newsgropup. """ It's a common question. A list is a data structure that is intended to be used with homogenous members; that is, with members of the same type. """ and in defense of a challange to this statement based on the flexibility of Python of handling data of different types in a list, came this response: """ This is perfectly true, but that's the intention. Guido says so himself. Lots of people either don't believe him, or don't understand him. """ So that, in effect, was the first time I was told that the problem is I don't understand what Guido meant, i.e. I didn't understand that lists were designed to be used " with homogenous members, that is weith members of the same type". Thankfully Donn interceded at that point to bring the dicussion more onto a sensible track. And as a result: We all agree, (do we not) at this point - even the poster of these remarks - if that is what Guido in fact meant, I was doing good not to understand him, (or believe him if I did.) SECOND ------------------------------------------------------------------------------------------------------------- When Donn thought the terminology "homogenous data" and "hetereogenous data" in the context of the discussionss were coming from me, or other "unofficial" sources, he implied strongly that the use of this terminology was part of what was creating some misunderstanding of the concepts involved. When I told him the terminology was not mine, but Guido's my lack of understanding (that being the constant) now became that I didn't understand what Guido meant when he used the terminology which was a moment ago unacceptable. That is the second time I was told the problem was *my* capacity to understand what Guido meant. > >He then *also* said something about how static typing might be >introduced into Python - but that was about possible static typing, >not about the terms "homogenous" and "heterogenous". Even with >static typing, it might be possible to declare a list that is >statically typed, contains homogenous data, and yet contains >objects as different as None and a module. The type of this >list might be "list of (NoneType union ModuleType)", better >declared as "list of optional ModuleType". THIRD ------------------------------------------------------------------------------------------------------------- Donn. who I think we agree, brought some light to this discussion did state clearly, I think, that the use of the "homogenous data" (in describing for example None and a module) is bad and misleading terminolgy. Perhaps, because it supports too well a supposition that we are only talking in tautologies. What can be said be homogenous about such data, outside of the membership in a list? Donn suggests the list is homogenous, even if the data is not, in any meaningful sense. I think I understand that a bit. Yet you insist, with a fresh start on all this, on using the terminology "homogenous data". I don't understand Martin any better thatn I understand Guido. In fact I am totally lost. Art From lbates at swamisoft.com Thu May 27 16:09:12 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 27 May 2004 15:09:12 -0500 Subject: remove item from list based on name References: Message-ID: Something like the following: locked_files=['C:\pagefile.sys', 'C:\hiberfil.sys', 'C:\Documents and Settings\All Users\Application Data\Microsoft\Dr Watson\user.dmp', 'C:\DOCUMENTS AND SETTINGS\LOCALSERVICE\NTUSER.DAT', 'C:\DOCUMENTS AND SETTINGS\LOCALSERVICE\ntuser.dat.LOG', 'C:\DOCUMENTS AND SETTINGS\NETWORKSERVICE\NTUSER.DAT', 'C:\DOCUMENTS AND SETTINGS\NETWORKSERVICE\ntuser.dat.LOG', 'C:\WINDOWS\SYSTEM32\CONFIG\default', 'C:\WINDOWS\SYSTEM32\CONFIG\default.LOG', 'C:\WINDOWS\SYSTEM32\CONFIG\SAM', 'C:\WINDOWS\SYSTEM32\CONFIG\SAM.LOG', 'C:\WINDOWS\SYSTEM32\CONFIG\SECURITY', 'C:\WINDOWS\SYSTEM32\CONFIG\SECURITY.LOG', 'C:\WINDOWS\SYSTEM32\CONFIG\software', 'C:\WINDOWS\SYSTEM32\CONFIG\software.LOG', 'C:\WINDOWS\SYSTEM32\CONFIG\system', 'C:\WINDOWS\SYSTEM32\CONFIG\system.LOG'] and your list of files is in your_files, use list comprehension to build a new_list. new_list=[f for f in your_files if f not in locked_files] This gets you a new list of only those files that are not in the locked_files list. Note, you must have an exact match (e.g. full pathnames) for this to work. HTH, Larry Bates Syscon, Inc. "Bart Nessux" wrote in message news:c95e2g$nm2$1 at solaris.cc.vt.edu... > Hi, > > I am generating a list of file names... some of the files are locked by > the OS (Windows XP) and I know the names of these files (NTUSER.DAT, > ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is > there a way that I can delete these items from the list based on their > names? > > Thanks, > Bart From segphault at sbcglobal.net Tue May 25 17:40:17 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Tue, 25 May 2004 21:40:17 GMT Subject: Help:What does this mean? References: Message-ID: On Wed, 26 May 2004 05:18:18 +0800, kr wrote: > Hello, > I am new to PytonWin. I have a simple script, just one line-- print "hello". > It runs OK when I use File/Run > But in command line >>> Script1.py > I got the error msg: > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'Script1' is not defined > > What's wrong with it? How can I fix it? > THKS > kr import Script1 --segphault From mtadin66 at yahoo.com Wed May 19 23:41:15 2004 From: mtadin66 at yahoo.com (Marijan Tadin) Date: Thu, 20 May 2004 04:41:15 +0100 Subject: beginner - viewer HTML-text with TkInter References: Message-ID: "WOJSAL" wrote in message news:c8crk9$cda$1 at inews.gazeta.pl... > I want show HTML-text (messages, textarea etc.) > with TkInter. What free package, module i need? > Please help. > -- > Regards > WOJSAL > http://www.wojsal.prv.pl As far as I know, there is no HTML widget in Tkinter. Just to solve a problem, you can use webbrowser module (http://www.python.org/doc/current/lib/module-webbrowser.html), which has nothing to do with Tkinter, but it will display some HTML text in a webbrowser of your choice. If it has to be all Tkinter, you might look at Grail (http://grail.sourceforge.net/). Marijan Tadin From eldiener at earthlink.net Tue May 18 21:54:49 2004 From: eldiener at earthlink.net (Edward Diener) Date: Wed, 19 May 2004 01:54:49 GMT Subject: Circular imports Message-ID: Although it may not be good design, I have a situation such that module A imports module B and module B imports module A. This appears to be causing problems when I use Python with mod_python/Apache and PSP programming. Can anybody tell me if there are any situations where circular imports cause problems and, other than a redesign to eliminate it, if there are any other ways around those problems ? From usenet at -OBFUSCATION-joefrancia.com Sat May 15 02:25:52 2004 From: usenet at -OBFUSCATION-joefrancia.com (Joe Francia) Date: Sat, 15 May 2004 06:25:52 GMT Subject: Palm Address Book Archive References: Message-ID: <1640543.jVXVUEme3l@joefrancia.com> Paul Gross wrote: > Does anyone know of a python module or script which can read the Palm > Address Book Archives? Using Palm Desktop, I can export my addresses to > a .aba file, but I can't find any code to use this file programmatically. > > I know that Palm Desktop can also export to comma and tab delimited > files, but this isn't as good for a few reasons. One, there's no way to > know what the custom fields are. Two, this method is dependent on how > the data is exported (which columns are selected and in which order). > > Thanks. > Paul There's a script here: http://www.geocities.com/Heartland/Acres/3216/palmrecs.htm -- Soraia: http://www.soraia.com From RobMEmmons at cs.com Tue May 4 22:21:03 2004 From: RobMEmmons at cs.com (Robert M. Emmons) Date: Tue, 04 May 2004 21:21:03 -0500 Subject: Need Help in Python In-Reply-To: <77632a66.0405041826.37568aef@posting.google.com> References: <77632a66.0405041826.37568aef@posting.google.com> Message-ID: <40984F8F.1000408@cs.com> Mahmood Mashal wrote: > Hello everyone. I started programming in Python like a month ago and i > have a problem. I want the program that I am writing to use a > character to draw a box. How can i declare that character as a > variable? If anyone could help me. Thanks Python has no declaration. Character strings are like any other variable: x = "a" or x = "abcdef" or x = chr(35) Several options. Rob From pit.grinja at gmx.de Sun May 2 12:05:02 2004 From: pit.grinja at gmx.de (Piet) Date: 2 May 2004 09:05:02 -0700 Subject: newbie answer on Python tutorial example in section 4.7.1 (default arg values) References: <56cfb0e3.0405011337.2a8710bc@posting.google.com> Message-ID: <39cbe663.0405020805.459b3403@posting.google.com> porky_pig_jr at my-deja.com (Porky Pig Jr) wrote in message news:<56cfb0e3.0405011337.2a8710bc at posting.google.com>... Hi TIA, > def f(a, L=[]): > L.append(a) > return L > > and somehow L just keeps growing between the calls, so > > print f(1) > returns [1] > and then > print f(2) > returns [1, 2] > etc. I'm not really clear on this example, but assume that L is set > aside somewhere (in the function definition), initialized only once > (during the def), and then all subsequent calls affect that locally > defined L. I agree that this one is diffcult to get. The point is (or seems to be) that when you do not provide a value for the second argument (which is true for all the function calls), the default value is used. So during the first call, the interpreter notices that L is lacking, assigns the default value to it (empty list) and then passes this parameter together with the already given 'a' to the function. When you call the function a second time without a value for L, the default L will again be passed to the function, but it will not be evaluated, so the assignment "L = []" will not be executed and the non-empty list L will be passed to the function. When you change the function to > def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L your first function will evaluate the assignment for L resulting in the "value" "None" for L (I am not sure whether one should talk about values in this context). On successive calls to the function without a given parameter for L, the expression for L will NOT be evaluated, but the lack of the parameter will be noted, and thus the if-clause will be evaluated as true and assign the value "[]" to L which will then be used on further execution. This is at least what I thought. I just checked the behaviour of the function when you change the default value for L from "None" to "[]". In this case I had expected that successive calls of the function would notice the absence of L and that the if-clause would evaluate as true as well, but this is not the case. So when you change the function to > def f(a, L=[]): > if L is None: > L = [] > L.append(a) > return L and write f(1),f(2) and so on you will also see that the list is growing with each function call. So my post was not that helpful, I guess. Maybe a python expert has some explanation. I am looking forward to see how that thread will develop. Best wishes Piet From moughanj at tcd.ie Mon May 24 06:01:17 2004 From: moughanj at tcd.ie (James Moughan) Date: 24 May 2004 03:01:17 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> <16752bcc.0405230518.2023328a@posting.google.com> Message-ID: <16752bcc.0405240201.7eede57@posting.google.com> David MacQuigg wrote in message news:... > On 23 May 2004 06:18:54 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >David MacQuigg wrote in message news:... > >> On 22 May 2004 11:50:18 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> > >> >David MacQuigg wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... > >> >> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> >> >David MacQuigg wrote: > > >> >> I like your example, but not as a *substitute* for Animals_2. It's > >> >> just too complex for non-CIS students at this point in the course. I > >> >> think I understand your concerns about Animals_2. I think the best > >> >> way to deal with those concerns is not by complicating the example, or > >> >> by taking out everything that could lead to problems, but rather by > >> >> pointing out the problems, and showing subsequent examples that fix > >> >> those problems, even at the expense of more complexity. > >> >> > >> >> If you have a simple all-in-one alternative to Animals_2, show me. > >> >> > >> > > >> >Again, clearly I have not communicated myself well - I mean a > >> >*completely* different example to the entire Animals approach. The > >> >difficulty with writing a good Animals-type example comes from the > >> >things which it is trying to do, which aren't especially well > >> >expressed by a class-heirarchy. > >> > >> What I am trying to do in Animals_2 is provide the simplest, most > >> learnable example of Python OOP, which has at least one of every basic > >> structure the students will encounter in a real program. So I include > >> bound, unbound, and static methods, but not metaclasses or > >> descriptors. > >> > >> Creating a good example like this is turning out to be more of a > >> challenge than I expected. I'm fairly happy with Animals_2, but I > >> appreciate the "maintainability" problems you have pointed out, and > >> have added footnotes accordingly. The examples in Learning Python are > >> too spread out in little pieces, and of course, no attention to the > >> issues you are concerned about. If you know of another place I can > >> look for a good all-in-one teaching example, I am interested. > >> > > > >Just for the sake of example, this is one of the programs which I > >always write while learning a language, written in a way I'd use to > >demonstrate OO; all it does is read in a wordlist, then print out > >synonyms for user-inputed words. Handy for crosswords. ;-) > > > > I've posted these examples on our webpage at > http://ece.arizona.edu/~edatools/Python/Examples Let me know if I > should make any changes. These will be very helpful for students to > see alternative styles in programming. > > -- Dave *Shakes head* OK, one change; please change the word synonyms to anagrams in the text of the programs as well. :) When I write a program which can algorithmically detect synonyms it'll be really something... From missive at frontiernet.net Sun May 16 10:54:33 2004 From: missive at frontiernet.net (Lee Harr) Date: Sun, 16 May 2004 14:54:33 GMT Subject: C++ runtime References: <10ab81nkihhj168@corp.supernews.com> Message-ID: On 2004-05-15, kj7ny wrote: > I was at a class for a system I work on and the instructor was talking > about how the system worked with any language that supports C++ Runtime. > > I'm not sure what that means :) > > Does that mean anything to you folks? And... does Python support C++ > Runtime? > http://www.google.com/search?q=python+c%2B%2B+runtime http://www.python.org/sigs/c++-sig/ http://www.boost.org/ From heikowu at ceosg.de Sun May 2 16:50:41 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sun, 2 May 2004 22:50:41 +0200 Subject: PEP 328 update In-Reply-To: <20040502192032.GA27165@panix.com> References: <20040502192032.GA27165@panix.com> Message-ID: <200405022250.41302.heikowu@ceosg.de> Am Sonntag, 2. Mai 2004 21:20 schrieb Aahz: > PEP 328 (``import`` changes) has been updated and is available at > http://www.python.org/peps/pep-0328.html +1 on the PEP... Except maybe that there should be a transition period for the relative import stuff, as (at least) I use it quite extensively... Heiko. From hungjunglu at yahoo.com Sat May 22 12:29:44 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 22 May 2004 09:29:44 -0700 Subject: Running code on module import References: <20040522035701.13396.00001028@mb-m06.aol.com> Message-ID: <8ef9bea6.0405220829.74478fcf@posting.google.com> vbasicboy at aol.com (Grant D. Watson) wrote in message news:<20040522035701.13396.00001028 at mb-m06.aol.com>... > By importing my magic module, I want to have my main() function invoked, > without any "if __name__..." stuff. My C-and-Java trained aesthetic > sensibilities aside, I want to do this so that I can do a bunch of > argv-processing stuff and just pass the results to main() without having to > call anything manually. --------------------- When in Rome, do as the Romans do. I thought your posting had some more substance to it. But now I realize you were simply a barbarian not used to the way of the Romans. But if you really want to do things the barbarian way, here is one way. --------------------- I guess you are a Unix user. However, I'll give you a Windows version, you should be able to easily do the same thing in Unix. Instead of running: python demo.py Create a batch (shell) file called watson.bat, with a line like: python runmain.py %1 %2 %3 %4 %5 %6 and inside your runmain.py: # runmain.py import sys import os.path module_name = os.path.splitext(sys.argv[1])[0] exec 'import %s' % module_name module = sys.modules[module_name] del sys.modules[module_name] # if you want so # tweak the args and set the switches .... # run main() module.main(switches, args) and then run your program using: watson demo.py --option1 --option2 --------------------- Python may have some hooks that would allow you to intercept moments like the end of compilation stage, the start of execution stage, and the exit of normal execution. What you want to do falls into the general category of aspect-oriented programming. So there may be some other tricks. However, why complicate your life? It's much simpler just to do things the way Romans do, when you are in Rome. regards, Hung Jung From moxley at moxleydata.com Wed May 5 13:10:17 2004 From: moxley at moxleydata.com (Moxley Stratton) Date: Wed, 05 May 2004 10:10:17 -0700 Subject: Web programming ... In-Reply-To: References: Message-ID: Sarah Tanembaum wrote: > Is python good for creating Web application? I do like the OOness of Python, > as a newbie, I'm trying to find out if Python has all its necessary > modules/utilities for Web programming just as extensive as, say, PHP or > Ruby(some say that Ruby is not ready for this sort of application and is not > yet mature as Perl, Python, and PHP - is it true?). > > > PHP is a more straight-forward web development language for a newbie because it has been developed and marketed for the web developer in mind. However, this is how I see the difference: PHP provides only one built-in basic approach to web application development: a web server module (or CGI) plus a page template model, similar to asp and jsp, plus the PHP language. Python doesn't provide any web application development model built-in. You either develop Python web applications as CGI scripts-- which isn't very popular because of performance issues-- or you work with a web application model that somebody has developed. Because Python doesn't enforce any particular web development model, developers are free to take any approach that has been developed, or they may develop their own model. This creates the potential for more sophisticated applications, but it almost always makes it more difficult than PHP to create small ones. It also means that as a newbie, you have to spend the time to pick a model to start with. Another thing I'd like to say about the PHP model is that it is very mature and well-known. I'm a PHP developer who has been tinkering around with Python for some time now. I've been researching Webware as a candidate for my primary Python web development model. -- Moxley Stratton From pythongnome at hotmail.com Wed May 12 17:12:22 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 May 2004 21:12:22 GMT Subject: Real-time graphs References: Message-ID: wrote in message news:mailman.463.1084375754.25742.python-list at python.org... > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? > > TIA > Stephen > You could make a Tkinter canvas and set it up to display the graph and update it every second or however long you wish. From asdf at sadf.ca Fri May 21 02:44:07 2004 From: asdf at sadf.ca (asdf as) Date: Fri, 21 May 2004 11:44:07 +0500 Subject: Python compilers? References: Message-ID: <40ADA537.9060105@sadf.ca> Svein Ove Aas wrote: > Is anyone working on a python-to-native compiler? > I'd be interested in taking a look. > > Come to think of it, is anyone working on a sexpr-enabled version of > Python, or anything similar? I really miss my macros whenever I try to > use it... > From __peter__ at web.de Wed May 12 10:17:36 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 May 2004 16:17:36 +0200 Subject: getting the index while iterating through a list References: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> Message-ID: Fernando Rodr?guez wrote: > While iterating through a list I'd like to know not just the current > element, but also its index. Is there a better way than this: > > i = 0 > newList = [] > for element in aList: > newList.append((i, element)) > i += 1 > > Is there a more elegant way of doing this with for? And with map()? >>> aList = ["alpha", "beta", "gamma"] >>> list(enumerate(aList)) [(0, 'alpha'), (1, 'beta'), (2, 'gamma')] >>> Peter From loic at fejoz.net Thu May 6 10:35:19 2004 From: loic at fejoz.net (Yermat) Date: Thu, 06 May 2004 16:35:19 +0200 Subject: Private identifiers - naming In-Reply-To: <930ba99a.0405060600.17e076bc@posting.google.com> References: <930ba99a.0405060600.17e076bc@posting.google.com> Message-ID: Sridhar R wrote: > In python, to hide (from direct access) identifiers from outsiders > (not current module), we usually prefix the variables with '__'. > > But this is usually _difficult_ to read. Imagine a module (which is a > common one) containing more private variables than public variables. > > How cryptic it would be to see text with lot of __ in front of them !! > > Any thoughts? Do we really need private variable ? -- Yermat From mark at hahnca.com Mon May 24 14:19:16 2004 From: mark at hahnca.com (Mark Hahn) Date: Mon, 24 May 2004 11:19:16 -0700 Subject: Prothon vs. Python integers In-Reply-To: <40B237B2.4020608@prescod.net> Message-ID: <000d01c441bb$9fc8c000$0b01a8c0@mark> > From: Paul Prescod > I think that in this case, Python is demonstrably better than Prothon. > > C:\temp\prothon\Prothon>python > > >>> print 2**65 > 36893488147419103232 > > >>> print 2**65 == (2**65 + 1) > False > > > C:\temp\prothon\Prothon>prothon > >>> print 2**65 == (2**65 + 1) > True > > If Prothon is a language designed for the next ten years then > it should > be tuned for correctness and ease of use, not for limitations > of today's > hardware. I'm sure this isn't the only place Python is better. Prothon has the long integer support in the parser if anyone wants to take the trouble to put the long object code in. I did nothing to preclude it. I just didn't see any need for it myself and didn't take the trouble to put it in. Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely once you get to 3.7e19 you are in floating point territory. I can't imagine counting anything up to 10**19. From rschroev_nospam_ml at fastmail.fm Sun May 2 06:38:36 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 02 May 2004 10:38:36 GMT Subject: Efficient string concatenation methods In-Reply-To: References: Message-ID: Oliver Crow wrote: > I'd be happy to hear if anyone else has done similar tests and if > there are any other good candidate methods that I missed. I'd like to try out another variant, but I'm unable to run your script... Where does that timing module come from? I can't find it anywhere. The method I propose is simply def method7(): return ''.join(map(str, xrange(loop_count))) I ran my own little test and it seems to be faster than method6, but I'd like to run it in your script for more reliable results. Also, I haven't done any memory measurement, only a timing. -- "Codito ergo sum" Roel Schroeven From imbosol at aerojockey.com Wed May 19 17:54:48 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 19 May 2004 14:54:48 -0700 Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> Message-ID: <60dfb6f6.0405191354.2c04a105@posting.google.com> Paul Rubin wrote in message news:<7xad0581ax.fsf at ruckus.brouhaha.com>... > Carl Banks writes: > > I don't follow you. In what way is Python dynamic that Lisp isn't? > > > >>> class foo: > ... def bar(self, x): > ... return x*x > ... > >>> a = foo() > >>> a.bar(3) > 9 > >>> a.bar = lambda x: x*x*x > >>> a.bar(3) > 27 > >>> Well, come on, of course there's going to be some things here and there you can do in one and not the other. In wat is Python dynamic that Lisp isn't to such an extent that it would cripple any attempts to compile it? -- CARL BANKS From E.A.M.Huijbers at REMOVEstudent.tue.nl Fri May 21 11:21:31 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Fri, 21 May 2004 17:21:31 +0200 Subject: Deleting Directories In-Reply-To: References: Message-ID: Laura McCord wrote: > This is probably a very basic question but I started learning python. I > am almost done writing my delete directory script but I am at a stand > still right now. > I want to delete folders in my "/var/www/html/da" directory that are > over 1 day old. > > But, when I find the folder a simple rmdir() command does not work > because the directory is not empty. What else do I need to do to delete > a directory that contains content? Assuming you already figured out how to check the directories' timestamps, shutil.rmtree() will do what you want. From http Wed May 19 00:53:58 2004 From: http (Paul Rubin) Date: 18 May 2004 21:53:58 -0700 Subject: Python compilers? References: Message-ID: <7xad0581ax.fsf@ruckus.brouhaha.com> Carl Banks writes: > I don't follow you. In what way is Python dynamic that Lisp isn't? >>> class foo: ... def bar(self, x): ... return x*x ... >>> a = foo() >>> a.bar(3) 9 >>> a.bar = lambda x: x*x*x >>> a.bar(3) 27 >>> From Miklos at nowhere.hu Sat May 22 03:59:25 2004 From: Miklos at nowhere.hu (Miklos) Date: Sat, 22 May 2004 09:59:25 +0200 Subject: module looping References: Message-ID: David Eppstein wrote: > In article , > hwlgw at hotmail.com (Will Stuyvesant) wrote: > >> How to loop without using a looping construct; or a generator >> without "yield". > > Seems like it will quickly hit the recursion limit... > Yep, that's right. But it's still an interesting* feat. :-) * to me, at least Best, Pm -- -- Pm From grante at visi.com Wed May 26 11:32:11 2004 From: grante at visi.com (Grant Edwards) Date: 26 May 2004 15:32:11 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: On 2004-05-26, SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be > created, but Python programmers regularly use a class when > there will only be one instance. What is the benefit of this? 1) Because people are notoriously bad and predicting the future. Their guesses at what "will be" are often wrong. If you use a class, then you can add a second instance later when you figure out what the customer really wanted. 2) I find it often helps me think through the problem and arrive at a more structured, easily maintained solution compared to a bunch of random functions. > It has a disadvantage of a whole lot of "self." being required > everywhere, making the code less readable. In some cases (particulary mathematical computations), the self's can reduce readability. A few local variables can fix that. > Also, since a strength of Python is rapid application > development, it slows one down to have to put in all those > self.'s. I've never seen any project where the speed of development was limited by typing speed. > The code seems much cleaner to me without classes that have > only one instance. Until the requirements change (or are actually discovered), and you need more than one instance. -- Grant Edwards grante Yow! If I felt any more at SOPHISTICATED I would DIE visi.com of EMBARRASSMENT! From tjreedy at udel.edu Fri May 21 18:35:03 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 18:35:03 -0400 Subject: terminological obscurity References: <4Zsrc.528320$Pk3.64397@pd7tw1no> <10asqll7hiq9l48@news.supernews.com> Message-ID: "John Roth" wrote in message news:10asqll7hiq9l48 at news.supernews.com... > This is one of the longstanding issues. Guido intended lists > for conceptually homogeneous cases: that is, part of a list > is conceptually similar to the entire list. > > Tuples are intended for places where you want to simply > gather up a bunch of objects into one object for convenience > in passing them around. Assume, for example, that I've got > a tuple that includes a name, address, postal code, telephone > number, part number and order quantity. Half of that tuple > is not conceptually the same as the entire tuple. That's what > is meant by inhomogenaity. The argument against tuple.count() and tuple.index() could also be used against tuple slicing, but I won't say that too loudly. > There are a number of places where this gets sticky, > and other people regard other properties as more important. For me, mutability is pragmatically the most important. I would prefer that .count, .index, and .rindex were identical across sequences. > It is, however, Guido's language. He's the Benevolant Dictator > for Life, so his intention is the official intention. But anyone is free to implement private intentions with count and index functions. The itertools make it easy to write efficient and more general functions which count or locate items produced by *any* iterable, not just lists, that match any criterion, not just equality to a particular value. So the addition of two specialized methods to one type is not currently an issue to me. Terry J. Reedy From jgardner at jonathangardner.net Mon May 24 11:24:06 2004 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 24 May 2004 08:24:06 -0700 Subject: nested grouping with regular expressions References: <2164532c.0405232251.3877859a@posting.google.com> Message-ID: <6cc20cea.0405240724.59c1c49b@posting.google.com> "Fredrik Lundh" wrote in message news:... > "ds2000" wrote: > > > Unfortunately, re.match("<(..)*>", string).groups() will return only > > the groups correspond to the last occurence of (regex) > > > > Is it possible to get a more tree-like group match (i.e. or at least a > > list which will contain the groups of each regex occurence). > > use re.findall > > (you may have to use multiple REs; a re.search to find the entire > group, a re.findall/finditer to split it up). > You'll probably end up not using regular expressions after all. XML parsers work much better for parsing XML than regexes. In general, when a regex stops becoming the obvious solution, start using a parser. ;-) From fgeiger at datec.at Mon May 3 02:00:49 2004 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 3 May 2004 08:00:49 +0200 Subject: [PythonWin32] TLB's for mere mortals? Message-ID: Hello all, I've used Python COM servers from a VB6-app successfuly. I'd now like to do this from .NET (C#). I could use late binding, but that code really looks *ugly* and cumbersome compared to the one in VB6. If I could use early binding things would be easier. But then I need a type library. How do I write such a beast for my Python scripts? I found several posts in the net and a script named typelibutil.py was mentioned (http://mailman.pythonpros.com/pipermail/pycom-dev/2002q1/000334.html), which doesn't seem to exist anymore. Other posts (e.g. http://mailman.pythonpros.com/pipermail/pycom-dev/1999q3/000163.html) showed some code. Do I really need to dive into all that? Do I need to write such code by hand? PythonNET came to my mind, but if I've understood them right, it is for using .NET classes from Python and not the other way round. And IronPython (looks very promising to me) is not yet available. Any hint is welcome. Many thanks in advance Franz GEIGER From grante at visi.com Wed May 19 00:59:39 2004 From: grante at visi.com (Grant Edwards) Date: 19 May 2004 04:59:39 GMT Subject: alternatives to making blocks like { } or other ?? References: Message-ID: On 2004-05-18, Paul McGuire wrote: >>> could i use something else like >>> >>> def sth(x): >>> { >>> return x >>> } > ... and no religious wars on where the braces are supposed to > go, HOORAY!!! But as religious wars go, the great Python "tab" debate ranks right up there. > And I'll second Larry's comment - it takes about 10-20 minutes > to get used to, but then you just focus on indentation, and it > seems *very* natural - liberating, even! Especially if you've got an editor with a "python mode". -- Grant Edwards grante Yow! I guess we can live at on his POT FARM in HADES!! visi.com From fredrik at pythonware.com Tue May 25 06:08:13 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 12:08:13 +0200 Subject: in operator for strings References: Message-ID: "Moosebumps" wrote: > Wouldn't it be cool if you could do this? > > ('hello','test') in 'blah blah hello blah test': > > and it would say if all elements of the list are in the string? well, if you're asking me, I'd say that what's really cool is that you can do not only findall(('hello', 'test'), 'blah blah hello blah test') but also find_any(('hello', 'test'), 'blah blah hello blah test') find_in_order(('hello', 'test'), 'blah blah hello blah test') find_in_any_case(('hello', 'test'), 'blah blah hello blah test') starts_and_ends_with(('hello', 'test'), 'blah blah hello blah test') find_only_on_fridays(('hello', 'test'), 'blah blah hello blah test') etc. without having to change the language, or any of its implementations. From dpharris76 at msn.com Fri May 28 01:19:12 2004 From: dpharris76 at msn.com (Dave Harris) Date: Fri, 28 May 2004 00:19:12 -0500 Subject: Canvas polygon coords() using list comprehension Message-ID: I have written a reasonably clean way to perform coordinate transformations on a polygon, but Tkinter Canvas is not being particularly cooperative. The following program has been distilled down to a minimum and generates a traceback (see below) when it runs. It appears that the create_polygon() method is more versatile than the coords() method. Could someone can suggest a way to have the list comprehension not generate tuples, that would probably create a coordinate list acceptable to coords()? Thanks, Dave Harris # cantest.py - canvas test program from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() c = Canvas(frame, width=300, height=300) c.pack() outline1 = [(100, 0), (200, 50), (150, 150)] p1 = c.create_polygon(outline1, fill='', outline='black') p2 = c.create_polygon(outline1, fill='', outline='red') outline2 = [(x+10, y+20) for (x, y) in outline1] c.coords(p2, outline2) root = Tk() app = App(root) root.mainloop() Traceback (most recent call last): File "cantest.py", line 24, in ? app = App(root) File "cantest.py", line 20, in __init__ c.coords(p2, outline2) File "C:\PYTHON23\Lib\lib-tk\Tkinter.py", line 2039, in coords self.tk.splitlist( _tkinter.TclError: bad screen distance "170)]" From seefeld at sympatico.ca Tue May 18 13:05:24 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 18 May 2004 13:05:24 -0400 Subject: error converting list to tuple In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Stefan Seefeld" wrote in message >>(I call this code from within a C++ extension module), > > > You should have said that in the beginning since that is a whole different > ball game: extension modules in C are not Python. ok, let me be more specific: From my C++ code I call a method of a python object which happens to do the tuple->list conversion. And as Python is implemented in C, I thought it didn't matter, it's the same underlying API / object model, just different syntax ;-) > It is easy to mess up in C ;-). You are most likely to get an answer (from > another C extension writer) if you post a short as possible code snippet > that exhibits the error, and the actual and complete error message. That's (part of) the problem: I can't reproduce this in isolation, so I wanted to know how I could debug this. What I do is calling 'PyObject_Str' on the python object. That object has its '__str__' method implemented in a way that involves said tuple->list conversion, so the call raises an exception and the call returns 0. Thanks, Stefan From elainejackson7355 at home.com Fri May 21 15:42:56 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 21 May 2004 19:42:56 GMT Subject: terminological obscurity References: Message-ID: <4Zsrc.528320$Pk3.64397@pd7tw1no> "Michael Chermside" wrote in message news:mailman.145.1085158045.6949.python-list at python.org... | Elaine Jackson writes: | > All tuple methods are also list methods, and most list methods are also tuple | > methods; among those that are NOT also tuple methods, there are exactly two | > ('count' and 'index') that do not involve mutation. Is there any special | reason | > why they AREN'T also tuple methods? | | Yes. Both make sense only if you consider a tuple as a homogeneous | sequence of items, and that's not what Guido intended it to be | used for. #################################################### This invites the question: What DID he intend it to be used for? Also, like the other respondent, I don't understand what homogeneity has to do with it. #################################################### | | > A question about terminology ('namespace'): | > | > >>> prince=tuple() | > >>> king=[prince] | > >>> del prince | > | > At this point, does the object formerly known as prince belong to the | > namespace implemented by globals()? More generally, is there a | > terminological way to distinguish between (1) a function from a set | > of names into a set of objects, and (2) the aforementioned set of | > objects? | | After executing your code, there exist two objects, one is a tuple | and the other is a list. The global namespace contains one binding: | the name "king" is bound to the aforementioned list. The tuple is | not referred to directly by any name in the global namespace but it | will not be garbage collected yet because it is referenced by the | list and cannot be freed until the list itself is freed. | | Whether this answers your questions I'm not sure... the questions | didn't make sense to me. ############################################################# I'm trying to find out (for a start) whether the term 'global namespace' refers to (1) the set of bindings, or (2) the set of bindings, together with any objects that currently exist but do not have "real" names. ############################################################# | | > Is there a handy noun that refers to sameness of identity in the same | > way that 'equality' refers to sameness of value? ('Identicalness' is | > pretty clumsy, and 'identity' is confusing, since it already has a | > meaning that is closely related but needs to be kept distinct.) | | I've usually heard "identity" used. I don't know of any other synonynms | to use here. | | > Suppose X is a container that contains n items (incidentally, is 'items' | > the right term?) and i in an integer with 0<=i<=n. Does " X[i] " count | > as a 'name'? | | "items" is a perfectly good term for the things in a list. In common | usage, "X[i]" is not a name. It is, however, an "L-value" -- a slightly | related term which (unlike "name") has a fairly precise definition. ############################################################# Do you know a good place to find a discussion of matters like this? BTW, thanks for responding. Peace ############################################################# From ville at spammers.com Sat May 15 17:31:00 2004 From: ville at spammers.com (Ville Vainio) Date: 16 May 2004 00:31:00 +0300 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> Message-ID: >>>>> "Michele" == Michele Simionato writes: Michele> of learning Zope TAL/TALES/METAL, which I do not like Michele> that much; I would rather prefer to generate HTML pages Michele> with Lisp macros and use real s-expressions instead of Michele> XML/HTML, but I can't :-( What would you do with macros? The resulting s-exprs would still need to be evaluated to get the html, so the performace wouldn't be better... And you can use s-exprs in python too: page = [ [ head , [ title, "my page"] ], [ body, [ heading, "welcome to my page"], [ para , "paragraph1 blah blah"] [ para , "paragraph2 more blah blah "]] ] Further elaboration on the idea at http://www.students.tut.fi/~vainio24/pysexpr/ -- Ville Vainio http://tinyurl.com/2prnb From madsurfer2000 at hotmail.com Sun May 2 06:38:57 2004 From: madsurfer2000 at hotmail.com (-) Date: 2 May 2004 03:38:57 -0700 Subject: Looking at the next element in a for loop Message-ID: Hi, If I have a simple for loop like this: for a in b: print a Is there a way I can get the next element in the loop? Something like this: for a in b: if a == 1: print From davidf at sjsoft.com Wed May 26 07:21:47 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 26 May 2004 13:21:47 +0200 Subject: supermethod shortcut Message-ID: Hi I was recently thinking about the awkwardness I find in using the super method to call a superclass's function. The majority of the time I use super in the following way: class Y(X): def some_method(self, arg1, arg2): do_something(arg1) arg2 += 1 super(Y, self).some_method(arg1, arg2) The whole super(Y, self).some_method seems an awkward way to say "call the superclass's version of this function". So I defined a function that looks up the calling function name in the stack frame and calls super on the self attribute, and returns the function name: import sys def supermethod(currentclass): callingframe = sys._getframe().f_back functionname = callingframe.f_code.co_name self = callingframe.f_locals["self"] superobject = super(currentclass, self) return getattr(superobject, functionname) This then reduces the above to supermethod(Y)(arg1, arg2) Of course explicit is better than implicit and so maybe not looking up self is better: import sys def supermethod(currentclass, self): callingframe = sys._getframe().f_back functionname = callingframe.f_code.co_name superobject = super(currentclass, self) return getattr(superobject, functionname) This still means you call supermethod(Y, self)(arg1, arg2) instead of super(Y, self).functionname(arg1, arg2) Anyway I just wondered if others would find this interesting / useful / material for a flame war :-) David From sridharinfinity at yahoo.com Fri May 28 10:17:40 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 28 May 2004 07:17:40 -0700 Subject: Non-programmer needs help with PyGTK-2.0.0 Message-ID: <930ba99a.0405280617.efc1e21@posting.google.com> You should do ./configure --prefix=/usr bcoz, python was installed on /usr (not /usr/local) From __peter__ at web.de Fri May 21 04:45:26 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2004 10:45:26 +0200 Subject: unicode regex example: trouble References: Message-ID: marek wrote: > trying this example to make print MatchObject reference. Fails (prints > None). Does anybody know where I am wrong? > > # -*- coding: cp1251 -*- > > import re > > # pattern in Ukrainian ('привіт') > p = '\377\376?\004@\0048\0042\004V\004B\004' > > # data (pattern is in the middle of the string) > d = '\377\376t\000e\000s\000t\000?\004@\0048\0042\004V\004B\004t\000t\000' > > re_test = re.compile(p, re.UNICODE) > > print re_test.search(d, re.UNICODE) What you have here are funny 8 bit characters, not unicode: >>>>>> print p, d ???@82VB ??test?@82VBtt I guess the encoding is utf-16, therefore: >>> du = d.decode("utf-16") >>> pu = p.decode("utf-16") >>> r = re.compile(pu) >>> m = r.search(du) >>> m <_sre.SRE_Match object at 0x40392090> >>> print m.group(0).encode("utf-16") ???@82VB Works as expected :-) Here's what the docs say about the unicode flag: UNICODE Make \w, \W, \b, and \B dependent on the Unicode character properties database. New in version 2.0. You may or may not need that when you refine your regexp. Peter From dmq at gain.com Sat May 22 13:46:31 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 22 May 2004 10:46:31 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> Message-ID: <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> On Thu, 13 May 2004 10:56:58 -0400, "Terry Reedy" wrote: >"Antoon Pardon" wrote in message >news:slrnca6d58.1i9.apardon at trout.vub.ac.be... >> One could argue that all forms of methods and functions are unified. >> It is just that python does some magic so that the method you >> access from an object is not the actual function but the curried >> function with the object. > >My view is similar: in Python, a method is a dressed up (wrapped) function. >'Unification of methods and functions' reads to me like 'unification of >dressed-up bodies and naked bodies'. What would that mean? One thing I >like about Python is that there is only function-body syntax and not a >separate, slightly different method-body syntax. To me, having only one >type of code body *is* unification. So it is hard for me to see what is >being proposed. Introducing a syntax like '.var' that would only be >meaningful in a method and not a function would be dis-unification. There seems to be a lot of misunderstanding on the question of "magic" in Python's method binding syntax vs the proposed syntax. I see students having difficulty learning the current syntax. Python experts say its real easy, and point to the explicit "self" as an advantage of the current syntax, vs the "magic" of setting a global __self__ variable. All of this is missing the problem. If Python were consistent, and *always* used a special first argument, there wouldn't be a problem. The magic first argument would be no more difficult than magically setting a global variable. The problem is that some methods require a magic first argument, and others require that it *not* be there. In one case you call cat1.talk() and in another it is Cat.talk(cat1). I know this is not terribly difficult to understand -- one is a bound method, the other unbound. Still it is a problem for beginners, and it leads to unecessary complexities like static methods. The recent discussion on "Method binding confusion" 5/2/04 shows that even experts can get confused. Here is the example, reduced to its simplest terms: import math def mypow(x, y): return x**y class MathA: pow = math.pow class MathB: pow = mypow ma = MathA() mb = MathB() print ma.pow(2,4) #=> 16.0 print mb.pow(2,4) #=> # TypeError: mypow() takes exactly 2 arguments (3 given) How would you explain this to non-CIS students in a class on circuit design, where there is very little time to discuss programming? -- Dave From dieter at handshake.de Sun May 2 13:47:32 2004 From: dieter at handshake.de (Dieter Maurer) Date: 02 May 2004 19:47:32 +0200 Subject: _socket module missing solaris 7 build python 2.3.3 References: <409275CC.1D6D080@csr.utexas.edu> <4092D7CE.1050605@v.loewis.de> Message-ID: "Martin v. L?wis" writes on Sat, 01 May 2004 00:48:46 +0200: > Stephen Williams wrote: > > anyone out there know of a way around this? compiler flags or > > something? > > Around what? That sunfreeware does not ship the socket module? I have had similar problems: The SUN header files for Solaris 7 did not define "INET V6" related macros. Therefore, the compilation of "_socket.c" failed. I modified the Python sources slightly to define the missing macros. Dieter From goodger at python.org Sun May 2 13:33:41 2004 From: goodger at python.org (David Goodger) Date: Sun, 02 May 2004 13:33:41 -0400 Subject: [OT] does the charset lie? In-Reply-To: <16533.12062.56470.647993@montanaro.dyndns.org> References: <16533.8123.5800.539196@montanaro.dyndns.org> <40952451.3020106@python.org> <16533.12062.56470.647993@montanaro.dyndns.org> Message-ID: <409530F5.5040306@python.org> Skip Montanaro wrote: > OTOH, this means if I need the raw > content of the page (after expanding any entities), I need to so something > like (assuming the raw bytes are already in data): > > data = unicode(data, "iso-8859-1").encode("utf-8") > data = map_entities_to_utf_8(data) > data = unicode(data, "utf-8") Or, even simpler, skip the intermediate step: data = unicode(data, "iso-8859-1") data = map_entities_to_unicode(data) map_entities_to_unicode() could use htmlentitydefs.name2codepoint from the stdlib. This must have already been done somewhere. -- David Goodger From jepler at unpythonic.net Mon May 17 21:14:14 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 17 May 2004 20:14:14 -0500 Subject: Timer events In-Reply-To: <93dqc.15615$gr.1409242@attbi_s52> References: <93dqc.15615$gr.1409242@attbi_s52> Message-ID: <20040518011413.GA8092@unpythonic.net> umm, why not convert the given time into seconds, and then call sleep once? def get_time(): # taken from EAS' code print "Enter the hours, minutes, and seconds you want the computer to wait." while hou < 0 or hou > 23: hou = input("Hours: ") # All the usual warnings about input() apply while min < 0 or min > 59: min = input("Minutes: ") while sec < 0 or sec > 59: sec = input("Seconds: ") # my innovation return sec + 60 * min + 60 * 60 * hou time.sleep(get_time()) print "\a\a\a" exit = raw_input("\nPress enter to exit.") From winexpert at hotmail.com Tue May 25 09:06:33 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 25 May 2004 13:06:33 +0000 Subject: hard disk serial Message-ID: Hi, What you want to use is the win32api.GetVolumeInformation. API. Its part of win32. To get to it you need to import it.... import win32api Then I believe you would use win32api.GetVolumeInformation ( ... etc) The actual api is documented here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/getvolumeinformation.asp (I'm learning python myself but know the windows sdk pretty well) Good Luck David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: "Lea Informatique" >To: "David Stockwell" >Subject: Re: hard disk serial >Date: Tue, 25 May 2004 14:55:23 +0200 > >I'm targeting win32 >for the moment it's the only OS we should use > >did you get an idea ? > > >----- Original Message ----- >From: "David Stockwell" >To: ; >Sent: Tuesday, May 25, 2004 2:51 PM >Subject: RE: hard disk serial > > > > Hi, > > > > What OS are you targeting? Or are you looking for an OS independent > > solution? > > > > David > > ------- > > Cell: http://cellphone.duneram.com/index.html > > Cam: http://www.duneram.com/cam/index.html > > Tax: http://www.duneram.com/index.html > > > > > > > > > > >From: > > >To: python-list at python.org > > >Subject: hard disk serial > > >Date: Tue, 25 May 2004 14:44:49 +0200 > > > > > >Hi every one > > >I try to get hard disk serial number > > >how can i do this ? > > > > > >-> THANK'S A LOT > > > > > > > > >-- > > >http://mail.python.org/mailman/listinfo/python-list > > > > _________________________________________________________________ > > Best Restaurant Giveaway Ever! Vote for your favorites for a chance to >win > > $1 million! http://local.msn.com/special/giveaway.asp > > > > > > > > _________________________________________________________________ Get 200+ ad-free, high-fidelity stations and LIVE Major League Baseball Gameday Audio! http://radio.msn.click-url.com/go/onm00200491ave/direct/01/ From sholden at holdenweb.com Tue May 25 20:01:46 2004 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 May 2004 20:01:46 -0400 Subject: why i In-Reply-To: References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: Dennis Lee Bieber wrote: > On 25 May 2004 16:35:29 +0950, Ben Finney > declaimed the > following in comp.lang.python: > > >>The usage of "i" was promulgated by the FORTRAN language, which allowed >>only single-letter variable names (and was all upper case, too, so it > > > That must have been a really old version of FORTRAN -- all > versions I've encountered allowed for, at least, 6 significant > characters in variable names. (This goes back to F-IV/F-66). BASIC was > limited to one or two characters. > [...] I think the original author was confusing Fortran and BASIC. I used Fortran II back in 1968, and that definitely allowed six-character names. regards Steve From winexpert at hotmail.com Thu May 27 11:19:26 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 15:19:26 +0000 Subject: Best way to enumerate something in python Message-ID: All I can say is WOW! It took me a bit to figure out what you were doing but I think I see it. Let me see if I get this right: First declare a string with the 'base name' of all my columns in it. declare my dictionary (for later sql statement grabs) and make it empty. I think create a list of field names and enter a loop in the loop: create a variable using the basename and append a "_COL" to form an easy lookup constant. and assign that new variable with the loop index. still in the loop, add a dictionary entry mapping the string to the var name Its pretty impressive.... Guess I still have a lot to learn with python.... David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: Peter Hansen >To: python-list at python.org >Subject: Re: Best way to enumerate something in python >Date: Thu, 27 May 2004 10:40:05 -0400 > >David Stockwell wrote: > >>FWIW this is what I'm going to do for enumerated types in python. Its not >>perfect but it will make it fairly easy to get at column names so I can >>build SQL statements on the fly and still have fairly easy to maintain >>code >> >>#setup stuff >>NAME_COL, ADDRESS_COL, CITY_COL, ZIPCODE_COL, \ >>STATE_COL, COUNTRY_COL, SS_COL, CAT_COL, \ >>DATE_COL, SALARY_COL = range(10) >> >>mycol = { >> NAME_COL: " NAME ", ADDRESS_COL: " ADDRESS ", >> CITY_COL: " CITY ", ZIPCODE_COL: " ZIPCODE ", >> STATE_COL:" STATE ", COUNTRY_COL: " COUNTRY ", >> SS_COL: " SS ", CAT_COL: " CAT ", >> DATE_COL: " DATE ", SALARY_COL: " SALARY " } >># Use these for indexing by column name > >Any time you see a pattern of repetition like this, you can >make improvements, at least with Python if not some other >languages. If nothing else, this will generally vastly improve >maintainability, and often readability as well. > > > >>> cols = 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' > >>> mycol = {} > >>> for i,col in enumerate(cols.split()): >... globals()[col + '_COL'] = i >... mycol[i] = ' %s ' % col >... > >>> dir() >['ADDRESS_COL', 'CAT_COL', 'CITY_COL', 'COUNTRY_COL', 'DATE_COL', >'NAME_COL', 'SALARY_COL', 'SS_COL', 'STATE_COL', 'ZIPCODE_COL', >'__builtins__', '__doc__', '__name__', 'col', 'cols', 'enum', 'i', 'mycol'] > >>> mycol[CITY_COL] >' CITY ' > >-Peter >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From peter at engcorp.com Wed May 26 09:49:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 09:49:09 -0400 Subject: Bad interpreter In-Reply-To: References: Message-ID: Peter Hansen wrote: > Benjamin Niemann wrote: > >> Peter Hansen wrote: >> >>> Remove the hidden CR character which you got at the end of the >>> lines by moving the file to a Windows system and editing it. ;-) >>> >>> This one is pretty tricky to figure out the first few times... >> >> Should be the other way 'round: If you edit the file under Windows >> (e.g. with Notepad), (invisible) CRs are added. > > We're saying the same thing. Ah, I see you understood me to be saying that "by moving the file to a Windows system you can remove the CR characters". My intended meaning was "you got the CR characters by moving the file to a Windows system", and I wasn't giving him any idea how to remove them. :-) Confusion solved... -Peter From dmq at gain.com Mon May 24 17:37:06 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 14:37:06 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> Message-ID: On Mon, 24 May 2004 14:39:11 +1200, Greg Ewing wrote: >David MacQuigg wrote: > >> Nobody seems to understand that lambda functions, static methods, etc. >> are clutter. > >On the contrary, lambda has long been regarded as a wart >for various reasons. The best way to fix it is probably >to just drop it altogether. Nothing essential would be >lost. If "lambda functions" were nothing but functions with the name left off, they would serve their current purpose, and they would not be such a problem that there is talk of actually taking them *out* of the language. They aren't essential, but they do serve a purpose which some feel is important. >We don't see static methods as clutter, because for the >most part we don't see them (i.e. we don't normally use >them). It would be no great loss if they were dropped, >too. I would see it as a loss. The next best alternative is to move the static method outside of the class, and that puts an arbitrary restriction on how I can structure my programs. If the person writing the program feels that the function belongs in the class, let's not say it can't be done because either a) The syntax doesn't allow it. or b) We assume he is wrong in thinking his function belongs inside his class. My perspective may be different, because I have not yet absorbed the Python traditions, and I don't have any instictive avoidance of static methods. >In neither case is it necessary to fundamentally >redesign the language to fix these, even if >they are regarded as problems. The proposed change are minimal, and could be done in the next non-backward compatible upgrade (Python 3?). Unlike Prothon, I am very concerned about the ability to automatically migrate existing Python programs to the new syntax. I believe that is possible with the proposed syntax. I believe the changes will make it easier for beginners to learn Python OOP, and at worst, be a minor and temporary annoyance for experts. I would expect learning the simpler syntax would take an expert two hours at the most. -- Dave From j_mckitrick at bigfoot.com Thu May 13 22:15:19 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 13 May 2004 19:15:19 -0700 Subject: Does ANYONE use Pmw and BLT on Linux/BSD? Message-ID: I am having NO luck getting Pmw to find BLT, and I have to get a realtime graph working soon. What is the trick to getting this to work? From mwh at python.net Thu May 20 06:42:35 2004 From: mwh at python.net (Michael Hudson) Date: Thu, 20 May 2004 10:42:35 GMT Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> <5155aad2.0405200230.1899e3be@posting.google.com> Message-ID: kveretennicov at yahoo.com (Konstantin Veretennicov) writes: > Carl Banks wrote in message news:<38Yqc.166$eO6.128 at fe2.columbus.rr.com>... > > > > There's more like it, e.g. the existence of the > > > locals() dictionary and the ability to modify it. > > > > New feature? I didn't think modifying the dict returned by locals > > affected the variables. > > > > Evidence of crime :) > > Python 2.3.2 > >>> x > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'x' is not defined > >>> locals()['x'] = 1 > >>> x > 1 > > > Not to mention stack frame magic available via inspect.*... Well, fortunately *this* level of gimmickery is already somewhat forbidden... Cheers, mwh -- > so python will fork if activestate starts polluting it? I find it more relevant to speculate on whether Python would fork if the merpeople start invading our cities riding on the backs of giant king crabs. -- Brian Quinlan, comp.lang.python From simoninusa2001 at yahoo.co.uk Sun May 2 18:26:11 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 2 May 2004 15:26:11 -0700 Subject: Newbie: Create Executable from single script file References: <39cbe663.0405010157.781b8610@posting.google.com> Message-ID: <30260531.0405021426.7b0e2c94@posting.google.com> If you just want a single file executable then look at McMillan Installer for www.mcmillan-inc.com (mirrored at www.the-jedi.co.uk/comps/downloads) Otherwise stick with py2exe and create a Setup.exe using InnoSetup. From mark at prothon.org Tue May 25 14:26:10 2004 From: mark at prothon.org (Mark Hahn) Date: Tue, 25 May 2004 11:26:10 -0700 Subject: Prothon vs. Python integers References: <40b3111d$0$7727$afc38c87@news.easynet.co.uk> Message-ID: <6dMsc.17883$bF3.11520@fed1read01> "Peter Hickman" wrote > > Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely > > once you get to 3.7e19 you are in floating point territory. I can't imagine > > counting anything up to 10**19. > > Except all those sad people doing that thing called 'maths'. > > Sorry but one of my requirements for a language is that is can handle integers of any size quickly and easily (and a good integer square root would be nice). However I always seem to > end up coding with C and GMP. I said in this thread at noon yesterday that I was wrong and that I will implement longs. From donn at u.washington.edu Thu May 6 18:04:15 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 06 May 2004 15:04:15 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: In article <997a06e0.0405061128.6768676d at posting.google.com>, pugnatio2 at yahoo.com wrote: > What's the standard way to implement polymorphic behavior in a python > method, given that method arguments can't declare their types as > they're being passed in, and method definitions don't have signatures? > > For instance, if I wanted to write a method that auto-detected whether > it was being passed a string or a tuple/list, how would I do so > without using type() to identify the parameter's type? Using type() is > deprecated in the documentation I've read. type() does what you want to do. It's not so much that the function is deprecated, rather the idea behind wanting to use it in the first place. A string is a kind of sequence, as are lists and tuples. If you really want to deal with a string as a variation on that theme, but there are differences that you have to take into account, then maybe someone can suggest an approach if you can describe the issue. On the other hand, if you want to support a string as an single value instead of a list or tuple of values, then you're not really talking about polymorphism here anyway. When a function decides to support various unrelated types for a particular parameter, I don't know what you call that, but it isn't polymorphism in any useful sense. It has been done, it's up to you whether you want to do it, but personally I think it's bad news because it's confusing and difficult to do right. A misguided convenience. Polymorphism is about a function supporting a range of objects that conform to a certain specification (in Python that's an implicit specification.) Like a function written with a file object in mind can also support a cStringIO object, automatically. Obviously, type() is the wrong direction in this context, because that "automatically" part is important. But type() is also difficult to do right, even if you don't care about polymorphism, because polymorphism is there whether you want it or not. What if you have been checking for StringType instead of list or tuple, and someone passes a Unicode object? Is that a string? Is it StringType? You're not ready for that if you haven't explicitly accounted for it, and there's lots of Python code still in use that was written before there was such a thing as a Unicode object. Donn Cave, donn at u.washington.edu From apardon at forel.vub.ac.be Tue May 11 07:12:35 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 May 2004 11:12:35 GMT Subject: Unification of Methods and Functions References: Message-ID: Op 2004-05-11, Delaney, Timothy C (Timothy) schreef : > Antoon Pardon wrote: > >> I'm a bit sick of this argument. There is a lot om implicity >> going on in python. if obj belongs to cls then obj.method() >> is syntactic sugar for cls.method(obj). That looks like >> a big implicite way to handle things in python. > > Actually, they're not strictly the same. The instance knows which class > it is an instance of - that's why the syntactic sugar can work. > > What you've stated is saying: > > class C: > def f (self): > pass > > c = C() > > then c.f() is identical to calling C.f(c) > > Now, in the above case that's correct. However, when subclasses get > introduced that goes out the door. > > class D (C): > def f (self): > pass > > d = D() > > Now, d.f() is *not* identical to C.f(d). Instead it should be D.f(d). > Without knowing the class that d is an instance of, it is not possible > to call the correct method without the syntactic sugar. I don't see how this contradicts what I want to say. In both case you have something of the form obj = cls() And in both obj.method() is equivallent to cls.method(obj) > d.f() is closer to syntactic sugar for d.__class__.f(d). However, even > that's not strictly correct, because c.f and d.f are bound methods - > they know which instance they are bound to without any further reference > to that instance. > > Yes - there is a lot hidden here - but what is hidden is purely > implementation details. That it is an implementation detail doesn't contradict that it is implicit. -- Antoon Pardon From dpharris76 at msn.com Wed May 26 10:34:31 2004 From: dpharris76 at msn.com (Dave Harris) Date: Wed, 26 May 2004 14:34:31 +0000 Subject: Why a class when there will only be one instance? Message-ID: Peter Maas wrote: > >>SeeBelow at SeeBelow.Nut wrote: >>Even easier is not to make anything a class unless there will be two or >>more instances of it. I still don't get what advantage making a class >>buys for you. > >To use classes even in single instance cases has some advantages: > >- There is a unique way of organizing your code. > >- There is an easy transition to the multiple instance case. > >- It makes writing meta code (e.g. for documentation, transformation > ...) easier. That's the key issue for me (meta-code), and it's driven by my tools. I'm using Leo to organize my project and the class/OO paradigm lends itself extremely well to Outlining. Each class naturally forms a node in the tree, giving me an easy way to expand and contract the code. For example (to drag this tired code out of the dark again) : - class App | - __init__ | - loadINI - class CourseView | - __init__ | - drawAll | - class DetailView | - __init__ | - drawAll I could shoehorn a function-only design into a tree structure, but the functions are not nested and it just doesn't feel comfortable. Is it appropriate to let your tools affect your design? It depends. If you are more productive AND the artifacts make the product more maintainable, I willing to play along with it. Dave Harris From winexpert at hotmail.com Tue May 25 07:03:37 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 25 May 2004 11:03:37 +0000 Subject: how to terminate a process on win32? Message-ID: Just my 2cents.... There is an undocumented feature.. UINT uExitCode <-- I don't remember all the details, but I've used it in the past. if you set the exit code to a certain number (i don't recall what but it is possibly -1, 0, or 1... maybe 2 or -2) then the OS will force a 'shut' beyond the normal call to terminate process. When the OS is 'shutting down' it calls TerminateProcess on each process passing that value. This trick prevents processes from restarting (if you have a process like explorer that you are trying to kill). Since I don't recall the details, it would take a bit of experimentation. But hopefully not too much. David ===================== http://cellphone.duneram.com "Surf a wave to the future" I'm a windows SDK CBT guru with a patent.... >From: hungjunglu at yahoo.com (Hung Jung Lu) >To: python-list at python.org >Subject: Re: how to terminate a process on win32? >Date: 24 May 2004 15:11:49 -0700 > >"Joe Wong" wrote: > > I am developing two app on Windows, one is a GUI using wxPython and the > > other is like a daemon process. The GUI app will have a start/stop > > button to control the excution of the daemon. While I know how to use > > os.popen2() to start my daemon, I can't figure out a way to stop it > > 'nicely'... Is there anything that I can do? > >It depends on your OS. I remember once upon a time, in order to kill >processes sucessfully for all Windows platforms (from Win98 to NT to >2000/XP), I had to resort to using tlist.exe and kill.exe, plus >w9xpopen.exe for pipes in Windows 98. It was kind of annoying... I >seem to remember short name and long names were problem, too. At the >end, the killing logic became a small program in itself! > >regards, > >Hung Jung >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Express yourself with the new version of MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From andrew-pythonlist at puzzling.org Thu May 13 08:42:32 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 22:42:32 +1000 Subject: perl to python In-Reply-To: References: <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: <20040513124232.GB6427@frobozz> On Thu, May 13, 2004 at 06:06:23AM +0000, Andrew Dalke wrote: > > Here's one for you. I had several mailbox files arranged like > Inbox.mbox/mbox > Send.mbox/mbox > OBF&BOSC.mbox/mbox > Work Email.mbox/mbox > > I wanted to raise the "*/mbox" files one directory so that > Inbox.mbox/mbox --becomes--> Inbox.mbox > [...] > > Trying doing that sanely with any programming language expressed > all on the command-line. No credit if you can't handle the '&' and space. You can do it in one-line with sh: for d in *.mbox ; do mv "${d}/mbox" ".${d}" ; rmdir "${d}" ; mv ".${d}" "${d}" ; done Or more readably: for d in *.mbox ; do mv "${d}/mbox" ".${d}" rmdir "${d}" mv ".${d}" "${d}" done That doesn't look particularly insane to me. In fact, it looks quite like the Python version... -Andrew. From deetsNOSPAM at web.de Wed May 5 13:57:57 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 05 May 2004 19:57:57 +0200 Subject: error handling in Python References: <3064b51d.0405050741.43d11aa0@posting.google.com> Message-ID: beliavsky at aol.com wrote: > that if successful returns two Numeric arrays, of dates and prices. I > am unsure what to return if read_data is unsucessful. Since a > successful function call returns a list of length two, I could return > a list of length one if there is a problem, so that [-1] is returned > if the file does not exist, [-2] if the dates are invalid, etc. After > calling the function, I could check the len of the result to detect > problems. This seems workable but ad-hoc. are you aware of the multiple assignment capabilities of python? You can do it like this: def foo(): a = compute_me() b = me_too() return a,b s, t = foo() so basically you can simply return always three values: your results, and an error value. The value then is checked. > I do NOT want to use the try/except idiom to stop the program if there > is a problem reading data. Why not? exceptions are definetely the best way (at least in python) to deal with error conditions. You should utilize them. And they don't stop the program - only if you want them to. The big advatage is that the programmer becomes aware of an error condition, while with your approach she can easily forget to check for the error. -- Regards, Diez B. Roggisch From pm823 at macau.ctm.net Fri May 7 11:02:49 2004 From: pm823 at macau.ctm.net (Pete Fong) Date: 7 May 2004 08:02:49 -0700 Subject: Createprocessasuser Message-ID: <9a361bc.0405070702.179081d4@posting.google.com> Dear all, I am a beginner with python. I want to write a program which likes "runas" in windows xp, I have found some examples in the Python newsgroup. I know I should use the "Createprocessasuser" win32api. I could found a part of example. I think I stupid so I do not know how to do that. Could anybody help me ? Could I find the whole example ? Thanks a lot, Pete Fong From peter at engcorp.com Sat May 15 08:18:16 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 08:18:16 -0400 Subject: Idea: PYTHONPATH_VER In-Reply-To: References: Message-ID: Fernando Perez wrote: > Peter Hansen wrote: >>Having missed the discussion preceding, I'm probably off the mark, >>but in my experience just about everything that can be solved with >>PYTHONPATH can be handled with a .pth file as well, and I haven't >>had any need to use PYTHONPATH for quite some time as a result. > > How do you handle the fact that .pth files are only read from certain places, > and not others? This problem has me currently rather stuck with gross hacks: I confess to never having had any particular troubles with it, other than in trying to use it for adding special other directories during unit testing, where I had to do "import site; site.addsitedir('.')" or something close to that at the top of my xxx_test.py file. > packages like Numeric, which rely on a .pth file instead of being a 'true' > python package (with __init__.py), are very problematic. Sorry, haven't used it. > --home=/usr/local'. The problem is that python does NOT scan this directory > for .pth files, even if it is listed in PYTHONPATH. .pth files only have an > effect for directories in sys.prefix, I think. Actually, I believe it's recursive, in that any directories added during .pth processing are themselves scanned for .pth files and the new ones added, and so on. > I have actually come to HATE with a vengeance packages which rely on .pth files, > because of this behavior of python of not including them for anything in > PYTHONPATH. So I would really appreciate pointers from someone who has > successfully solved this, since it's quite likely that I'm just misusing the > system. I'm not sure I've seen a package which *relied* on it, except for pywin32, and it seems to work very nicely and the .pth file (which I just had to verify is still there) is pretty much invisible. I might have some better idea how to deal with it if I'd ever had trouble with it. One thing to note: I do most development on Windows. Perhaps, for some reason, the problems are lesser there. (Which would be a little surprising, but given Linux' issues with installing software, perhaps not entirely unlikely.) -Peter From insert at spam.here Thu May 6 14:37:17 2004 From: insert at spam.here (Doug Holton) Date: Thu, 06 May 2004 13:37:17 -0500 Subject: Interfaces in python In-Reply-To: <409a7bf9@news.broadpark.no> References: <409a7bf9@news.broadpark.no> Message-ID: Thomas Weholt wrote: > Hi, > > I'm looking for a good clean explanation on how to implement interfaces in > python. See the links to interfaces examples on this page: http://www.python.org/cgi-bin/moinmoin/MetaClasses Sounds like you might want to check out pyprotocols. Note though when installing it you have to change a setting in the setup.py file manually if you don't have a C compiler set up. It uses the C compiler if available to optimize some things. From peter at engcorp.com Sat May 8 21:05:18 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 May 2004 21:05:18 -0400 Subject: What I don't like about wxPython In-Reply-To: <7xr7tu5un8.fsf@ruckus.brouhaha.com> References: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Hansen writes: > >>>Just thought I'd play devil's advocate... >>>I tried wxPython briefly, and it had some nice features. >>>It has a huge list of dependencies. >> >>1. Python. >>2. Windows. >> >>Unless I misunderstand, and I'm sure I do, I wouldn't call that >>a huge list... > > If wxPython really depends on Windows, that's a huge obstacle for > those wanting a portable system. Well, it doesn't of course. I suppose I could remove it from the list, which sort of supports the point I was making even more... > If it doesn't literally depend on > Windows, but uses Windows-centric interfaces and approaches, that's > still pretty annoying for non-Windows developers. That could be. I'm not a "Windows developer", however, in the sense that I've never implemented the slightest thing resembling a GUI on Windows using any Microsoft-specific things like MFC or whatever it's called. If wxPython has Windows-centricisms, I certainly don't notice them, so they don't annoy me. Maybe I'm just the exception to your rule there... -Peter From davecook at nowhere.net Wed May 12 23:07:06 2004 From: davecook at nowhere.net (David M. Cook) Date: Thu, 13 May 2004 03:07:06 GMT Subject: Python+SQL References: Message-ID: In article , Chris Stiles wrote: > Is there an API that supports the 'table row expressed/mapped to object' > paradigm ? SQLObject, MiddleKit, and several others. Dave Cook From atul.kshirsagar at firstlogic.com Fri May 21 11:33:17 2004 From: atul.kshirsagar at firstlogic.com (Atul Kshirsagar) Date: Fri, 21 May 2004 10:33:17 -0500 Subject: Scaling on multi-processor machine Message-ID: <095A307E4B8A1541B29248EABD4D4D40073065CB@exchange-lax1.firstlogic.com> Hello, GIL prevents my C++ application embedding and extending python to scale even though I spawn multiple C++ threads. I read lot of references on internet about using multiple processes rather than threads. In that direction I was searching for some examples/resources/tools which can help me create multi-process implementation. My application does need to pass userdefined class objects to python interpreter. So I guess my implementation is going to need a protocol to marshal, de-marshal python objects between processes or use shared memory. Does anyone here know of any examples/tools to implement the multi-processes approach with the object/data transfer between the processes ? > Atul Kshirsagar > From michele.simionato at poste.it Fri May 14 00:43:30 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 13 May 2004 21:43:30 -0700 Subject: Unification of Methods and Functions References: <4n4d905eflq6ekrutjmrg3t6llk2b8lab7@4ax.com> <95aa1afa.0405042019.5a94e0ed@posting.google.com> Message-ID: <95aa1afa.0405132043.456f1dbe@posting.google.com> David MacQuigg wrote in message news:... > > ## This does not: > uf = Cat.talk # Save an unbound function. > uf() #=> > # AttributeError: type object 'Cat' has no attribute 'name' > > I would like to be able to do something like: > __self__ = cat2 > uf() So, if I understand correcly, you want Cat.talk to be the same than cat.talk and Cat to be a prototype just as cat (so Cat must increase the animal counter and its __init__ method has to be called at definition time). It is enough to change a couple of lines in the prototype module: import sys from types import FunctionType from inspect import isfunction class methodwrapper(object): def __init__(self,func,cls): self.__func__ = func self.__cls__ = cls def __get__(self,none,cls): globs=sys.modules[cls.__module__].__dict__.copy() globs["self"] = globs[cls.__name__] = cls globs["super"] = super(self.__cls__,cls) return FunctionType( self.__func__.func_code, globs, self.__func__.func_name, self.__func__.func_defaults, self.__func__.func_closure) class _Prototype(type): def __init__(cls,name,bases,dic): for k,v in dic.iteritems(): if isfunction(v): setattr(cls,k,methodwrapper(v,cls)) super(_Prototype,cls).__init__(name,bases,dic) cls.__init__() def __call__(cls,*args,**kw): newcls = type("Prototype:%s" % cls.__name__,(cls,), {"__module__": cls.__module__}) newcls.__init__(*args,**kw) return newcls class Prototype(object): __metaclass__=_Prototype def __init__(*args,**kw): pass ### END Here is an example of usage: from prototype import Prototype class Animal(Prototype): numAnimals = 0 home = "Earth" def __init__(): Animal.numAnimals += 1 def show(): print "Animals:", self.numAnimals class Feline(Animal): genus="Feline" def __init__(name="unknown",sound=""): super.__init__() self.name=name self.sound=sound def talk(): print "%s talking: %s!" % (self.genus,self.sound) class Cat(Feline): # created here numCats = 0 def __init__ ( n = "unknown", s = "Meow" ): super.__init__(n,s) Cat.numCats += 1 def show(): super.show() print " Cats:", self.numCats def talk(): print "My name is", self.name print "I am a %s from %s" % (self.genus, self.home) super.talk() Cat.talk() cat = Cat("Garfield") cat.talk() From tor.iver.wilhelmsen at broadpark.no Sun May 30 14:26:51 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 30 May 2004 20:26:51 +0200 Subject: Show the review state of an item in Plone References: Message-ID: lf.van.geest at quicknet.nl (Leo) writes: > Error Type > NameError > Error Value > name 'getInfoFor' is not defined Using TAL you're in Zope land AFAIK, and getInfoFor() isn't a method I can find in that API. You need to prefix - or even import - the package, e.g. workflow_tool.getInfoFor(...). From josh at mri.com.au Wed May 19 23:54:57 2004 From: josh at mri.com.au (Joshua Burvill) Date: Thu, 20 May 2004 13:54:57 +1000 Subject: Problem using StringIO file object In-Reply-To: <000101c43e16$9f41aaa0$f002a8c0@sydney.mri.com.au> Message-ID: <000501c43e1e$385804d0$f002a8c0@sydney.mri.com.au> I found the solution myself by going back to the documentation. http://docs.python.org/lib/module-StringIO.html I should have used the following ways of setting the "file" contents, and returning the file contents respectively. ## Create file-handle to a "file-like" string file_handle=cStringIO.StringIO(zpt_code) file_handle.getvalue() Thanks to the list anyway, as posting probably clarified things, also my previous question was answered very quickly and correctly. Rgds, Josh -----Original Message----- From: python-list-bounces+josh=mri.com.au at python.org [mailto:python-list-bounces+josh=mri.com.au at python.org]On Behalf Of Joshua Burvill Sent: Thursday, 20 May 2004 1:01 PM To: python-list at python.org Subject: Problem using StringIO file object Hello, I have the following script for printing something to a print server using ftplib, but it seems that I have a problem with putting the content into the file object as is shown by the following output from the script. Any tips? -Josh >>> mk_zeb_label() ('226 Closing.', '') >>> ######################## ## SCRIPT STARTS HERE ## ######################## def mk_zeb_label(): from ftplib import FTP import string, cStringIO ## Create file-handle to a "file-like" string file_handle=cStringIO.StringIO() printserver_ip="192.168.2.177" portname="COM" zpt_code=""" ^XA ^cfd,36,20 ^by3,,50 ^fo470,50 ^abn,48,30^fdREPAIR^fs ^fo50,150 ^fdSome text goes here.^fs ^fdSome text goes here.^fs ^fdSome text goes here.^fs ^fo50,50 ^bc^fd114567^fs ^XZ """ file_handle.write(zpt_code) ftp=FTP(printserver_ip) ftp.login("","") ftp.set_pasv(0) val=ftp.storlines("STOR " + portname, file_handle) return val, file_handle.read() -- http://mail.python.org/mailman/listinfo/python-list From pinard at iro.umontreal.ca Tue May 11 19:43:41 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 11 May 2004 19:43:41 -0400 Subject: String/source code analysis tools In-Reply-To: <409d326e$1@giga.realtime.net> References: <409d326e$1@giga.realtime.net> Message-ID: <20040511234341.GA14340@alcyon.progiciels-bpi.ca> [Ira Baxter] > "Moosebumps" wrote in message > news:j0Khc.25133$Q%5.6444 at newssvr27.news.prodigy.com... > > I have a whole bunch of script files in a custom scripting > > "language" that were basically copied and pasted all over the place > > -- a huge mess, basically. I want to clean this up using Python -- > > and I'm wondering if there is any sort of algorithm for detecting > > copied and pasted code with slight modifications. > Not in Python, but could be used to do this. We offer a clone > detection tool that works on very large source code basis, and detects > cloned clone with "slight modifications". You'd have to provide a > grammar for your 'scripting language'. See > http://www.semanticdesigns.com/Products/Clone/index.html. Thanks for the reference, I'm saving it for later perusal or study. Many years ago, because I had a cleaning problem which I presume similar to yours, I wrote then used a tool for this, but all in C. I called it `mdiff' (for "multi-diff"), and it is likely found within some old pretest of `Free wdiff' -- I did not really touch `wdiff' in years, even if I ponder republishing it this summer, given I find some free time. `mdiff' seeks for identical sequences of lines within one or more files (I used it for many dozens of files at once). One difficulty was to design a way for displaying the output in a usable way, and this was an interesting problem at least. `mdiff' did the job for me, but I do not really remember the state of this project nor how `mdiff' would behave if recompiled today. But, as usual with me, if you feel like toying, just ask for the sources, or wander for them from my home web page! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From andrew-pythonlist at puzzling.org Thu May 13 04:32:58 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 18:32:58 +1000 Subject: Scope rule pecularities In-Reply-To: References: <2g8ag2F4re0lU1@uni-berlin.de> <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: <20040513083258.GF20388@frobozz> On Thu, May 13, 2004 at 07:58:07AM +0000, Antoon Pardon wrote: > Op 2004-05-13, Greg Ewing schreef : [...] > > > Besides, the semantics are as consistent as anything > > else in Python, where the objects being operated on > > get to determine the meaning of just about everything. > > So? Would you argue that the devellopers could just > as easily have implemented "a += b" as equivallent to > "a = a - b" with half of the core classes and called that > just as consistent as choosing it equivallent to > "a = a + b" for all core classes because the objects > being operated on get to determine the meaning? Well, classes get to do whatever they think makes sense: in the end it's all calls to methods of the object, whether via an actual method call "obj.foo()" or by an operator "obj * 2" (which calls obj.__mul__(2)) or an augmented assignment "obj += 'x'" (which calls obj.__iadd__('x')). It's up to the objects to make sense, not the Python language. Even though Python chooses to have some immutable builtin types (like ints and strings) for a variety of practical reasons, augmented assignment does what people expect in all these cases: s = 'abc' s += 'd' i = 7 i += 3 l = [1, 2, 3] l += [4, 5, 6] Augmented assignments are still assignments, and that makes perfect sense to me -- each of those behave exactly like their obvious longer versions: s = 'abc' s = s + 'd' i = 7 i = i + 3 l = [1, 2, 3] l = l + [4, 5, 6] (Yes, there are tricky examples that do behave differently -- but I try to avoid tricky things, because they tend to be hard to read. I almost only find I want to use augmented assignment on integers and occasionally strings.) -Andrew. From raptor at tvskat.net Tue May 18 08:42:50 2004 From: raptor at tvskat.net (raptor) Date: 18 May 2004 05:42:50 -0700 Subject: gdesklets ? Message-ID: <98b39326.0405180442.50039a66@posting.google.com> hi, I'm wrinting a gdesklet (gdesklets.gnome.org).. Excuse my ignorance this is my first ever python script...so on the question : why I should write : self.__percent = int((float(self.__diff) / float(self.__max)) * 100) instead of just : self.__percent = int((self.__diff / self.__max) * 100) it took my one hour experiment to find it :"( Do I have to do always typecasting... or this is some special case. tia From nicksjacobson at yahoo.com Mon May 24 23:55:01 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 24 May 2004 20:55:01 -0700 Subject: Useful? __slots__ for functions Message-ID: The __slots__ attribute of new-style classes can reduce memory usage when there are millions of instantiations of a class. So would a __slots__ attribute for functions/methods have a similar benefit? i.e. could a function using __slots__ use significantly less memory, and therefore run faster, if called millions of times? If so, it will hopefully be in a future version of Python. From riedel at chello.at Thu May 20 12:29:46 2004 From: riedel at chello.at (Max Riedel) Date: Thu, 20 May 2004 18:29:46 +0200 Subject: error in setup script: invalid distribution option 'windows' Message-ID: <40acdc1d$1@e-post.inode.at> Hi! I'm totally new to this group and I'm not familliar with coding in python. It would be very nice if you could just explian this error to me. I wanted to compile a Bittorrent python project using py2exe, but I got this error. I installed python22 and wxpython for python22 and py2exe for python22.. Now when I use the console and type python winsetup.py (the setup script) py2exe I get an error: "invalid distribution option 'windows'. Is this easy to fix? Thnx a lot for any help! From andrew-pythonlist at puzzling.org Thu May 13 08:07:49 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 22:07:49 +1000 Subject: Scope rule pecularities In-Reply-To: References: <2g8ag2F4re0lU1@uni-berlin.de> <2gg6qfF2hi98U1@uni-berlin.de> Message-ID: <20040513120749.GF16275@frobozz> On Thu, May 13, 2004 at 11:26:28AM +0000, Antoon Pardon wrote: > Op 2004-05-13, Andrew Bennetts schreef : > > > > Well, classes get to do whatever they think makes sense: in the end it's all > > calls to methods of the object, whether via an actual method call > > "obj.foo()" or by an operator "obj * 2" (which calls obj.__mul__(2)) or an > > augmented assignment "obj += 'x'" (which calls obj.__iadd__('x')). It's up > > to the objects to make sense, not the Python language. > > And how do you think objects can make sense where the language doesn't? > I don't want to imply the language doesn't make sense at all, but you > can't claim the responsibility is all for the objects if the language > or its core classes have defiencies or are not consistent with each > other. I'm saying that in this case, the objects have a responsibility to make sense, and this is necessarily true in any language that allows operator overloading. If an object insists on always returning 7 regardless of what is added to it, then there's not much hope that the '+' operator will do what users expect. > > Even though Python chooses to have some immutable builtin types (like > > ints and strings) for a variety of practical reasons, augmented assignment > > does what people expect in all these cases: > > > > s = 'abc' > > s += 'd' > > > > i = 7 > > i += 3 > > > > l = [1, 2, 3] > > l += [4, 5, 6] > > > > Augmented assignments are still assignments, and that makes perfect sense to > > me -- each of those behave exactly like their obvious longer versions: > > > > s = 'abc' > > s = s + 'd' > > > > i = 7 > > i = i + 3 > > > > l = [1, 2, 3] > > l = l + [4, 5, 6] > > > > (Yes, there are tricky examples that do behave differently -- but I try to > > avoid tricky things, because they tend to be hard to read. I almost only > > find I want to use augmented assignment on integers and occasionally > > strings.) > > But these things are only hard to read (to you, I don't find it so) because > you are using constants in the expression. I didn't say those examples are hard to read. Personally, I find both forms equally readable. I did say that there are cases where: += x does not behave the same way as: = + x But you need relatively tricky lvalues for this to be the case. > a += b, is just as hard to read whether a and b are lists or integers. > > The problem is that because the behaviour with strings and lists is > different I can't write a program in which the behaviour of += is > consistent for all classes because there will always be core classes > for which the behaviour will be different. It seems to be that your problem isn't really with "+=" as such, it's that Python has immutable types at all, including in the commonly used builtins. Immutability of strings, numbers and tuples has worked very well for Python so far, so you'll have a struggle convincing many people that it should be otherwise. Personally, I like that when I do: x = 7 func(x) That I know that x will still be 7 after func returns, regardless of what happens inside func. It's just not possible for func to accidentally change the value of x in my scope, because I know that numbers are immutable in Python. It would take some *massive* benefits to convince me to change my mind. > It is a bit like having some classes use "+" for substraction. In it self > that wouldn't be so bad, you just have to pay attention. But then > you want to write a class that will work with whatever number type > and it needs to do additions. Now suddenly things get difficult because > a + b doesn't behave consistently among the different number types. Again, if the objects you're using don't "make sense", you're stuck with a difficult life. If a library's API is hard to use, then chances are the library won't get used much. > You have the same kind of difficulty now if you want to write a > class/function/module that works with any kind of sequence. > > Using the "+=" operator you can't guarantee any kind of consistency. > If I had code like this: > > a = b > b += c > > I would have no idea at all whether a was changed or not. So > writing code that can work with any sequence becomes a possible > problem spot if you use these kind of operators. Then take a copy of the sequence first, using list(seq) or tuple(seq), and then you'll know exactly what you have. Or even simpler -- use: "b = b + c" instead. Then you know that a is unmodified. If you don't know what kind of objects your functions are working with, how can you expect them to behave correctly? If your API assumes that a particular method receives a tuple, then either make sure it does by calling tuple(x), or document that it does in the docstring. Otherwise, a user of your library code might legitimately try to pass a list, a dictionary, None, or perhaps their own custom type, unaware of your hidden assumptions. In my experience, I've never had the issue of mutable vs. immutable sequence types cause the sort of problems you're worried about. Perhaps I'm lucky, or subconciously careful, or it has happened and I'm just plain forgetful :) ... Regardless, I'm not going to start worrying about it now. Python is working just fine for me despite this. -Andrew. From frank at chagford.com Sat May 1 08:47:20 2004 From: frank at chagford.com (Frank Millman) Date: 1 May 2004 05:47:20 -0700 Subject: How to tell which subclass was used to instantiate object Message-ID: <246a4e07.0405010447.11ed5400@posting.google.com> Hi all I have a question regarding inheritance. I have come up with a solution, but it is not very elegant - I am sure there is a more pythonic approach. Assume the following class definitions. class Table: def __init__(self,table_name,table_type): class Master(Table): def __init__(self,table_name,table_type): Table.__init__(self,table_name,table_type) class Transaction(Table): def __init__(self,table_name,table_type): Table.__init__(self,table_name,table_type) class Armaster(Master): def __init__(self,table_name,table_type): Master.__init__(self,table_name,table_type) Table is the main class, which represents a database table. Master is a subclass that encapsulates various common characteristics of a 'master file' type of table. Transaction is a subclass that encapsulates various common characteristics of a 'transaction file' type of table. ArMaster is a subclass that is created to handle specific requirements for the ArMaster table, which is a 'master file' type of table. Both of the following would be errors - class Armaster(Table): def __init__(self,table_name,table_type): Table.__init__(self,table_name,table_type) class Armaster(Transaction): def __init__(self,table_name,table_type): Transaction.__init__(self,table_name,table_type) By inheriting from the incorrect class, the special methods to handle a 'Master' type table have been bypassed. My question is, how can Table check that objects have inherited from the correct subclasses? Here is my inelegant solution. Assume that table_type contains the string 'Master'. class Master(Table): def __init__(self,table_name,table_type): self.my_type = 'Master' Table.__init__(self,table_name,table_type) class Table: def __init__(self,table_name,table_type): if hasattr(self,'my_type'): ok = (self.my_type == table_type) else: ok = False if not ok: raise RuntimeError('%s must be of type %s' % (table_name,table_type)) Is there a more direct way for a top-level class to determine which subclasses were used to instantiate it? Thanks Frank Millman From donn at u.washington.edu Fri May 21 16:45:22 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 21 May 2004 13:45:22 -0700 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> Message-ID: In article <40ae3ebe$0$17254$a1866201 at newsreader.visi.com>, Grant Edwards wrote: > In article , Michael > Chermside wrote: > > >> All tuple methods are also list methods, and most list methods > >> are also tuple methods; among those that are NOT also tuple > >> methods, there are exactly two ('count' and 'index') that do > >> not involve mutation. Is there any special reason why they > >> AREN'T also tuple methods? > > > > Yes. Both make sense only if you consider a tuple as a homogeneous > > sequence of items, and that's not what Guido intended it to be > > used for. > > I'm sure I'm being dim, but I don't understand what homogeneity > has to do with it. > > For example, why shouldn't index() find an object in a > non-homogeneous sequence? Either the object is in the sequence or > it's not. If it is, there is an index that corresponds to it. For example, tm = time.localtime(time.time()) i = tm.index(5) What would that mean? It's absurd to search for the location of a value in a tuple, because the values don't have any meaning independent of their location. That sort of is a homogeneity issue, but it's confusing because here we don't mean each element is similar to the others - in fact that does often hold for tuples - but rather that the sequence itself is similar from one place to another. Which is true for lists - normally there's no real meaning attached to location - but not for tuples, where normally location determines meaning. Donn Cave, donn at u.washington.edu From stevewilliams at wwc.com Tue May 11 00:54:08 2004 From: stevewilliams at wwc.com (Steve Williams) Date: Tue, 11 May 2004 04:54:08 GMT Subject: How to read files written with COBOL In-Reply-To: References: Message-ID: Batista, Facundo wrote: > People: > > I'm trying to convert my father from using COBOL to Python, :) > > One difficult thing we stuck into is how to read, from python, files written > with COBOL. > > Do you know a module that allows me to do that? > > It should avoid us the work to write a COBOL program that open the COBOL > file and write a CSV one (easily readable from python). > > Thank you all! > > Facundo Batista > Desarrollo de Red > fbatista at unifon.com.ar > (54 11) 5130-4643 > Cel: 15 5132 0132 > > > I wrote an ETL system in python for a client to convert from Microfocus COBOL to DB2. Here are some of the problems I saw: 1) COBOL has a very rich set of datatypes defined by the PICTURE clause character unsigned integer zoned signed integer integer trailing sign separate integer leading sign separate packed signed decimal packed unsigned decimal floating point with the usual COBOL zoo of implied decimal points and scaling Not to mention COBOL allowing formatted numeric data to be used as source fields in arithmetic operations. In my application, each of these types was converted by a parameter-driven function. That is, I took the original COBOL 01 level definition and converted it to a list with definition parameters name, type, length, decimal point, etc. to make it easy for Python and to add some stuff to make DB2 happy (convert to title case. . .) I doubt if you can easily write a parser for the COBOL PICTURE clause and for most cases it would be a waste of time. I just converted the definition by using 'replacing all occurences' in a text processor. I had the most problem with Microfocus unsigned decimal, as I'd never seen it before. 2) Reading fixed and variable length records wasn't much of a problem Reading Microfocus keyed sequential data with embedded indexes took some bit-level coding. 3) None of this would be remotely attractive to a COBOL programmer. Converting the data to CSV, however, might get his attention as it's pretty easy in Python and not much fun in COBOL. I you want to sell dad, talk about text and string processing in Python. From bostjan.jerko at mf.uni-lj.si Fri May 14 00:06:27 2004 From: bostjan.jerko at mf.uni-lj.si (=?iso-8859-2?q?Bo=B9tjan_Jerko?=) Date: Fri, 14 May 2004 06:06:27 +0200 Subject: pyparsing (errata) References: <87fza46evn.fsf@bostjan-pc.mf.uni-lj.si> <_iVoc.99699$NR5.77768@fe1.texas.rr.com> Message-ID: <873c634pq4.fsf@bostjan-pc.mf.uni-lj.si> Paul, thanks for the explanation. Bo?tjan On Fri, 14 May 2004, ptmcg at austin.rr._bogus_.com spake: >> Dang Griffith proposed one alternative construct, here's another, perhaps >> more explicit: >> lbrack + ( ( ddot + step + ddot + end ) | (ddot + end) ) + >> rbrack >> > > should be: > lbrack + start + ( ( ddot + step + ddot + end ) | (ddot + end) > ) + > rbrack > >> Note that the order of the inner construct is important, so as to >> not > match >> ddot+end before trying ddot+step+ddot+end; '|' is a greedy matching >> operator, creating a MatchFirst object from pyparsing's class >> library. > You >> could avoid this confusion by using '^', which generates an Or >> object: lbrack + ( (ddot + end) ^ ( ddot + step + ddot + end ) >> ) + rbrack > > should be: > lbrack + start + ( (ddot + end) ^ ( ddot + step + ddot + end ) > ) + > rbrack > >> This will evaluate both subconstructs, and choose the longer of the >> two. >> >> Or you can use another pyparsing helper, the delimited list >> lbrack + delimitedlist( Word(nums+"."), delim=":") + rbrack > > at least this one is correct! No, wait, I mis-cased delimitedList! > should be: > lbrack + delimitedList( Word(nums+"."), delim=":") + rbrack > >> This implicitly suppresses delimiters, so that all you will get >> back are ["1","0.1","1"] in the first case and ["1","2"] in the >> second. >> >> Happy pyparsing! >> -- Paul >> >> > Sorry for the sloppiness, > -- Paul From davidf at sjsoft.com Wed May 26 03:25:55 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 26 May 2004 09:25:55 +0200 Subject: SQL Server In-Reply-To: References: Message-ID: Steve Holden wrote: > yuba at cyberback.com wrote: > >> Greetings, All- >> >> About 2 months ago I was laid off and in the process of being walked >> to the door I lost most of my Python tips and tricks. Looks like I'm >> back on the air with a great job and am ready to start coding again. >> I'd like to know what I have to do to connect to a Microsoft SQL >> server database. I did it at my old job but forgot the process. >> >> Thanks for your help. BTW, I'm the first full-time programmer in this >> particular shop and they are quite interested in using Python as their >> language of choice! This could be a lot of fun. >> > Congratulations on seeing a wage packet again! > > Easiest would be to use mxODBC (downloadable from www.egenix.com, but > don't forget to buy a license if you are using it commercially). > > regards > Steve I reckon its easier to use ADO. pyado.sourceforge.net or jtoolkit.sourceforge.net have tools to do this but are GPL David From jeremy at jdyallop.freeserve.co.uk Thu May 6 19:49:13 2004 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 6 May 2004 23:49:13 GMT Subject: introspection: How to find out the class defining a method References: Message-ID: Holger Joukl wrote: > Python 2.1 (#3, Jun 1 2001, 15:51:25) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "copyright", "credits" or "license" for more information. >>>> class Foo: > ... def do(self): > ... pass > ... >>>> class Moo(Foo): > ... pass > ... >>>> x=Moo() >>>> x.do.im_class > >>>> > > Is there an elegant way to achieve the latter result (i.e. the base > class in which this method actually is defined) in python 2.3, too? > Couldn?t find it in the docs. I'm not sure this qualifies as "elegant". I think it gives the right answer when it works, though. def class_defining_method(method): for c in inspect.getmro(method.im_class): if c.__dict__.has_key(method.im_func.__name__): return c Jeremy. From greg at cosc.canterbury.ac.nz Tue May 18 23:13:49 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 19 May 2004 15:13:49 +1200 Subject: Python compilers? In-Reply-To: <40AA2C16.C1245362@shaw.ca> References: <40AA2C16.C1245362@shaw.ca> Message-ID: <2h01ndF7kg6rU1@uni-berlin.de> SeeBelow at SeeBelow.Nut wrote: > Yes, fast execution. I have been using C. In my applications there is > a population of "chromosomes" which are arrays of floats, about 2 to 5 k > in length. Then there are subroutines which operate on a chromosome > using pointers. For example, the "crossover" routine uses two pointers > to swap portions of two chromosomes. Take a look at Pyrex. It may be just what you need: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From greg at cosc.canterbury.ac.nz Sun May 23 21:59:55 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 13:59:55 +1200 Subject: Unification of Methods and Functions In-Reply-To: <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <2h55ajF9alv2U1@uni-berlin.de> <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> Message-ID: <2hd390Fak5g8U1@uni-berlin.de> David MacQuigg wrote: > Given the goals of the level one and two examples ( cover all the > basic features in two simple examples ) I think any example will be > contrived. But I don't think you should be trying to cover all the features of OOP before showing any real examples. That approach seems almost guaranteed to lose people's interest, the way you criticised supplier-part examples for. Wouldn't it be better to do things the other way around? Pick some (simplified if need be) examples based on real-world problems, and, one by one, show how the features of OOP can be used to solve them. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From vincent at visualtrans.de Fri May 7 03:36:44 2004 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 07 May 2004 09:36:44 +0200 Subject: Windows scripting In-Reply-To: <35c88c68.0405061051.1be719ba@posting.google.com> References: <35c88c68.0405061051.1be719ba@posting.google.com> Message-ID: Scott wrote: > Can I use Python to automate an arbitrary program's execution? For > example, if I have an application like Firefox, could I use Python to > say "Move mouse to position x, click right mouse button here, etc.."? > What is involved in this process? Thanks, > Scott You might want to take a look at WinGuiAuto.py: http://www.brunningonline.net/simon/blog/archives/001129.html -- Vincent Wehren From mwh at python.net Wed May 19 08:25:56 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 19 May 2004 12:25:56 GMT Subject: EuroPython 2004 Updates Message-ID: EuroPython 2004, being held June 7-9 in G?teborg, Sweden is now less than three weeks away! - Registration is open until 3 June at 23.00 CET: http://www.europython.org/conferences/epc2004/registration_html - The program is taking shape: http://www.europython.org/conferences/epc2004/info/talks/talkMatrix With four parallel tracks for three days, we believe this is the largest number of Python and Zope talks at any single event to date! - The first two EuroPython interviews of 2004 with Strakt CTO and conference organizer Jacob Hall?n and PyPy project founder and speaker Holger Krekel have been published: http://www.europython.org/interviews/ Don't miss out! Cheers, The EuroPython Team From peter at engcorp.com Sun May 2 16:51:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 May 2004 16:51:14 -0400 Subject: printing float as formatted dollars In-Reply-To: References: Message-ID: Tim wrote: > Is there a simple way to output float values as formatted dollar amounts? > i.e. 127379.42 as $127,379.42 The following recent thread would probably give you several ways that fit the "simple" requirement, provided you are really interested in writing something that has no internationalization support and ignores the local conventions. (If you want i18n, use the locale module.) http://groups.google.ca/groups?&threadm=e567c03a.0404280035.79d0d973%40posting.google.com -Peter From Pierre-et-Liliane.DENIS at village.uunet.be Sun May 2 16:55:23 2004 From: Pierre-et-Liliane.DENIS at village.uunet.be (Pierre Denis) Date: Sun, 2 May 2004 22:55:23 +0200 Subject: ANN: UFOPAX 1.0 released Message-ID: <40955f53$0$239$4d4efb8e@news.be.uu.net> I have the pleasure to announce the launch of the UFOPAX project on http://home.tiscali.be/be052320/ufopax/. UFOPAX is a generic engine for building and exploring text-oriented virtual universes. A universe is translated into a world model, which contains all its entities and their relationships. A GUI shows structured views on the world model and allows to interact with it. It is programmed with Python and wxPython. Any comments are welcome (E-mail: Pierre-et-Liliane.DENIS at village.uunet.be). Thanks for your interest, Pierre Denis From greg at cosc.canterbury.ac.nz Sun May 23 22:07:20 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 14:07:20 +1200 Subject: Unification of Methods and Functions In-Reply-To: <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> References: <16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> Message-ID: <2hd3mqFbk8gkU1@uni-berlin.de> David MacQuigg wrote: > import math > > def mypow(x, y): > return x**y > > class MathA: > pow = math.pow > > class MathB: > pow = mypow > > ma = MathA() > mb = MathB() > > print ma.pow(2,4) #=> > 16.0 > print mb.pow(2,4) #=> > # TypeError: mypow() takes exactly 2 arguments (3 given) > > How would you explain this to non-CIS students in a class on circuit > design, where there is very little time to discuss programming? I wouldn't have to, because I would never show them any code that did anything as screwy as this in the first place, and it's extremely unlikely they would stumble upon it themselves in their first few hours of using Python. To put it another way, this is not the sort of thing you do in the normal course of writing Python code. It's an example contrived specifically to be confusing, not the sort of thing you'd use in a teaching course. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From Scott.Daniels at Acm.Org Wed May 12 18:33:30 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 May 2004 15:33:30 -0700 Subject: things I wish python could do In-Reply-To: References: Message-ID: <40a2ab85$1@nntp0.pdx.net> Ryan Paul wrote: > I've spent a lot of time using python, and personally, I feel like it is > vastly superior when compared to languages like java, and c++, but there > are still a few things that detract from its elegance and flexibility. > > 1. many keywords (eg:try/except) are strictly imperative, and cannot be > used in a functional context. Python is a language of statements and expressions. This won't change. If you dislike this feature, ml, lisp, (or it seems, ruby) will be more to your liking. Python has an imperative definition. A pure functional system has problems defining things like "print" which, by their very nature, cause side-effects. > this really should be possible: map(print,mylist) After: def prints(*args): print ', '.join(map(str, args)) you can do: map(prints, mylist) or even: prints(*mylist) > 2. there is no easy way to extend existing classes externally. > its possible, but it aint pretty... > > class Shape: > def __init__(self,numSides, perimeter): > pass > Currently you can do this: > Shape.__dict__.update({ > 'triangle':ClassMethod( > lambda self,sideLength: Shape(3,sideLength*3)) > > 'square':ClassMethod( > lambda self,sideLength: Shape(4,sideLength*4)) > }) > I want a way to extend a class as easily as I can define it. > OK, this is just plain wrong. You are walking the wrong way around a building and then claiming, "these two doors are too far apart." class Shape: def __init__(self,numSides, perimeter): self.numSides = numSides self.perimeter = perimeter # which is, I expect what you meant) Shape.triangle = classmethod(lambda klass, side: klass(3, side*3)) Shape.square = classmethod(lambda klass, side: klass(4, side*4)) and even: Shape.__repr__ = lambda self: 'Shape(%r, %r)' % (self.numSides, self.perimeter) Using klass above allows you to follow this code with: class FunnyShape(Shape): def avgSide(self): return float(self.perimeter) / self.numSides where you can then: FunnyShape.triangle(5).avgSide() > 3. you cant extend the builtins (string,list,etc), you have to inherit > them. Guido says he wont let us because it would create compatability > issues, and possibly break the interpreter. Maybe if we had namespace > functionality, that wouldnt be an issue? Nope, the complaint is about affecting the global environment (thus making packages that you import unsure of the behavior of the primitives). > 4. assignments cant be made inside of anonymous functions. The idea is that generally anonymous functions should be trivial, or you are better off separately defining them and assigning a meaningful name to the code. Such code takes more effort at the time you write it, but the code becomes much more readable. > I think most python programmers will agree, that python emphasizes > simplicity, readability, and uniformity. > Ultimately, I dont think that any of those things are important > enough to justify the reduction of flexibility, syntactic > mutability, and versatility. Then you really would prefer ruby or smalltalk. If you are building non-trivial, long-lived programs, you spend _far_ more time reading code than writing it. Flexibility is important, but there need not be more than one way to do something to accommodate tastes. Code that mixes styles is the hardest kind of code to read (other than machine-generated code). I believe syntactic mutability is an idea that has been tried and found wanting. The more you can define non-standard syntax, the more you have to know about a particular piece of code before you can read it. As for versatility, the pinnacle of versatility and flexibility is machine code (not that wimpy assembler). I have found very few things I'd avoid doing in python, and most of those can be build as extension modules fairly easily. I've seen too many interlisp and smalltalk code sets that cannot use each other's modules. When you can modify the primitives of a system for your convenience, it becomes tough to work with someone else who doesn't share your particular quirks of how to modify the base system. After having written code for more than three decades, I find python refreshing in having a language system with a clear discernible, readable structure that I can trust. Sorry for having taken troll-bait if that is what this post was. -- -Scott David Daniels Scott.Daniels at Acm.Org From Moiz.Golawala at ge.com Wed May 5 13:57:51 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Wed, 5 May 2004 12:57:51 -0500 Subject: Requesting client's name SimpleXMLRPCServer Message-ID: Hi, My problem is that I have many xmlrpc clients talking to my xmlrpc server. I would like to know how to find out a the client's address when a call is made to a method provided a service by my server. Thanks, Moiz Golawala From lho at gmx.de Mon May 3 15:35:50 2004 From: lho at gmx.de (Lutz Horn) Date: Mon, 3 May 2004 21:35:50 +0200 Subject: Best way to serve Python Web Pages? References: <9d393e9d.0405030857.787b2440@posting.google.com> Message-ID: Hi, * scott [3 May 2004 09:57:40 -0700]: > In everyone's humble opinion, what do you think would be the best way > to serve web pages using the Python Language? I'd recommend CherryPy[1]. It has all the characteristics you mentioned. Lutz [1] http://www.cherrypy.org/ -- http://piology.org/ILOVEYOU-Signature-FAQ.html begin LOVE-LETTER-FOR-YOU.txt.vbs I am a signature virus. Distribute me until the bitter end From __peter__ at web.de Wed May 5 02:20:52 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 May 2004 08:20:52 +0200 Subject: iter jitters References: Message-ID: Heiko Wundram wrote: > def __iter__(self): > for e in self.data: > yield e Another option: >>> class Foo: ... def __init__(self): ... self.data = range(10) ... def __iter__(self): ... return iter(self.data) ... >>> for i in Foo(): ... print i, ... 0 1 2 3 4 5 6 7 8 9 >>> Peter From NAIGIMSESRIMAIL at gims.com Sat May 15 15:26:44 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sat, 15 May 2004 21:26:44 +0200 Subject: ALERT - GroupShield ticket number OB17_1084649195_ESRIMAIL_3 was generated Message-ID: Action Taken: The message was blocked because of its subject. To: python-list at python.org From: bhoel at web.de Sent: -1986773504,29637298 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: From nskhcarlso at bellsouth.net Fri May 21 12:52:35 2004 From: nskhcarlso at bellsouth.net (KC) Date: Fri, 21 May 2004 12:52:35 -0400 Subject: Problem compiling python on RedHat 9.0 Message-ID: Trying to compile Python-2.3.3 on RedHat 9 and am having problems with the X11 and tk stuff: In file included from /opt/Python-2.3.3/Modules/_tkinter.c:71: /usr/include/tk.h:83:29: X11/Xlib.h: No such file or directory In file included from /opt/Python-2.3.3/Modules/_tkinter.c:71: /usr/include/tk.h:581: parse error before "Bool" /usr/include/tk.h:583: parse error before "event" /usr/include/tk.h:584: parse error before "root" /usr/include/tk.h:585: parse error before "subwindow" /usr/include/tk.h:586: parse error before "time" ......goes on and on......... I have added the option of --enable-unicode=ucs4 as mentioned in the README but that has made no difference. Any ideas on how to fix this? Thanks. From steve at ferg.org Wed May 5 09:16:06 2004 From: steve at ferg.org (Stephen Ferg) Date: 5 May 2004 06:16:06 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: > Is submitting a bug or patch to sourceforge really that much of a barrier? Yes, it is a significant barrier. It requires knowledge of both Latex and a certain way of using diff. There are many, many Python users -- especially Python-on-Windows -- who are not familiar with these technologies and don't have the time to learn them for the sole purpose of making a contribution to the documentation. > As a reader, I > prefer properly written and edited and officially approved documentation to > ten pages of advice from people I don't know ... I agree. But there are gaps in the documentation, where the officially approved documentation is silent. In such cases, I prefer advice from others, even though I've never met them, to no help at all. After all, what is comp.lang.python except advice from people that you've (for the most part) never met. :-) > I've never felt that the Python documentation was particularly lacking... In general, I'd agree that the Python documentation is outstanding. But there are gaps -- a qualifying phrase here, a missing reference there, a small example in many places. Filling those gaps would make the difference in those places between documentation that is just barely adequate and documentation that is really excellent. For experienced Pythonistas, this difference may be merely a minor matter of convenience, but for newbie Pythonistas this may be the difference between usable and not usable. And we want to support newbies. We want to attract as many of them as possible. The larger the newbie population today, the larger the active, experienced Python community tomorrow. And remember, it is the newbies who are finding the problems in the documentation... they are the ones reading it, because they are the ones that need it. As newbies, they may not yet be masters of all the supporting technologies we use (see my earlier point about the technical barriers being too high), but they are certainly the people in the best position to find gaps in the documentation and to supply material that others would find useful. WE NEED TO MAKE IT EASIER FOR MANY HANDS -- INCLUDING NEWBIE HANDS -- TO CONTRIBUTE TO THE DOCUMENTATION. The PHP model is a good one. Many hands contribute online. Periodically, expert hands incorporate the best of the online contributions into the mainline docs. From shalabh at cafepy.com Fri May 21 16:07:47 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Fri, 21 May 2004 13:07:47 -0700 Subject: Scaling on multi-processor machine References: <095A307E4B8A1541B29248EABD4D4D40073065CB@exchange-lax1.firstlogic.com> Message-ID: Atul Kshirsagar wrote: > Hello, > GIL prevents my C++ application embedding and extending python to scale > even though I spawn multiple C++ threads. I read lot of references on > internet about using multiple processes rather than threads. > > In that direction I was searching for some examples/resources/tools which > can help me create multi-process implementation. My application does need > to pass userdefined class objects to python interpreter. So I guess my > implementation is going to need a protocol to marshal, de-marshal python > objects between processes or use shared memory. > > Does anyone here know of any examples/tools to implement the > multi-processes approach with the object/data transfer between the > processes ? I haven't done anything similar myself but I can give a few pointers: http://twistedmatrix.com/products/spread http://poshmodule.sourceforge.net/ -- Shalabh From imbosol at aerojockey.invalid Fri May 7 01:13:48 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 07 May 2004 05:13:48 GMT Subject: Scope rule pecularities References: Message-ID: Donn Cave wrote: > > > In article , > Antoon Pardon wrote: > ... >> Beside you missed the point. I don't need solutions, I know the >> work arounds to make it work. The point is that although a += b >> is supposed to be syntactic sugar for a.__iadd__(b), you need >> a global (and even that won't help if you have nested functions >> and the a is on an intermediate level) to make the first work >> but not for the second. > > += is a bit of a wart. The only value in it is that you can > execute this read-and-modify sequence with a single access in > some cases where accesses matter because of side effects. > (Single access higher up in an expression - e.g., if we have > a[0][0] += 1, you skip an a[0].) If that seems like a silly > reason to take on this abominable kludge, I'm probably not > explaining it well - wasn't my idea. There is one other little benefit: it lets you avoid having to type and maintain two identical expressions. I kind of felt the same way you did until one day I had to write a bunch of assignments looking like this: cell[4*(i+1)+j+1].wallratio[k] = cell[4*(i+1)+j+1].wallratio[k] - 0.1 (It was for a rogue-like game BTW. Yes, if -= didn't exist, of course I would set w = cell[4*(i+1)+j+1].wallratio and use w[k] = w[k] - 0.1 today. Using -= is still an improvement over that.) One other thing: for things like Numerical Python, where efficiency matters, using += is usually faster than +. That is, a[:] = c, a += b, is faster than a[:] = c+b. A lot of nice little reasons to have it so I wouldn't call it a kludge and certainly not abominable. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From roy at panix.com Thu May 27 09:31:49 2004 From: roy at panix.com (Roy Smith) Date: Thu, 27 May 2004 09:31:49 -0400 Subject: How to list all functions in an imported module? References: <889cbba0.0405270506.3cd91d26@posting.google.com> Message-ID: In article <889cbba0.0405270506.3cd91d26 at posting.google.com>, klachemin at home.com (Kamilche) wrote: > I can't figure out how to list all functions from an imported module. > I searched Google, but all the answers I found didn't work. Did > something change in Python 2.2, perhaps there's a new method of doing > it? I would start with "dir (moduleName)" From grante at visi.com Sat May 1 13:27:30 2004 From: grante at visi.com (Grant Edwards) Date: 01 May 2004 17:27:30 GMT Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> Message-ID: <4093de02$0$17252$a1866201@newsreader.visi.com> In article , Peter Hansen wrote: >>>You can't get greater then 1ms accuracy when measuring a time >>>on todays machines, and that will be less when measuring time >>>over a network... >> >> Not sure what you mean by "todays machines", but on a >> Pentium-class machine running Linux, you get approx 1us >> resolution with calls to time.time(): > > Keep in mind the difference between "accuracy" and > "resolution" (or "precision"). I do. Not only do you get 1us resolution, you get packet timestamp _accuracy_ to well under 1ms according to tests I've run comparing packet timestamps against an oscilloscope trace. Delta-T accuracy of calls to time() are accurate to 1us as well. Absolute accuracy depends on how you set your system clock. Running NTP with in-kernel FLL control of the system tick will generally allow you to maintain absolute accuracies of under 100us. > I think Knio is probably right that, unless you are running on > a realtime OS, you won't be able to guarantee anything better > than 1ms accuracy, and quite probably not even that. Under Linux, I can guarantee you the answer you get back from time.time() is accurate to 1us. However, it is a multitasking system, and there are other things running. While it's easy to _determine_ exactly when you called time.time(), it's difficult to _control_ the point in time when you call time.time(). When your task does get a chance to run, and you do get to call time.time(), you'll generally get a result accurate to 1us. If I do a busy-wait loop with nothing else running, I've been able to accurately measure pulsewidths of a few microseconds under Linux using the gettimeofday() call (which I believe is what time.time() calls. As soon as there are other ready tasks, the accuracy of the measurement quickly deteriorates to tens of millisconds due to scheduling latencies. -- Grant Edwards grante Yow! It's today's SPECIAL! at visi.com From fourier at interia.pl Sun May 23 03:31:48 2004 From: fourier at interia.pl (Rafal Biegacz) Date: Sun, 23 May 2004 09:31:48 +0200 Subject: (no subject) Message-ID: From della at toglimi.linux.it Tue May 25 14:19:18 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Tue, 25 May 2004 18:19:18 GMT Subject: Update with pickle In-Reply-To: References: Message-ID: Nicolas Fleury wrote: >> I don't get what you want to do. Can you explain yourself better? What >> do you mean by "updating" an object? > Use the same reference instead of creating a new instance. Basically > making pickle call __init__ of an existing object. The best solution I > see for now is to copy the __dict__ of the new object to the existing > one. I want to update the content of an object with a dumped object of > the same type so that all reference to existing object are still valid. I think it's not possible to do automatically. Beware of copying __dict__, since starting with python 2.2, it's possible to have data that doesn't reside in __dict__, for instance when using __slots__. I guess you have to find a way to encapsulate information, and maybe a proxy could be OK for you (I can't find the recipe in the Python Cookbook right now, since it appears to be down). That way, you could keep all references to the proxy, and change the encapsulated data when you need it. -- Ciao, Matteo From aahz at pythoncraft.com Sat May 15 15:52:11 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2004 15:52:11 -0400 Subject: Test error with Python 2.3.4c1 References: Message-ID: In article , Berthold H?llmann wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , Berthold H=F6llmann > wrote: >>> >>>The error desribed in SF error report No. 870120 (segmentation fault >>>in test_re) still persists for me in 2.3.4c1. >> >> Is there a patch for it? Bugfix releases are mostly low-effort >> collections of patches that already exist -- there's not much attempt >> made to call for new patches before the release goes out. All that >> bugfix release candidates are intended to do is make sure that no new >> bugs have been created. > >The patch working for me is to reduce the default USE_RECURSION_LIMIT > >diff Modules/_sre.c~ Modules/_sre.c >98c98 >< #define USE_RECURSION_LIMIT 10000 >--- >> #define USE_RECURSION_LIMIT 6835 In that case, you should check against the CVS version of Python; I believe there've been some changes that affect this kind of thing. If that fixes your problem, please close the bug report. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From dd55 at cornell.edu Mon May 3 23:28:42 2004 From: dd55 at cornell.edu (Darren Dale) Date: Mon, 3 May 2004 23:28:42 -0400 Subject: is it possble to run a script from the python shell? Message-ID: If so, how is it done? This is probably a stupid question. But when I os.chdir into a directory that I know contains a python file, when I try to call it >>>color_demo.py I get NameError: name color_demo is not defined Thanks, Darren From news at outbacklinux.com Tue May 18 07:01:44 2004 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 18 May 2004 20:31:44 +0930 Subject: pexpect module References: Message-ID: <40a9eca3$1@duster.adelaide.on.net> First of all, look up the manual for Cisco's 'show' command. See if there is a way to turn off the paging. If not, try to fool cisco into thinking you have a very large page size on your terminal (e.g. 10,000 lines). If this is not possible, you can loop in your python script -: while 1: i=child.expect('--More--',pexpect.TIMEOUT) if i==0: child.sendline(' ') else: break Adrian. Gianluca Trombetta wrote: > hmmm, i'm not so stupid...:-). > The command ls -l | more was an example...i'm not really need to run ls -l > | more in an automate program. > But I need to run some cisco commands like "show ip bgp summary", this > command print a table and put a "More" by default, if the table is too big > for a single terminal screen. > So I need to remove this behavior because if I match the " --More-- " with > expect module i can match only the first one "More", then this the program > crash and receives a timeout. > > Hi > Gianluca > > > > "Lee Harr" ha scritto nel messaggio > news:P9Lpc.5055$xg3.4383 at news01.roc.ny... >> On 2004-05-14, Gianluca Trombetta wrote: >> > Someone know pexpect module? >> > I've a problem working with it... >> > >> > I need to run some commands on remote hosts, like ls, df -k etc..All > right. >> > Although, when i launch a command that have a "more" inside, i don't > know >> > what i must expect! >> > An example: >> > >> > if i want to run an "ls -l | more" on a remote host, it don't return me > a >> > prompt, but a "-------------More-------------"...thus i don't know how > much >> > this. >> > >> >> >> The only reason I can see for piping the command through more would >> be if there were a person sitting there wanting to read the output >> before going on to read the next page of output. That seems counter >> to the idea of using pexpect to automate the process. Do you >> really need to pipe through more? >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From rogerb at rogerbinns.com Wed May 5 19:45:29 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 5 May 2004 16:45:29 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? References: <109i81e6lmpj623@corp.supernews.com> Message-ID: Michael Geary wrote: > Asking for patches and comments via Sourceforge is nowhere near as effective > as having a comment box right on the doc page. Someone has to be really > motivated to take the trouble to go to SF to submit a comment. Not only that, there is a many month if not year lead time between supplying information via SF and actually having the results available (the next release of Python). The PHP docs give instant gratification. I know I am significantly less likely to contribute to projects the longer the lead time between me making a contribution and the results being available. Roger From tim.one at comcast.net Thu May 27 02:41:45 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 27 May 2004 02:41:45 -0400 Subject: why learn In-Reply-To: <40b58695_1@news.iprimus.com.au> Message-ID: [mr_vocab] > hey i finished working through alot of python stuff and no a fair bit bout > it > > now what can i do with it??? Follow your bliss: in your case, it looks like you'd really enjoy writing a program to post the same question 100 times. It's a lot easier to write a program for that than to stay up all night doing it by hand . From dmq at gain.com Mon May 24 18:11:51 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 15:11:51 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405181600.3b6d6373@posting.google.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> <16752bcc.0405230518.2023328a@posting.google.com> <16752bcc.0405240201.7eede57@posting.google.com> Message-ID: On 24 May 2004 03:01:17 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:... >> I've posted these examples on our webpage at >> http://ece.arizona.edu/~edatools/Python/Examples Let me know if I >> should make any changes. These will be very helpful for students to >> see alternative styles in programming. >> >> -- Dave > >*Shakes head* OK, one change; please change the word synonyms to >anagrams in the text of the programs as well. :) When I write a >program which can algorithmically detect synonyms it'll be really >something... Done. You can send me an email for little stuff like this that might not interest the group. -- Dav From me at privacy.net Wed May 12 08:30:27 2004 From: me at privacy.net (Duncan Booth) Date: 12 May 2004 12:30:27 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: Kirk Job-Sluder wrote in news:slrnca3t0e.2asc.kirk at eyegor.jobsluder.net: > I'll be more specific about the challenge. Using only stock python with > no added modules, give me a script that pretty-prints a > character-delimted file using one variable assignment, and one function. > > Here is the solution in awk: > BEGIN { FS="\t" } > {printf("%s %s %s %s", $4, $3, $2, $1)} > > > One assignment statement and one function call is easy. Of course, you could argue that more than one name gets rebound, but then that is also true of the awk program: import sys for line in sys.stdin: line = line[:-1].split('\t') print "%s %s %s %s" % (line[3], line[2], line[1], line[0]) While I agree with you that using the appropriate tool is preferred over using Python for everything, I don't really see much to choose between the Python and awk versions here. From kveretennicov at yahoo.com Thu May 20 06:30:27 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 20 May 2004 03:30:27 -0700 Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> Message-ID: <5155aad2.0405200230.1899e3be@posting.google.com> Carl Banks wrote in message news:<38Yqc.166$eO6.128 at fe2.columbus.rr.com>... > > There's more like it, e.g. the existence of the > > locals() dictionary and the ability to modify it. > > New feature? I didn't think modifying the dict returned by locals > affected the variables. > Evidence of crime :) Python 2.3.2 >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> locals()['x'] = 1 >>> x 1 Not to mention stack frame magic available via inspect.*... - kv From noemail at noemail4u.com Tue May 18 09:13:15 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Tue, 18 May 2004 13:13:15 GMT Subject: Timer events References: <93dqc.15615$gr.1409242@attbi_s52> Message-ID: <23f923c6a04de354f78e218effbf6341@news.teranews.com> On Tue, 18 May 2004 00:48:05 GMT, "EAS" wrote: >While this topic is still up, can someone look at my program and tell me how >to keep the total time in one place? (meaning updating it instead of >printing it each time.) [snip] > print h, ":", m, ":", s [snip] This works on the Windows machine I'm using; I don't have a Unix box handy: Change: print h, ":", m, ":", s to: print h, ":", m, ":", s, '\x0d', or: print "%02d:%02d:%02d\x0d" % (h, m, s), By putting a comma at the end, the cursor doesn't move to the next line. By making the carraige return character the last thing to print, the cursor moves to the start of the current line. The next time the time is displayed, it overwrites the previous value, making it look like it stays in place. If you're running inside of an IDE, I have no idea if this will work for you. --dang From stephen.mcphail at casaccia.enea.it Fri May 28 06:06:33 2004 From: stephen.mcphail at casaccia.enea.it (byte biscuit) Date: Fri, 28 May 2004 12:06:33 +0200 Subject: Fortran-compiled DLLs in Python References: Message-ID: I feel we're getting there... recapitulating: >>> from ctypes import * >>> h2o = windll.H2O # loads DLL in python >>> tt=c_double(20.) # tt, pp and state are inputs, given values in C datatypes >>> pp=c_double(1.0) >>> state=c_int(1) >>> dierr = c_int() #dierr, sig and prop are outputs, initialised in C datatypes >>> sig = c_double() >>> prop = (c_double * 16)() # create a 16 element double array access violation error: >>> h2o.WATER(tt, pp, state, byref(dierr), byref(sig), prop) Traceback (most recent call last): File "", line 1, in ? WindowsError: exception: access violation which in fact - Dennis - is caused by non-referencing, because: >>> h2o.WATER(byref(tt), byref(pp), byref(state), byref(dierr), byref(sig), prop) returns without error. It is interesting (for me, that is) to note that prop in fact does NOT need referencing, whereas all other variables (input&output) DO. But, the returned answer is: 0 which shouldn't be of course............... so there does seem to be a problem in the definition/passing of the prop parameter, I would say? stephen "Thomas Heller" ha scritto nel messaggio news:mailman.362.1085666603.6949.python-list at python.org... > > > > This is the classical GP fault, which would normally crash a program. > ctypes catches it, but doesn't give more information (in current CVS, it > would have informed you about which memory location could not be written > or read, but that would probably not help you very much). > > > - Prop (datatype: double precision array[16 elements]) [output] > > I do not know how fortran passes this parameter, in the example code I > posted I assumed that the caller allocates an array, passes a pointer to > it to fortran, and the fortran code fills in the elements. > > Do you have C sample code that works? > > Thomas > "Dennis Lee Bieber" ha scritto nel messaggio news:p00cb0hvqdj9u9ar7jddgr9qcpnra8im6k at 4ax.com... > C passes by value, and to get a "modifiable" argument, the programmer has to explicitly pass an address (as the value) and then, also, explicitly dereference through the value. Traditionally, FORTRAN passes ALL arguments by address, not value. This may vary a bit in more modern implementations -- character strings may pass a "string descriptor", which is a structure containing the address of the string (as normal) along with an added word containing the size of the space allocated for the string. I suspect you need to use byref() on all of the arguments. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Home Page: < > Overflow Page: < From peter at engcorp.com Thu May 13 13:13:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 13:13:11 -0400 Subject: make faster Richards benchmark In-Reply-To: <6748553f.0405130833.2bf7d912@posting.google.com> References: <6748553f.0405122211.5be5a150@posting.google.com> <873c64zpu7.fsf@blakie.riol> <6748553f.0405130833.2bf7d912@posting.google.com> Message-ID: Duncan Lissett wrote: > Wilk wrote in message news:<873c64zpu7.fsf at blakie.riol>... > >>dlissett0 at yahoo.com (Duncan Lissett) writes: >> >> >>>I'd appreciate any suggestions on how to make faster Python >>>implementations of Richards benchmark. Perhaps there are obvious >>>problems that can be corrected? >>> >>>http://www.lissett.com/ben/bench1.htm >> >>import psyco >>psyco.full() >> >>2 times faster :-) > > And Simon: "I just tried the benchmark with Psyco, and cut the run > time for input=10000 from 8.1 seconds to 3.4" > > Joseph, Simon, Wilk: thanks for the Psyco suggestion, and special > thanks for going ahead and trying it - we get slightly better than x2. What platform is this on? On WinXP, with an AMD 2500+ chip, and lots of memory etc., I'm still getting only 38% speedup, nowhere near 100%... -Peter From __peter__ at web.de Mon May 10 09:24:49 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 May 2004 15:24:49 +0200 Subject: newbie question - remove a module from ram References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> Message-ID: Paul McGuire wrote: > "john fabiani" wrote in message > news:4AAnc.6791$dH5.4946 at newssvr27.news.prodigy.com... >> Hi, >> >> I believe I have good understanding of import but it occurred to me that >> I might want to remove an imported module. I.e I load a module into ram >> and I no longer need the module. Modules just stays in ram? In the >> windows world I would "thisform.release()" and the garbage collector >> would release the ram. So did I miss something or is there no release >> method. How about a method within a class like destroy()? >> >> I just got to believe it's there???? But where? >> John > > Well, you were pretty close with calling something like .release(). Use > the del statement. > >>>> import random >>>> print random.random() > 0.475899061786 >>>> del random >>>> print random.random() > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'random' is not defined >>>> and then >>> import sys >>> sys.modules["random"].random() 0.43459738002826365 >>> should make it clear that (next to) no memory is freed in the process. Peter From mrjean1 at comcast.net Tue May 25 01:26:34 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 25 May 2004 05:26:34 GMT Subject: Useful? __slots__ for functions References: Message-ID: <240520042236356939%mrjean1@comcast.net> [[ This message was both posted and mailed: see the "To," "Cc," and "Newsgroups" headers for details. ]] Nick, I do not know the answer to your question, but the impact of __slots__ is very significant. Below is a message I posted a few weeks ago. In addition to being faster (to create) and smaller, __slots__ objects have another major advantage, at least in my view. They are 'frozen' and can not be extended dynamically, not intentionally and -even more importantly- not by accident. There are situations where the latter is a major benefit, for example in applications where extensibility is not a requirement. /Jean Brouwers ProphICy Semiconductor, Inc. > Path: attbi_s04!attbi_s03!attbi_s01!attbi_s02!attbi_slave12!attbi_master11!wn14feed!worldnet.att.net!199.218.7.141!news.glorb.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local1.nntp.dca.giganews.com!nntp.comcast.com!news.comcast.com.POSTED!not-for-mail > NNTP-Posting-Date: Wed, 12 May 2004 15:05:16 -0500 > Subject: __slots__ vs __dict__ > Date: Wed, 12 May 2004 13:14:48 -0700 > From: Jean Brouwers > Newsgroups: comp.lang.python > Reply-To: JBrouwers at ProphICy.com > Message-ID: <120520041314481389%JBrouwers at ProphICy.com> > MIME-Version: 1.0 > Content-Type: text/plain; charset=ISO-8859-1 > Content-transfer-encoding: 8bit > User-Agent: Thoth/1.7.2 (Carbon/OS X) > Lines: 209 > NNTP-Posting-Host: 67.161.46.201 > X-Trace: sv3-IgpWl13JKku68lEaAxfUeuMDddQ2Hb+wpcL1Xy3D1hWFRMKqKkQK8oYKWO6fJa6w0ibSPg2HtHvHitY!pbEuqBO6sUAMUZawbd1zxH3XYX1WmCBcg/PRch8EUhprgUWBOELz1iGE9uwWRe93JDJDgO8= > X-Complaints-To: abuse at comcast.net > X-DMCA-Complaints-To: dmca at comcast.net > X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers > X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly > X-Postfilter: 1.1 > Xref: attbi_master11 comp.lang.python:158864 > X-Received-Date: Wed, 12 May 2004 20:05:16 GMT (attbi_s04) > > > Classes using __slots__ seem to be quite a bit smaller and faster > to instantiate than regular Python classes using __dict__. > > Below are the results for the __slots__ and __dict__ version of a > specific class with 16 attributes. Each line in the tables shows the > number of instances created so far, the total memory usage in Bytes, > the CPU time in secs, the average size per instance in Bytes and the > average CPU time per instance in micseconds. > > Instances of this particular class with __slots__ are almost 6x > smaller and nearly 3x faster to create than intances of the __dict__ > version. Results for other classes will vary, obviously. > > Comments? > > /Jean Brouwers > ProphICy Semiconductor, Inc. > > > PS) The tests were run on a dual 2.4 GHz Xeon system with RedHat > 8.0 and Python 2.3.2. The test script is attached but keep in mind > that it only has been tested on Linux. It will not work elsewhere > due to the implementation of the memory() function. > > > testing __slots__ version ... > 4096 insts so far: 3.0e+05 B 0.030 sec 73.0 B/i 7.3 usec/i > 8192 insts so far: 8.8e+05 B 0.070 sec 107.5 B/i 8.5 usec/i > 16384 insts so far: 1.5e+06 B 0.150 sec 92.2 B/i 9.2 usec/i > 32768 insts so far: 3.3e+06 B 0.280 sec 101.0 B/i 8.5 usec/i > 65536 insts so far: 6.6e+06 B 0.560 sec 101.2 B/i 8.5 usec/i > 131072 insts so far: 1.4e+07 B 1.200 sec 103.4 B/i 9.2 usec/i > 262144 insts so far: 2.7e+07 B 2.480 sec 103.4 B/i 9.5 usec/i > 524288 insts so far: 5.5e+07 B 5.630 sec 104.0 B/i 10.7 usec/i > 1048576 insts so far: 1.1e+08 B 13.980 sec 104.0 B/i 13.3 usec/i > 1050000 insts total: 1.1e+08 B 14.000 sec 103.9 B/i 13.3 usec/i > > > testing __dict__ version ... > 4096 insts so far: 2.4e+06 B 0.050 sec 595.0 B/i 12.2 usec/i > 8192 insts so far: 4.6e+06 B 0.090 sec 564.5 B/i 11.0 usec/i > 16384 insts so far: 9.5e+06 B 0.180 sec 581.8 B/i 11.0 usec/i > 32768 insts so far: 1.9e+07 B 0.370 sec 582.2 B/i 11.3 usec/i > 65536 insts so far: 3.8e+07 B 0.830 sec 582.6 B/i 12.7 usec/i > 131072 insts so far: 7.6e+07 B 1.760 sec 582.7 B/i 13.4 usec/i > 262144 insts so far: 1.5e+08 B 4.510 sec 582.8 B/i 17.2 usec/i > 524288 insts so far: 3.1e+08 B 12.820 sec 582.8 B/i 24.5 usec/i > 1048576 insts so far: 6.1e+08 B 38.370 sec 583.1 B/i 36.6 usec/i > 1050000 insts total: 6.1e+08 B 38.380 sec 583.1 B/i 36.6 usec/i > > > -------------------------------slots.py------------------------------- >
> 
> from time import clock as time_clock
> def cputime(since=0.0):
>     '''Return CPU in secs.
>     '''
>     return time_clock() - since
> 
> 
> import os
> _proc_status = '/proc/%d/status' % os.getpid()  # Linux only
> _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
>           'KB': 1024.0, 'MB': 1024.0*1024.0}
> 
> def _VmB(VmKey):
>     global _scale
>     try: # get the /proc//status pseudo file
>         t = open(_proc_status)
>         v = [v for v in t.readlines() if v.startswith(VmKey)]
>         t.close()
>          # convert Vm value to bytes
>         if len(v) == 1:
>            t = v[0].split()  # e.g. 'VmRSS:  9999  kB'
>            if len(t) == 3:  ## and t[0] == VmKey:
>                return float(t[1]) * _scale.get(t[2], 0.0)
>     except:
>         pass
>     return 0.0
> 
> def memory(since=0.0):
>     '''Return process memory usage in bytes.
>     '''
>     return _VmB('VmSize:') - since
> 
> def stacksize(since=0.0):
>     '''Return process stack size in bytes.
>     '''
>     return _VmB('VmStk:') - since
> 
> 
> 
> def slots(**kwds):
>     '''Return the slots names as sequence.
>     '''
>     return tuple(kwds.keys())
> 
>  # __slots__ version
> class SlotsClass(object):
>     __slots__ = slots(_attr1= False,
>                       _attr2= None,
>                       _attr3= None,
>                       _attr4= None,
>                       _attr5= None,
>                       _attr6= None,
>                       _attr7= 0,
>                       _attr8= None,
>                       _attr9= None,
>                       _attr10=None,
>                       _attr11=None,
>                       _attr12=None,
>                       _attr13=None,
>                       _attr14=None,
>                       _attr15=None,
>                       _attr16=None)
> 
>     def __init__(self, tuple4, parent):
>         self._attr1 = False
>         self._attr2 = None
>         self._attr3 = None
>         self._attr4 = None
>         self._attr5 = None
>         self._attr6 = None
>         if parent:
>             self._attr7  = parent._attr7 + 1
>             self._attr8  = parent._attr8
>             self._attr9  = parent._attr9
>             self._attr10 = parent
>             self._attr11 = parent._attr11
>             self._attr12 = parent._attr12
>         else:
>             self._attr7  = 0
>             self._attr8  = None
>             self._attr9  = None
>             self._attr10 = None
>             self._attr11 = self
>             self._attr12 = None
>         self._attr13, self._attr14, self._attr15, self._attr16 = tuple4
> 
> 
>  # __dict__ version
> class DictClass(object):
>     _attr1 = None
>     _attr2 = None
>     _attr3 = None
>     _attr4 = None
>     _attr5 = None
>     _attr6 = None
>     _attr7  = 0 
>     _attr8  = None
>     _attr9  = None
>     _attr10 = None
>     _attr11 = None
>     _attr12 = None
>     _attr13 = None
>     _attr14 = None
>     _attr15 = None
>     _attr16 = None
> 
>     def __init__(self, tuple4, parent):
>         if parent:
>             self._attr7  = parent._attr7 + 1
>             self._attr8  = parent._attr8
>             self._attr9  = parent._attr9
>             self._attr10 = parent
>             self._attr11 = parent._attr11
>             self._attr12 = parent._attr12
>         else:
>             self._attr11 = self
>         self._attr13, self._attr14, self._attr15, self._attr16 = tuple4
> 
> 
> if __name__ == '__main__':
> 
>     import sys
> 
>     def report(txt, n, b0, c0):
>         c = cputime(c0);
>         b = memory(b0)
>         print "%8d insts %s: %8.1e B %7.3f sec %6.1f B/i %6.1f usec/i" \
>                % (n, txt, b, c, b/n, 1.0e6*c/n)
> 
>     if not sys.platform.startswith('linux'):
>         raise NotImplementedError, "%r not supported" % sys.platform
> 
>     if 'dict' in sys.argv[1:]:
>         print 'testing __dict__ version ...'
>         testClass = DictClass
>     else:
>         print 'testing __slots__ version ...'
>         testClass = SlotsClass
> 
>     t4 = ('', 0, 0, [])
>     b0 = memory()
>     c0 = cputime()
>     p = testClass(t4, None)
>     n, m = 1, 4096
>      # generate 1+ M instances
>     while n < 1050000:  # 1048576:
>         p = testClass(t4, p)
>         n += 1
>         if n >= m:  # occasionally print stats
>             m += m
>             report('so far', n, b0, c0)
>     report(' total', n, b0, c0)
> 
> 
In article , Nick Jacobson wrote: > The __slots__ attribute of new-style classes can reduce memory usage > when there are millions of instantiations of a class. > > So would a __slots__ attribute for functions/methods have a similar > benefit? i.e. could a function using __slots__ use significantly less > memory, and therefore run faster, if called millions of times? > > If so, it will hopefully be in a future version of Python. From ny_r_marquez at yahoo.com Fri May 28 09:18:06 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 28 May 2004 06:18:06 -0700 Subject: Transparent PNG and PIL References: <8a27e309.0405260724.5a9c1fdc@posting.google.com> <8a27e309.0405270602.6d0e8f59@posting.google.com> Message-ID: <8a27e309.0405280518.19cbd269@posting.google.com> "Fredrik Lundh" wrote: > "transparency", not "trasparency". Oh. I forgot that Python is not only case sensitive but spell sensitive as well. :o) Thank you. -Ruben From Joseph.V.Laughlin at boeing.com Tue May 11 16:18:03 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Tue, 11 May 2004 13:18:03 -0700 Subject: Python security settings Message-ID: <67B3A7DA6591BE439001F27362333512028772DA@xch-nw-28.nw.nos.boeing.com> import SimpleXMLRPCServer rpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 3010)) print "XMLRPC Server started!" rpc_server.serve_forever() When I run this program, I can connect to port 3010 on the localhost, but I can't connect to the port from any other machine (or from the local machine using the machine's hostname). Why is this? Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From cookedm+news at physics.mcmaster.ca Wed May 12 12:00:29 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 12 May 2004 12:00:29 -0400 Subject: Can Python be compiled by a C++ compiler ? References: <40A242B8.30703@skynet.be> Message-ID: At some point, Helmut Jarausch wrote: > Hi, > > having read http://www.python.org/doc/current/ext/ext.html by Guido > van Rossum and Fred Drake, > I got the impression I should compile Python with g++ since section 1.11 > indicates that otherwise the constructor of a global or static object > (of an extension in C++) won't be called. > > Now trying to build Python (CVS version) with g++ fails. E.g., one > problem is in Parser/pgen.c line 364 with a typical C-like confusion > of types and variables when it declares > > ss_arc *ss_arc > where ss_arc is defined by a previous typedef. A C++ compiler won't > accept this. > > Do I miss something? Yes. Just specify the C++ compiler to the configure script with the --with-cxx option. My guess it already does this automatically, and you're just making more work for yourself. Everything will be compiled with the C compiler (gcc), but will be linked by the C++ compiler. This assures that the appropiate run-time stuff needed for C++ extensions is linked in (or something like that), without actually having to rewrite Python in C++. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From buzzard at urubu.freeserve.co.uk Thu May 27 19:02:41 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 28 May 2004 00:02:41 +0100 Subject: Can someone help me with this bug? References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:c95gsa$492$04$1 at news.t-online.com... > Duncan Smith wrote: > > > I'm probably missing something that should be obvious, but can > > anyone tell me what's wrong with the following? > > > > temp.py > > --------------------------------------------------------------------- > > > > class Item(object): > > def __init__(self, id, data): > > self.id = id > > self.data = data > > > > > > class KeyedSet(dict): > > def __init__(self, items=None): > > if items is not None: > > for item in items: > > self[item.id] = item > > > > def __iter__(self): > > return self.itervalues() > > > > def __repr__(self): > > return '%s(%r)' % (self.__class__.__name__, self.keys()) > > > > def __contains__(self, item): > > return self.has_key(item.id) > > > > def intersection(self, other): > > res = self.__class__() > > for item in self: > > if item in other: > > res[item.id] = item > > return res > > > > def __and__(self, other): > > return self.intersection(other) > > > > def intersection_update(self, other): > > self &= other > > > > def __iand__(self, other): > > self = self.intersection(other) > > return self > > -------------------------------------------------------------------- > > > >>>> from temp import Item, KeyedSet > >>>> a = Item(0, 'W') > >>>> b = Item(1, 'X') > >>>> c = Item(2, 'Y') > >>>> d = Item(3, 'Z') > >>>> aset = KeyedSet([a, b, c]) > >>>> bset = KeyedSet([b, c, d]) > >>>> aset &= bset > >>>> aset > > KeyedSet([1, 2]) > >>>> aset = KeyedSet([a, b, c]) > >>>> aset.intersection_update(bset) > >>>> aset > > KeyedSet([0, 1, 2]) > >>>> > > > > I can't figure out why 'aset' is unchanged? Thanks. > > Your problem stripped down to the bare bones: __iand__() creates a new > instance instead of modifying the current one. > > self = something > > doesn't copy something's data to self, it just rebinds self to something for > the rest of the method. > > A minimal example of what went wrong: > > >>> class A: > ... def __init__(self, value): > ... self.value = value > ... def __iand__(self, other): > ... return A(self.value + other.value) > ... def __repr__(self): > ... return "value=%s" % self.value > ... > >>> a = b = A(1) > >>> a &= A(2) > > It looks like inplace modification, but isn't: > > >>> a, b > (value=3, value=1) > > a is rebound to the newly created instance, which tricks you into believing > it was modified. The backup reference b reveals the error. > Here's the correction (I'm lazy, so I reuse the unaltered parts of A): > > >>> class B(A): > ... def __iand__(self, other): > ... self.value += other.value > ... return self > ... > >>> a = b = B(1) > >>> a &= B(2) > >>> a, b > (value=3, value=3) > > Once you understand the basic principle, it should be no problem to apply it > to your KeyedSet class. If in doubt, use the sets.Set implementation as a > template. > > Peter > Yep. This also explains why the other unit tests involving __iand__ passed, leaving me thinking it was OK. Cheers. Duncan From della at toglimi.linux.it Fri May 28 13:34:48 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Fri, 28 May 2004 17:34:48 GMT Subject: "Private" Member Variables In-Reply-To: References: Message-ID: Scott Brady Drummonds wrote: > What are your thoughts? How much privacy should I build into my code? > Should I be using variables beginning with "__" and accessors? Or is that > simply not necessary (or normal) in Python code? The motto here is "we are all consenting adults". If the class users need to access a variable, then why not make it directly available? If you later notice that you'd need an accessor method, since the value of the "variable" has got to be precomputed, then use properties[1]. For instance: class Rectangle(object): def __init__(self, b, h): self.b, self.h = b, h def get_area(self): return self.b * self.h area = property(get_area) In this case the property is read-only, but you can also put a setter if you need it. [1] You need new-style classes for properties, so make sure you inherit from object or one of its descendants. -- Ciao, Matteo From hugo_mesquita at hotmail.com Tue May 4 14:41:22 2004 From: hugo_mesquita at hotmail.com (Fernando) Date: Tue, 04 May 2004 18:41:22 GMT Subject: IDE for Python References: Message-ID: dont bother wrote: > Hi Guys: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but > to my surprise its just an editor. I guess it cannot > even compile my code in python or maybe I am wrong. > Any ideas/recommendations for a free IDE for Python > Thanks > Dont > > > > > __________________________________ > Do you Yahoo!? > Win a $20,000 Career Makeover at Yahoo! HotJobs > http://hotjobs.sweepstakes.yahoo.com/careermakeover Hi there, check this one out: http://www.die-offenbachs.de/detlev/eric3.html From ville at spammers.com Thu May 6 01:36:50 2004 From: ville at spammers.com (Ville Vainio) Date: 06 May 2004 08:36:50 +0300 Subject: Ideas for Python 3 References: Message-ID: >>>>> "David" == David MacQuigg writes: David> In my humble opinion, GvR should have ignored the experts David> who told him lambdas were great, and just applied some David> simple common sense to find a better solution. Why don't we just let lambdas be? They got a bad rep because of the lack of lexical closures (and hence the default variable hack), but the issue is solved already. Lambdas work well enough for simple currying/whatever tasks, and don't really hurt anyone. -- Ville Vainio http://tinyurl.com/2prnb From info at aes-italia.it Wed May 26 12:34:58 2004 From: info at aes-italia.it (Annalisa Rea (AES Tel. 0775 830930)) Date: Wed, 26 May 2004 18:34:58 +0200 Subject: Trovato virus nel messaggio "Delivery (info@aes-italia.it)" Message-ID: <21B5C6C8D16ED511843F0050DA7C7DF20E4EB1@ITER01> Symantec AntiVirus ha trovato un virus in un allegato inviato da (python-list at python.org ) a info at aes-italia.it. Per garantire che i destinatari possano utilizzare i file inviati, eseguire una scansione dei virus, ripulire eventuali file infetti e inviare di nuovo l'allegato. Allegato: message.pif Nome virus: W32.Netsky.Q at mm Azione intrapresa: Ripulisci non riuscito : Quarantena riuscito : Stato file: Infetto -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1628 bytes Desc: not available URL: From jmeile at hotmail.com Thu May 13 03:57:28 2004 From: jmeile at hotmail.com (Josef Meile) Date: Thu, 13 May 2004 09:57:28 +0200 Subject: make faster Richards benchmark In-Reply-To: <6748553f.0405122211.5be5a150@posting.google.com> References: <6748553f.0405122211.5be5a150@posting.google.com> Message-ID: <40a33350$1@pfaff2.ethz.ch> Duncan Lissett wrote: > I'd appreciate any suggestions on how to make faster Python > implementations of Richards benchmark. Perhaps there are obvious > problems that can be corrected? > > http://www.lissett.com/ben/bench1.htm What's about including a second python implementation of the Richards benchmark using psyco? You don't have to modify your code, you only have to add two lines. It would be also interesting to see the differences between both source codes. Regards, Josef From matthiasjanes at gmx.net Fri May 7 23:37:58 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 7 May 2004 20:37:58 -0700 Subject: CGI Proplem displaying image Message-ID: Hi, Maybe someone of you can help me. I'm trying to display an image in memory(open file) with an cgi script - but it want work proberly: I'm running an Cgi webserver (CgiServerGui.py). both files are in the /cgi/ folder ################# #my CGISRIPT: test.py #! /usr/bin/env python print ("Content-type: image/jpeg"); print # End of headers! filename="cgi-bin//dog.jpg" infile = open(filename, 'rb') doginmemory=infile.read() print doginmemory ################## ################# #my html page with the image tag ################ I can't figure out whats the problem. funny: if I use a form with an method='post' I can get the picture show up in a whole webpage ( method='get' will not work) ########### ############ Any suggestion: (by the way: in the end the whole pictures should be stored in an sqlite database and also retrieved from it to be displayed within an html page. Thanks Matthias From s.brennan at cox.net Thu May 13 20:07:06 2004 From: s.brennan at cox.net (Shane) Date: Fri, 14 May 2004 00:07:06 GMT Subject: Python and Windows.Forms In-Reply-To: References: <87n08qrpcv.fsf@pobox.com> Message-ID: Thanks Larry, that was what I was hoping to hear. And thanks for the book suggestion; I'll be sure to look it up! Shane Brennan Larry Bates wrote: > Shane, > > You can access all the Windows common dialogs (forms?) > Python by using Win32 extensions. Specifically using > pywin.mfc dialog and win32ui modules. Here is an example > that I "hacked" from Demos directory. If this is > something you want to study more see Mark Hammond's > excellent Python Programming on Win32 book. > > HTH, > Larry Bates > Syscon, Inc. > > # > # Progress bar control example > # > # PyCProgressCtrl encapsulates the MFC CProgressCtrl class. To use it, > # you: > # > # - Create the control with win32ui.CreateProgressCtrl() > # - Create the control window with PyCProgressCtrl.CreateWindow() > # - Initialize the range if you want it to be other than (0, 100) using > # PyCProgressCtrl.SetRange() > # - Either: > # - Set the step size with PyCProgressCtrl.SetStep(), and > # - Increment using PyCProgressCtrl.StepIt() > # or: > # - Set the amount completed using PyCProgressCtrl.SetPos() > # > # Example and progress bar code courtesy of KDL Technologies, Ltd., Hong > Kong SAR, China. > # > > from pywin.mfc import dialog > import win32ui > import win32con > import time > > def MakeDlgTemplate(): > style = (win32con.DS_MODALFRAME | > win32con.WS_POPUP | > win32con.WS_VISIBLE | > win32con.WS_CAPTION | > win32con.WS_SYSMENU | > win32con.DS_SETFONT) > cs = (win32con.WS_CHILD | > win32con.WS_VISIBLE) > > w = 215 > h = 36 > > dlg = [["Progress bar", > (0, 0, w, h), > style, > None, > (8, "MS Sans Serif")], > ] > return dlg > > class TestDialog(dialog.Dialog): > def OnInitDialog(self): > rc = dialog.Dialog.OnInitDialog(self) > self.pbar = win32ui.CreateProgressCtrl() > self.pbar.CreateWindow (win32con.WS_CHILD | > win32con.WS_VISIBLE, > (10, 10, 310, 24), > self, 1001) > return rc > > def demo(): > d = TestDialog (MakeDlgTemplate()) > d.CreateWindow () > for i in xrange(100): > d.pbar.SetPos(i) > time.sleep(0.1) > > d.OnCancel() > > if __name__=='__main__': > demo() > > # $Header: /home/cvsroot/PyWin32/Pythonwin/pywin/Demos/progressbar.py,v 1.1 > 1999/09/01 23:33:35 mhammond Exp $ > > "Shane" wrote in message > news:sTAoc.67180$sK3.3272 at nwrddc03.gnilink.net... > >>Hey folks, >> >>I'm new to Python and programming in general and I'm having a blast. I >>was curious if it was possible to use Windows.Forms; I'm interesting in >>porting a C++ program a friend wrote for me to Python and would like to >>use a similar GUI (its fairly simple). I've noticed ActiveState has a >>.NET plugin for Python... >> >>http://www.activestate.com/Products/Visual_Python/?_x=1 >> >>...but I'm not sure that is what I am looking for and I'm stuck with >>Borland C# Builder Personal Edition anyway for financial reasons. >> >>One thing that threw me for a loop was that when I used ActivePython >>(ActiveStates Python IDE, I like it so far) to run a script I wrote, it >>gives me a Windows.Forms input box when I call raw_input as opposed to >>the regular console input message you get in the basic interactive >>window that comes with a standalone Pythin installation. What's going on >>there? Can I harness that a little more? >> >>Shane Brennan > > > From sholden at holdenweb.com Tue May 25 18:54:44 2004 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 May 2004 18:54:44 -0400 Subject: Problem with uudecode In-Reply-To: References: Message-ID: <38Qsc.182468$f_5.37708@lakeread01> Juho Saarikko wrote: > I made a Python script which takes Usenet message bodies from a database, > decodes uuencoded contents and inserts them as Large Object into a > PostGreSQL database. However, it appears that the to last few bytes > of uudecoded data are always mangled. Take a look of this hexdump output: > > Originals (decoded with Pan, each line is from a different file): > 000c2c0 e1bf 00ff 2541 a9e4 a724 d9ff > 0011a10 ff54 00d9 > 00093e0 fb4f a80d ffd9 c200 ffef 00d9 > > Decoded by the script: > 000c2c0 e1bf 00ff 2541 a9e4 a724 d0ff > 0011a10 ff54 00d8 > 00093e0 fb4f a80d ffd9 c200 ffef 00d8 > > As you can see, one of the last two bytes gets altered in all cases. > > The script also outputs the decoded file to disk for debugging purposes, > and the database large object and filesystem file match so it can't be a > PostGreSQL problem. > > So, if anyone has any idea what is wrong, please tell me ? I can't found > any reason why the bytes would get mangled... > > The script follows: > [...] I note that you are dumping words rather than bytes. Is it possible that the last byte isn't actually a part of the file, that endianness makes the last byte look like the penultimate byte, and that what you are seeing is simply noise? If not then it should probably be looked into ... regards Steve From andy at andybak.net Mon May 24 08:55:57 2004 From: andy at andybak.net (Andy Baker) Date: Mon, 24 May 2004 13:55:57 +0100 Subject: MSIE6 Python Question In-Reply-To: <22b7fd40.0405240325.7b2b6376@posting.google.com> Message-ID: The site might be checking your user-agent string. Urllib must allow you to choose what browser to identify itself as. Simply match the user-agent of known version of IE and see if that works. > -----Original Message----- > From: python-list-bounces+andy=andybak.net at python.org > [mailto:python-list-bounces+andy=andybak.net at python.org] On > Behalf Of Ralph A. Gable > Sent: 24 May 2004 12:25 > To: python-list at python.org > Subject: Re: MSIE6 Python Question > > "Kevin T. Ryan" wrote in message > news:<40b1697d$0$3131$61fed72c at news.rcn.com>... > > Ralph A. Gable wrote: > > > > > I'm a newbie at this but I need to control MSIE6 using Python. I > > > have read the O'Reilly win32 python books and got some > hints. But I > > > need to Navigate to a site (which I know how to do) and > then I need > > > to get at the source code for that site inside Python (as > when one > > > used the > > > View|Source drop down window). Can anyone point me to > some URLs that > > > would help out? Or just tell me how to do it? I would be very > > > grateful. > > > > I'm not sure why you need to go through IE, but maybe this will get > > you into the right direction: > > > > >>> import urllib > > >>> f = urllib.urlopen('http://www.python.org') > > >>> f.readline() > > ' > >>> f.readline() > > ' "http://www.w3.org/TR/html4/loose.dtd" >\n' > > >>> > > > > You could do: > > for line in f: > > process(line) > > > > just like you can with a file. Check the urllib, urllib2, > and other > > related modules (maybe httplib). Hope that helps. > > > Sorry. I forgot to mention that I have tried that. The data I > want is being stripped out when I access the URL via urllib. > I CAN see the data when I go into IE and do view source but > when I use urllib the site intentionally blanks out the > information I want. For that reason, I would like to get it > using IE6 if I can. If there are other ways to fake out the > site, I would be interested in that also. I thought that > perhaps the site was detecting the fact that I was not > querying it using a browser. I tried putting that into into > the HTTP messages but may not have done it right. At any rate > couldn't get that to work. It may be that the site is using > cookies to be sure someone is not getting the data. I haven't > pursued that. Again that is another reason I wanted to use > IE6 (since I know it works). The data is on a site to which I > subscribe to a service. But the particular information is > available to anyone if he/she types in the url (as long as > you are using a browser). > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Tue May 11 14:46:12 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 May 2004 14:46:12 -0400 Subject: Unification of Methods and Functions References: Message-ID: "Antoon Pardon" wrote in message news:slrnca1d94.1i9.apardon at trout.vub.ac.be... > I don't see how this contradicts what I want to say. In both case you have > something of the form > > obj = cls() > > And in both obj.method() is equivallent to cls.method(obj) I believe Timothy's point was that inst.meth() is more general than any specific clas.meth(inst) whenever there is more than one possible meaning of 'clas'. In the following snippet, one can only replace 'animal.speak', without changing semantics, with 'animal.__class__.speak(animal)' and not with any specific versioon of clas.speak(animal). If something cannot be substituted without changing meaning, in a particular context, then, in that context, it literally does not mean the same thing. class mammal: def speak(self): print 'umf' class dog(mammal): def speak(self): print 'arf' class cat(mammal): def speak(self): print 'meow' for animal in [mammal(), dog(), cat()]: animal.speak() >>> umf arf meow >>> Terry J. Reedy From Chris.Hornberger at blackrock.com Wed May 12 09:49:21 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 09:49:21 -0400 Subject: Idea for Python T-shirt Message-ID: ack! Does that mean I shouldn't talk about the Sausage I "did" for breakfast today? :) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Graham Fawcett Sent: Wednesday, May 12, 2004 9:40 AM To: python-list at python.org Subject: Re: Idea for Python T-shirt Christos "TZOTZIOY" Georgiou wrote in message news:... > (Don't mind me, my frequent late night "I should be sleeping by now" > brainstorm) > > A python smiling, its body curled in the background, 1's and 0's visible > in its body visibly grouped in fours, and below the slogan: > > "With Python your nibbles explode with desire" > > I'll do one for myself :) Personally, I wouldn't post an announcement to Usenet that I'm about to "do one for myself", even when my nibbles /are/ exploding with desire. Maybe it's a cultural difference; Anglo-Canadians can be pretty modest about such things. Oh, you were talking about the t-shirt... -- Graham -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Thu May 13 22:13:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 22:13:37 -0400 Subject: make faster Richards benchmark In-Reply-To: References: Message-ID: Simon Wittber wrote: >>>And Simon: "I just tried the benchmark with Psyco, and cut the run >>>time for input=10000 from 8.1 seconds to 3.4" >>> >> >>What platform is this on? > > WinXP, P4 2.6GHZ, 512MB RAM Hmm... did anyone else confirm your numbers, so that I'm the odd man out? I'm using Python 2.3.3 and the latest download of Psyco for it. If you're using that too, the only apparent difference is the CPU. Is it possible that could make such a significant difference? (Unlikely at best, I'd say.) -Peter From tim.one at comcast.net Sun May 30 08:31:36 2004 From: tim.one at comcast.net (Tim Peters) Date: Sun, 30 May 2004 08:31:36 -0400 Subject: API : constness ? In-Reply-To: Message-ID: [Beno?t Dejean] > i don't understand why the ANSI const keyword is never used in the API. It is used in the API, and more than once, but it isn't used as often as it could be used. It's more likely to appear in newer API functions. When Python was first written, most compilers were K&R, and Python avoided ANSI features until about a decade later (a C89 compiler is required now). A lot of the C API survived unchaged across all that time. There's no objection to slamming in consts now, but nobody has cared enough to bother doing so. From heikowu at ceosg.de Sat May 15 13:02:58 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 15 May 2004 19:02:58 +0200 Subject: sys.argv[0] and ps aux Message-ID: <200405151902.58688.heikowu@ceosg.de> Hi all! Is there some way to set sys.argv[0] on a Unix platform and have the string which is set show up in the output of ps aux? IIRC when I (re)set argv[0] in C, the newly set string pops up in ps aux (but I may be wrong here, it's a long time since I last programmed in C... ;)). Any hint appreciated! Heiko. From joewong at mango.cc Thu May 13 23:32:36 2004 From: joewong at mango.cc (Joe Wong) Date: Fri, 14 May 2004 11:32:36 +0800 Subject: capture exception raised by child thread. Message-ID: <06a901c43964$1a767460$7f00a8c0@scl01.siliconcreation.com> Hi, I have a class that created a child thread for processing, this thread might raise an exception under some condition. On the main program that create an object of this case, I put a try/except block trying to capture the exception but failed. Am I doing anything wrong here? here is the stripped version of my code: class A: def __init__(self): self.thread = threading.Thread(None, self.MyThread) self.thread.setDaemon(1) self.thread.start() def MyThread(self): while 1: # do something. if error: if error: raise exception in my Main program: main() a = A() while 1: try: # do something.. except exception, e: # I should capture the exception from A, but not.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From admin at na.org Thu May 6 02:19:53 2004 From: admin at na.org (admin at na.org) Date: Wed, 5 May 2004 23:19:53 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:25518066130039076510) Message-ID: <041701c43332$24f4c960$b0a8a8c0@na.org> Subject of the message: stolen Recipient of the message: Fellowship Services Mail From opengeometry at yahoo.ca Thu May 27 23:28:27 2004 From: opengeometry at yahoo.ca (William Park) Date: 28 May 2004 03:28:27 GMT Subject: a python script which will parse an email message References: Message-ID: <2hnpurFf75ecU1@uni-berlin.de> chuck amadi wrote: > any python script which will parse an email messages into a file to > poplulate a database. > > Im trying with UnixMailbox but I cant figure out howto abstract the > all email data messages to a file . Can you rephrase this with some example of "input" and "output" you want? As is, emails are already in a file, so there is no need to parse it to a file. -- William Park, Open Geometry Consulting, From nospan at thanks.com Mon May 3 17:28:35 2004 From: nospan at thanks.com (Allan Hughes) Date: Mon, 03 May 2004 16:28:35 -0500 Subject: Distributing a Python App Message-ID: <109dec4c2bdn38e@corp.supernews.com> I'm a python noob and have a question. I would like to write a little app and then share it with others. It is going to need to store potentially large amounts of data and then generate reports based on that data. I could just write to a DB, but that wouldn't be very portable. I would like a solution that will work 'out of the box' for any old shmo who wants to use it without worrying about whether they have the right DB. How can I build this in? Suggestion? What have you done in the past? Thanks! From tjreedy at udel.edu Sat May 22 11:17:17 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2004 11:17:17 -0400 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com><545cb8c2.0405201645.16ac3364@posting.google.com> <545cb8c2.0405220521.ac117a4@posting.google.com> Message-ID: "Jim Hefferon" wrote in message news:545cb8c2.0405220521.ac117a4 at posting.google.com... > Thanks, Peter and others, you have been enlightening. I understand > you to say that Python insists that I explicitly decide the decoding, > and not just smoosh the strings. Thanks. Abstractly, byte strings and unicode strings are different types of beasts. If you forget what you know about the CPython computer implementation and linear computer memories, it make little sense to combine them. The result would have to be some currently nonexistent byte-unicode string. Terry J. Reedy From vmilitaru at sympatico.ca Sun May 9 02:10:36 2004 From: vmilitaru at sympatico.ca (Vio) Date: Sun, 09 May 2004 02:10:36 -0400 Subject: Embed+extend+port Message-ID: <409DCB5C.9050407@sympatico.ca> My story: I played with a little embedded python piece of code (python interpreter embedded in wxWidgets app), and used SWIG to extend this embedded py interpreter. I did it in Linux, after some ironing all builds and runs as expected. On a particularily lazy day, I pasted these same wrapper sources to Win32 (cygnus). After fiddling with the Makefile to point in the right directions, compilation seems to go ok (give or take a couple of warnings). But then the linking step chokes with unfriendly messages like "undefined reference to _PyExit, _Py_Initialize, etc.". Could someone tell me what this mean? My guess is that my linker is not pointed at the right Python library, but could someone confirm/rebute this? I'm pointing the linker (on win32) to -L"/Python23/libs" where lives "python23.lib", as presumably I need an equivalent to Linux's "/usr/local/lib/python2.3/config/libpython2.3.a", so I'm wondering if I'm pointing at the right place on the win32 side, or even if I'd need to compile Python on win32 (currently using some precompiled distro on win32, while I recompiled Py on Linux). In other words, I'd like to do all my development on Linux, and not have to redo the work on win32 (besides some cut&paste). If I sound like a win32 newbie, well, I also like like one:) Cheers, Vio PS I just read on the list some comments that wxWidgets+Python mix is kinda slow. Bummer. From cookedm+news at physics.mcmaster.ca Mon May 3 23:27:07 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 03 May 2004 23:27:07 -0400 Subject: list as a base class in Python 2.1 References: <20040504125913.GC15311@flowcom.com.au> Message-ID: At some point, bdecker at flowcom.com.au wrote: > Hello, > > With python2.2 I am able to define a class based on the 'list' type as > follows: > > class sample(list): > ... > > But this doesn't work under python 2.1. Is there still a way to simply > use the list type as a base class under python 2.1? No. But you could try the UserList module, which will make it easier to emulate a list. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From fredrik at pythonware.com Tue May 25 02:19:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 08:19:49 +0200 Subject: terminological obscurity References: <40aec6ff$0$17254$a1866201@newsreader.visi.com><1085210465.206473@yasure><1085248385.210031@yasure><51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: Arthur wrote: > > Well for one, before new style classes, it was easier to think of an > "instance" as in some sense a pseudo data type. Instances of > different classes - even with no hierarchical relationship - were more > conceptually homogenous. nonsense. Python has always used duck typing (what's important is what you can do with x, not what type(x) happens to be). this hasn't changed a bit. (if you don't understand duck typing, you don't really understand Python) From peter at engcorp.com Fri May 14 08:32:59 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 08:32:59 -0400 Subject: beginner's question In-Reply-To: References: Message-ID: Hadi wrote: > I have two files and the array that contains 20 words in it. > I'm trying to write python script that suppose achieve the following: > -Open file-1, read the line that contains 20 words separated with commas > -Compare each word with words in the array > -Open file-2 > -if the word appears in the array write 'true' in file-2 > -if not write 'false' > -repeat this for every line in the file-1 > > so, two file will be identical in terms of number of lines and number of > words in each line. > However, file-2 will only contain wods 'true' and 'false'. > > Can anyone give some example or point me to som useful web sites please. Can you post some sample code that you've written to show that you've actually tried by yourself first? That will also give us a starting point in helping you. Otherwise we're likely to be spoonfeeding you answers to your homework assignment. Presumably you have already learned some basic programming in class and are supposed to be trying to apply that learning in this exercise? Hints: How do you open a file in Python and read lines from it? (see the tutorial online at www.python.org) How do you define an "array" in Python? (see tutorial again, looking at dictionaries) How do you write a loop in Python? (use the 'for' or 'while' keywords, depending on what exactly you want to do: see the tutorial for examples) -Peter From stephen.no at spam.theboulets.net.please Thu May 6 06:21:20 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Thu, 06 May 2004 05:21:20 -0500 Subject: linux1, linux2? Message-ID: What is the difference between linux1/linux2 that sys.platform returns? -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From me at privacy.net Wed May 19 05:36:00 2004 From: me at privacy.net (Duncan Booth) Date: 19 May 2004 09:36:00 GMT Subject: alternatives to making blocks like { } or other ?? References: Message-ID: Grant Edwards wrote in news:slrncalqqf.8f2.grante at grante.rivatek.com: > Please, please don't write code like that. You'll be shunned > just like the BASIC programmers who switched to C and pulled > crap like > > #define IF if ( > #define THEN ) { > #define ELSE } else { > #define ENDIF } > > #define WHILE while ( > #define DO ) { > #define DONE } That's not even a very good set of macros. You want: #define IF if((( #define THEN ))){ and then you can have something like: #define AND ))&&(( #define OR )||( for added fun and enjoyment. N.B. This cleverly changes the operator priorities to match the language of your choice. Safety Warning: The definitions of 'want' and 'cleverly' above may not exactly match the usual dictionary definitions. From t-meyer at ihug.co.nz Wed May 26 17:46:32 2004 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 27 May 2004 09:46:32 +1200 Subject: gencache.EnsureModule Error In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130681884B@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F1304677E92@its-xchg4.massey.ac.nz> > I believe that the error occurs at > def ensuremodule(): > gencache.EnsureModule('{00000201-0000-0010-8000-00AA006D2EA4}',0,2,1) > which is for ADO for SQLServer. > > Does anybody know why? [...] > IOError: [Errno 13] Permission denied: > 'C:\\PROGRA~1\\Python23\\lib\\site-packages\\win32com\\gen_py\ > \dicts.dat' It looks like you don't have permission to (re)create that file. Check that it's not locked by someone else, and that you have the appropriate permissions in that directory. =Tony Meyer From thelastmohiccan at yahoo.com Thu May 20 16:30:45 2004 From: thelastmohiccan at yahoo.com (lenk) Date: Thu, 20 May 2004 23:30:45 +0300 Subject: free psp host Message-ID: <2h4ijhF8g1alU1@uni-berlin.de> Hi all Where can I find ? thanks From moma at example.net Fri May 21 12:09:22 2004 From: moma at example.net (moma) Date: Fri, 21 May 2004 18:09:22 +0200 Subject: Deleting Directories In-Reply-To: References: Message-ID: Laura McCord wrote: > Hi, > > I need to delete all directories in /var/www/html/test that are older > than five days. I am new to python so how would I get started? Any tips > or suggestions would be appreciated. > > Thanks, > Laura > Hello Laura, Use walk() or listdir() to traverse thru all files in your directory. The following excerpt is a skeleton, untested code. It tests modified_date and can delete both files and directories. Note: rmdir() and unlink() is commented out. www.google.com has several examples. Search for "python walk and (dir or listdir)" // moma python newb http://www.futuredesktop.org #!/usr/bin/python -u import sys, time from os import listdir, unlink from os.path import isdir, isfile, islink, join, getmtime deldir = "/home/moma/tmp" days = 5 now = int(time.time()) deldate = now - (days * 24 * 60 * 60) # ------------------------------------- def del_entry(_name): try: if isdir(_name): # rmdir(_name) sys.stdout.write("Delete DIR %s\n" % (_name)) else: # unlink(_name) # or remove(_name) sys.stdout.write("Delete FILE %s\n" % (_name)) except IOError: sys.stderr.write("Cannot delete %s\n" % (_name)) # ------------------------------------- def list_dir(_dir, _date, _action): if not isdir(_dir): print "%s is not a directory" % (_dir) return # if getmtime(_dir) > _date: return for file in listdir(_dir): path = join(_dir, file) if getmtime(path) > _date: continue if isdir(path): list_dir(path, _date, _action) _action(path) else: # isfile() or islink() _action(path) // Run it list_dir(deldir, deldate, del_entry) From me at privacy.net Tue May 25 09:01:35 2004 From: me at privacy.net (Duncan Booth) Date: 25 May 2004 13:01:35 GMT Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: Jacek Generowicz wrote in news:tyf1xl8n0yl.fsf_- _ at pcepsft001.cern.ch: > Name Interpreted Compiled With declarations > > LispWorks 66 1.0 1.6 > Clisp 41 9.5 9.5 > CMUCL Got bored waiting 1.5 0.45 > SBCL Compiles everything 1.6 0.49 > Python Compiles everything 20 > gcc No interactivity 0.29 Using Psyco speeds things up somewhat. On my machine this test in Python without Psyco takes 14.31s, adding a call to psyco.full() reduces this to 0.51s From me at privacy.net Wed May 5 16:02:51 2004 From: me at privacy.net (Alejandro =?iso-8859-1?Q?L=F3pez-Valencia?=) Date: 5 May 2004 20:02:51 GMT Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <40992866$0$12738$636a15ce@news.free.fr> Message-ID: On 2004-05-05, Brian Quinlan wrote in : > Christophe Cavalaria wrote: > >> Try adding that line at the end of each modified file : >> >> # vim:sw=4:softtabstop=4:expandtab >> >> It tells vim all the commands it should automatically run when it opens the >> file and it should get you the correct behaviour for 4 spaces no tab >> indentation. > > Thanks for the suggestion but modifying all my files is a pretty ugly > solution. Not that I'm above using it if there is no better way :-) The better way is to read the fine manual (not that many do, it is too big :-). $ mkdir -p .vim/ftplugin $ cd .vim/ftplugin $ vim python_pep8.vim .... dradul at shangri-la ~/.vim/ftplugin [238]-% cat python_pep8.vim if exists("did_python_pep8") finish else let did_python_pep8=1 endif set tabstop=4 set shiftwidth=4 set softtabstop=4 set expandtab set textwidth=80 And that's all there it to it. -- Alejandro L?pez-Valencia qenqhy ng rgo qbg arg qbg pb http://dradul.tripod.com/ The limits of my language are the limits of my world. (L. Wittgenstein) From peter at engcorp.com Fri May 14 09:30:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 09:30:29 -0400 Subject: smtplib - missing message In-Reply-To: <23ae7099.0405140440.341a6244@posting.google.com> References: <23ae7099.0405140440.341a6244@posting.google.com> Message-ID: alastair wrote: > I'm trying to send an email using smtplib .... > When I look at the received mail, the > text I send is not there - does anyone know why this is the case ? > > Here's the code I've been using: > fromClause = "me at me.com" > toClause = "you at yahoo.co.uk" > > msg = "Please display me." > > server.sendmail(fromClause, toClause, msg) RFC2822 (or whatever it is) specifies that a mail message has headers, separated from the body of the message by an extra newline. (Or is it a CRLF combination? You can look that up yourself.) You don't have any header in your message, so you'll have to add one, something like: msg = "Subject: test\n\nPlease display me." Note the double newline to mark the end of the header fields. -Peter From eric_brunel at despammed.com Tue May 4 05:00:38 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 04 May 2004 11:00:38 +0200 Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> <109drk3erp8cm8c@news.supernews.com> <4096F56A.F9815BA7@shaw.ca> Message-ID: David M. Cooke wrote: [snip] > Some actual code would make what you're trying to do clearer. Here's > my guess: > > def stuff(master): > scale1 = Scale(master) > scale1.pack() > scale2 = Scale(master) > scale2.pack() > def init_classes(scales=[scale1, scale2]): > ... stuff ... > button = Button(master, command=init_classes) > button.pack() > > and what you'd like is > > def stuff(): > # doesn't work as scale1 and scale2 haven't been assigned yet > def init_classes(scales=[scale1, scale2]): > ... stuff ... > button = Button(master, command=init_classes) > button.pack() > scale1 = Scale(master) > scale1.pack() > scale2 = Scale(master) > scale2.pack() Also note that you have no need to pack objects just after creating them. You can just do: def stuff(master): scale1 = Scale(master) scale2 = Scale(master) def init_classes(scales=[scale1, scale2]): ... stuff ... button = Button(master, command=init_classes) button.pack() scale1.pack() scale2.pack() Using the grid layout manager instead of the pack one may also be a solution to the problem, since with it, the layout does not depend on the order of the calls to grid as it does with pack. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From nc-jantzegu at netcologne.de Sun May 23 17:35:55 2004 From: nc-jantzegu at netcologne.de (Günter Jantzen) Date: Sun, 23 May 2004 23:35:55 +0200 Subject: Fw: Unit testing in Prothon? (from comp.lang.python) References: Message-ID: "Roy Smith" schrieb im Newsbeitrag news:roy-4558B5.16371723052004 at reader2.panix.com... > I've read through the Prothon tutorial and must admit there is something > kind of interesting about the idea of prototypes instead of classes. > > My thoughts quickly turned to testing. If nothing else, classes give us > a nice place to hang unit tests on. I can design and test one class at > a time, then move on to the next one. What would unit testing look like > in Prothon? This is an interesting question. I forward your posting to prothon-user at lists.prothon.org I think I have no answer now. Or is it so simple: test an application object by using it as prototype for an test object with several testmethods? Regards Guenter From tjarko at dutlbcz.lr.tudelft.nl Fri May 14 10:37:02 2004 From: tjarko at dutlbcz.lr.tudelft.nl (Tjarko de Jong) Date: Fri, 14 May 2004 16:37:02 +0200 Subject: Loop and the list References: Message-ID: On 14 May 2004 13:46:46 GMT, Krzysztof Szynter wrote: >Hi all > >Have got a big problem. This is my code: >def maxvalue(TY): #gets an index of the max value in the TY list > max = 0 indexMax = -1 > for i in range(0,len(TY)): > if (max # max = i max=TY[i] indexMax=i > print TY[i],max > continue > # return max return indexMax >I don't understand why function maxvalue returns "9". When i start a >program and check TY list in 'first main point', the max value has an index >0'. Then putting the list into the function maxvalue, gives me the index >'9'. ;--/ > >Where is the mistake? > >ps >Apologise for the Polish text's, in the code. I'll answer for any question. From elainejackson7355 at home.com Sun May 16 12:39:40 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Sun, 16 May 2004 16:39:40 GMT Subject: tkinter button widget References: <7CBpc.467692$Pk3.138905@pd7tw1no> Message-ID: Sorry, that was 'my bad'. It actually does work. Thanks. "Jeff Epler" wrote in message news:mailman.7.1084710699.13608.python-list at python.org... | It works just dandy here, and since you didn't provide the error text | there's really not much I can do for you. | | Jeff | From roy at panix.com Thu May 20 10:52:58 2004 From: roy at panix.com (Roy Smith) Date: Thu, 20 May 2004 10:52:58 -0400 Subject: alternatives to making blocks like { } or other ?? References: <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: asmirnov1234567890 at yahoo.com (Andrei Smirnov) wrote: > i do really suffer. i have to use Perl and i know that i have no chance > to convince my new boss (very smart guy) to switch to Python because of > braces. that means wasted time on debugging perl crap code and listening > about Perl 6 future might. > > Please, Python writers, do provide braces as compatibility mode. Asking for braces in Python is like trying to teach a pig to sing; it won't work and it annoys the pig. For better or worse, Python uses indentation for statement grouping. There are more or less three ways to deal with this: 1) Decide you like the idea and use the language. 2) Decide you don't like the idea, but find enough else worthwhile in the language that you get past your dislike of indentation and use the language anyway. 3) Decide the indentation issue is so onerous to you that you can't get past it and don't use the language. Any of those are valid. Personally, I fall into camp #2, and think people in camp #3 are being obstinate fools, but any of the above is preferable to trying to get the language maintainers to add braces to the language. It just ain't going to happen. On the other hand, anybody is free to download the source code to the system and modify it in any way they see fit. If people like it, they'll adopt it. Lots of people have come up with variants, add-ons, or outgrowths of the core language: Jython, NumPy, Prothon, Pyrex, Psyco, Parrot, etc. Just in the last few days has yet another one called Pythong been mentioned, although details are still a bit sketchy on that :-) From demarchi at duke.edu Sun May 16 21:33:22 2004 From: demarchi at duke.edu (stormslayer) Date: 16 May 2004 18:33:22 -0700 Subject: benchmarks and questions for new python programmer Message-ID: Folks: I've been considering a shift to python. I currently use c++builder (borland) or perl. I do computational models / statistics programming, and was interested in python b/c it a. has a library that connects to the R stats package b. has code that seems way more readable than anything else There is, however, at least for my work, a hard constraint. Execution time for large data sets / lots of iterations of a model needs to be reasonabe. So, I wrote a program to test it out (appended to the bottom of this email). As I said, this is my first python program. I'm sure it is terrible, but in many ways, you hope that the interpreter / compiler corrects some errors (or the langauge isn't that easy to use after all). Benchmarks (for the paramter settings in the file): C++builder 6.0: 3 seconds Perl (ActivePerl 5.6.1.638): 14 seconds Python (ActivePython 2.3.2 Build 232): 1 minute 13 seconds Note that I didn't fiddle overmuch with any of the programs -- each one took about 15 minutes to bang out on the keyboard. I'm hoping that there is some obvious mistake in the way I used something in python to account for the speed differential. It seems like a really, really nice language, but orders of magnitude slower than C/C++ and a 5x slowdown over Perl seems abusive... Thanks for any advice. sd Python code: #!/usr/bin/env python import random pop=[] # popluation of agents; initially empty list N = 10000 # population size ep = .05 # mutation rate its = 100 # number of times through the main loop gold=0 # initial number of gold adopters; (1-gold) = silver adopters standard=0 # either 1 for gold or 2 for silver shifts=0 # number of regime shifts def init_all(): # init globals global pop, gold, standard pop = [] gold = 0 for i in range(N): if random.randint(1,2) == 1: pop.append(1) gold=gold+1 else: pop.append(2) if gold>N/2: standard=1 else: standard=2 # if tie, silver wins # print "Initial Population of Gold Users: ", gold # end function init_all def one_choose(): global pop, standard, gold, shifts for i in range(its): temp = random.randint(0,N-1) tempval = pop[temp] old_stand = standard if random.random()N/2: standard=1 else: pop[temp]=2 if tempval!=pop[temp]: gold=gold-1 if goldN/2: if pop[temp]!=1: pop[temp]=1 gold=gold+1 if gold>N/2: standard=1 else: if pop[temp]!=2: pop[temp]=2 gold=gold-1 if gold <2gk3eeF3gha1U1@uni-berlin.de> Message-ID: anton muhin wrote in news:2gk3eeF3gha1U1 at uni- berlin.de: > >> max([1, 2, 3]) > 3 It works. Sometimes. Don't know why, but executing the code, crashes the shell. I mean the shell missunderstood the commands, so i cannot even check max() working. The shell saw max() call like an int() call ;--< After a while... Aarggghhhh. Can somebeody tell me, why without starting this ^&%$ code, i have normally working shell, with max() function call, but after executing the code, my shell starts to treat ONLY max() function as int(), and the code crashes ale the time with: 'int' object is not collable But without touching the code i can call max() in shell any time i want. -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From heikowu at ceosg.de Sat May 8 05:33:09 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 8 May 2004 11:33:09 +0200 Subject: __import__ In-Reply-To: References: Message-ID: <200405081133.09339.heikowu@ceosg.de> Am Samstag, 8. Mai 2004 10:19 schrieb Ryan Paul: > "Its ok to use a language > feature as long as I know what I am doing." Hmm... If you need to override a builtin, and do not duplicate the original behaviour exactly (that's pretty much what the op wanted to do, anyway, if you need to override a builtin, you're not into duplicating the original behaviour), then you always create a can of worms whenever you use a different package. Say, I use: __import__("blah",{},{}), and my library expects __import__ to throw an error in case blah can't be found, to check whether my functionality is there or not. What the op wanted to do is to replace this check with some deep magic, probably returning a package instead when the actual import fails. What is my program expected to do? The import succeeds, but the package which was actually returned isn't usable, because it doesn't duplicate what I expect __import__("blah") to return. It's always much, much cleaner to not override the builtin, but to create a new method, which has the behaviour you want, and then to use that one throughout your package. That way each programmer can rely on the fact that the builtins work as they are specified in the language reference, and can be sure that his/her module also works on a different machine/with different modules, just because the underlying Python is the same. I've had to recode a project someone else wrote, and he heavily made use of such deep magic to create something which was a bit shorter overall, but which was much more difficult to maintain for me later on just because plugging in some other modules to extend the functionality simply was not possible anymore. He also overrode __import__ to return some dummy-module in case the one being imported wasn't found, and did even more black-magic checks to see where the call came from using the stack-trace, and then tested whether it was okay to return a dummy module or not. This is a maintenance nightmare... Heiko. From Mike at DeleteThis.Geary.com Sat May 15 17:56:45 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 15 May 2004 14:56:45 -0700 Subject: Python vs. VBScript vs. JavaScript in context of Windows ScriptingHost? References: <10ad4bqh6qpgffa@corp.supernews.com> Message-ID: <10ad4guhvd09udf@corp.supernews.com> Michael Geary wrote: > Microsoft has a very good Windows Script site with information on Script, > the WASH object model, etc. here: > > http://www.msdn.microsoft.com/scripting That, of course, should say "WSH object model." Dang spelling checker went and changed it before I noticed! :-) -Mike From Mike at DeleteThis.Geary.com Thu May 27 13:01:54 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 27 May 2004 10:01:54 -0700 Subject: Best way to enumerate something in python References: Message-ID: <10bc7o3cmtf7r0e@corp.supernews.com> David Stockwell wrote: > FWIW this is what I'm going to do for enumerated types in python. > Its not perfect but it will make it fairly easy to get at column names > so I can build SQL statements on the fly and still have fairly easy to > maintain code > > #setup stuff > NAME_COL, ADDRESS_COL, CITY_COL, ZIPCODE_COL, \ > STATE_COL, COUNTRY_COL, SS_COL, CAT_COL, \ > DATE_COL, SALARY_COL = range(10) > > mycol = { > NAME_COL: " NAME ", ADDRESS_COL: " ADDRESS ", > CITY_COL: " CITY ", ZIPCODE_COL: " ZIPCODE ", > STATE_COL:" STATE ", COUNTRY_COL: " COUNTRY ", > SS_COL: " SS ", CAT_COL: " CAT ", > DATE_COL: " DATE ", SALARY_COL: " SALARY " } > # Use these for indexing by column name > > # demonstration on how to 'get' > > print mycol[CITY_COL] I don't know much about SQL, so this may be a dumb question, but... Is it a requirement that you have indices for the columns as well as names? IOW, does it matter that NAME_COL is 0, ADDRESS_COL is 1, etc.? Or is the end result you're after to have NAME_COL be a way to get to the string " NAME "? If you don't need the numeric indices, there are a couple of other approaches you could take, both inspired by Peter Hansen's nifty bit of code: First, since you're putting CITY_COL and so forth in the global namespace anyway, you could simply define them as the strings: def makeColumnNames( names ): class container: pass cols = container() for c in names.split(): cols.__dict__[c] = ' %s ' % c return cols cols = makeColumnNames( 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' ) print "'%s'" % cols.CITY Or, you could avoid cluttering up the global namespace with those names, avoid the need for the _COL suffix, and use the cleaner cols.CITY notation instead of cols[CITY_COL]: def makeColumnNames( names ): class container: pass cols = container() for c in names.split(): cols.__dict__[c] = ' %s ' % c return cols cols = makeColumnNames( 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' ) print "'%s'" % cols.CITY If you do need the numeric indices as well, it would be easy to come up with a variation of one of the above approaches that gives you both the indices and the names in a convenient way. -Mike From michael at foord.net Fri May 21 06:01:13 2004 From: michael at foord.net (Fuzzyman) Date: 21 May 2004 03:01:13 -0700 Subject: Python compilers? References: <30260531.0405180848.42e2919d@posting.google.com> Message-ID: <8089854e.0405210201.2a9b6de@posting.google.com> simoninusa2001 at yahoo.co.uk (simo) wrote in message news:<30260531.0405180848.42e2919d at posting.google.com>... > Leif K-Brooks wrote: > > > > Is anyone working on a python-to-native compiler? > > > I'd be interested in taking a look. > Various people on various projects... most still at the vapourware stage. In essence python is a dynamic interpreted language though - in order to make it suitable for 'compilation' you have to remove some of the advantages. Funnily though, most people call Java a compiled language, but it only compiles to Java bytecode which runs on the virtual machine. Python precompiles to python bytecode which runs on the python virtual machine. So arguably it is *as* compiled as Java..... > > If it's faster code execution, the primary slowdown with a very > > high-level language like Python is caused by high-level data structures > > (introspection, everything being an object, etc.), not the code itself. > > A native compiler would still have to use high-level data structures to > > work with all Python code, so the speed increase wouldn't be very much. > > I think the main slowdown most people would see is the startup time - > the interpreter takes way too long to start (why the company where I > work won't replace Perl/PHP with Python). > It's not a problem I've been particularly aware of. Lots of projects to increase execution speed. Psyco is *very* good and very useable of x86 machines. I use it and see a real speed increase of approx 10 times on a couple of applications I 've done - anagram generator and binary interleaving... both of which are processor intensive. It doesn't address startup speed though......... > > If it's ease of distribution you're looking for, I think distutils can > > make standalone programs on Windows, and most Linux distros have Python > > installed by default. > > Oh that one is funny - do most distro's have PyQT and wxPython (and > their supporting Qt/GKT libs) installed by default, oh and which ones > come with 2.3 by default? > No - and worse PyQT is commercial only on windoze. You need py2exe (or similar) to make standalone programs that will run without python. It's not difficult though. > > If you just think a compiler would be cool (or would like to see how it > > would be done), check out Psyco, Pyrex, and probably some other > > projects. Pyrex even combats the speed issue by allowing native C types > > to be used in addition to Python high-level types. > > I thought Pyrex was a hybrid of C and Python (like Jython/Java) not > actually a Python-to-C convertor? And Pysco is just a different VM > isn't it? > That's right - Pyrex is a new language that mixes python and C syntax. You can also use it to easily build python extensions. > I could really push Python where I work if there was a native > compiler, my company uses C/C++/Java/Qt and were looking at QSA as a > way to allow the user to script things, but as all of our products > integrate with our software protection system, we can't be > distributing source or easily decompiled bytecode! > > We could replace the whole lot with PyQt and use an embedded Python > interpreter for the scripting! Ah the frustration :-( if you're lookibng at scripting then you'll be embedding an interpreter *anyway*. There *isn't* a native compiler... because python isn't a compiled language. *But* bytecode isn't *easily* decompiled (and decompyler is no longer publicly available) and speed critical stuff/stuff that needs to be compiled for security reasons can be compiled using Pyrex - which handles all the interfacing of python to C and you get the best of both worlds in terms of syntax. No reason you shouldn't distribute the PyQt libraries *with* your program - assuming you stick to the relevant licenses. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From donn at u.washington.edu Fri May 21 16:31:33 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 21 May 2004 13:31:33 -0700 Subject: terminological obscurity References: Message-ID: In article , "Elaine Jackson" wrote: > All tuple methods are also list methods, and most list methods are also tuple > methods; among those that are NOT also tuple methods, there are exactly two > ('count' and 'index') that do not involve mutation. Is there any special > reason > why they AREN'T also tuple methods? Not to speculate on the reason (that would be for Guido or someone who channels him to say), but suppose you accept the proposition that a tuple is not just an immutable list, it's intended to serve in a really distinct role. Now you can invert your question to ask, what's the apparent role of a sequence type that isn't interested in its length, nor in sequential searches? If you look at common use of tuple in the core language, I think it might be fairly clear what that's about. Take dict.items(), for example - a list, of tuples. The list is not a list because we want it to be mutable (what a horrible thought), but because it's a collection of conceptually similar objects ... so naturally, we want to know how many (length) and maybe we'd be interested in searching the list for things (though that would probably be silly in this particular case.) On the other hand, the key, value pair is a tuple because it always contains two values, and they're not interchangeable at all. What good is the length here? If it isn't two, something has gone very wrong. It makes no sense to apply a search indiscriminately to the values of a tuple, because they lose their meaning out of context. > A question about terminology ('namespace'): > > >>> prince=tuple() > >>> king=[prince] > >>> del prince > > At this point, does the object formerly known as prince belong to the > namespace > implemented by globals()? More generally, is there a terminological way to > distinguish between (1) a function from a set of names into a set of objects, > and (2) the aforementioned set of objects? Well, the "prince" binding disappears, but the object continues to belong to it indirectly, through that list reference. The more general question you pose is not clear to me. > Is there a handy noun that refers to sameness of identity in the same way > that > 'equality' refers to sameness of value? ('Identicalness' is pretty clumsy, > and > 'identity' is confusing, since it already has a meaning that is closely > related > but needs to be kept distinct.) What meaning is that? I would use identity. > A question about terminology ('name'): > > Suppose X is a container that contains n items (incidentally, is 'items' the > right term?) and i in an integer with 0<=i<=n. Does " X[i] " count as a > 'name'? I imagine in some contexts we may use name that way, as an expedient in casual usage, but I hope it isn't official nomenclature. You could call it a "binding". (If you're trying to square this all up in some kind of CS context, see if you can compare the Lisp usage of that term.) Donn Cave, donn at u.washington.edu From steve.menard at videotron.ca Thu May 27 20:26:21 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Thu, 27 May 2004 20:26:21 -0400 Subject: jython 2 cpython bridge In-Reply-To: <87lljdiiyn.fsf@pobox.com> References: <8dssc.179150$f_5.163363@lakeread01> <40b25aa6$0$36169$e4fe514c@news.xs4all.nl> <87lljdiiyn.fsf@pobox.com> Message-ID: John J. Lee wrote: > Steve Menard writes: > [...] > >>Alternately, you can look at JPype ( http://jpype.sourceforge.net ). >> >>It is still a very early release, but I would welcome any feeback. And >>version 0.1 should allow you to use JDBC without problem. >> >>It currently only works on Windows, but if there is interest, I could >>make a linux release pretty quickly. > > > I assume you've seen JPE? > > How does / will JPype differ from that? > > I *think* JPE hasn't been maintained for quite a while, but I'm not > certain what its current state is. > > > John Yes I have seen JPE. However, from the my admitedly quick look, it didn't allow the seemless integration I am looking for. Either that, or the samples did show off what JPE could do. Besides I intend to take JPype beyonf Python->Java integration, and choice is always good :) Steve From frank at chagford.com Thu May 13 10:55:57 2004 From: frank at chagford.com (Frank Millman) Date: 13 May 2004 07:55:57 -0700 Subject: General Ledger/Accounting Libraries References: Message-ID: <246a4e07.0405130655.24abe2e4@posting.google.com> Andreas Pauley wrote: > Hi All, > > Our company is currently evaluating Python as a language for writing > financial/accounting type software (among others). > > What libraries or packages are available in this domain for use? Hi Andreas I was in two minds as to whether I should respond to this. I am working on something that may provide what you are looking for, but it is still under development. I don't want to waste your time with vapourware, but if I explain what my ideas are and how far I have got, you can decide whether to take it any further. I am developing a generalised accounting/business package using Python. For the GUI I use wxPython. For the database, I use PostgreSQL with pyPgSQL on Unix/Linux, and MS SQL Server with Win32/odbc on Windows. It is too big to describe in a few lines, but I will list some of my design goals, and discuss how close I am to achieving them. Data integrity - I am an accountant first and a programmer second, so I have this area well covered. Some programmers are reliant upon input from an accountant/business analyst, and problems can arise when there is a communication gap. I wear both hats, so I just *know* what is required. In 20+ years of writing accounting software, my systems have received a number of criticisms, but going out of balance is not one of them. Performance - Using a database cursor and a wxPython virtual grid, I can select and display 10 000 rows out of a table of 260 000 rows in less than a second. I can scroll up and down the table with no perceptible delay. I can look for a particular row based on a search string, and it finds the row almost instantaneously. This is on a 266mhz Pentium II laptop with 128mb ram and Windows 2000. On my linux box with a 1.7ghz Celeron, it is even faster. I am reasonably confident that I can handle large volumes of data without a problem. Access control - Full access control is built in from the ground up. Users must log in, and are authenticated. Each user is assigned to one or more groups, and each group can have read/write privileges defined on every column in every table in the database. Full audit trails will be available (not done yet, but on the to-do list). Obviously I cannot prevent unauthorised access external to my software, so it is up to the system adminstrator to control access to the database itself and to the python programs. Flexibility - I used to be a fan of customisation, but with hindsight I believe that in the long run the benefits are illusory. I am therefore building in a lot of flexibility in such things as structure of g/l code and product code, ability to add your own business logic to database tables and columns, parameters to select things such as ageing methods, etc. Full source code will be available, so anyone can customise the programs if they want to, but I will be very open to requests to fold such customisations back into the main body of code, possibly selectable by a parameter. Support - The source code will be released under an Open Source license. Support will be available at a modest monthly charge (to be determined). Although I will have a few sites that I will support directly, my intention/hope is to develop a network of dealers/consultants, who will install and maintain the software at end-user sites and provide first-line support. I in turn will provide backup and support to them, in addition to continuing ongoing development of the software. Current state of software - I am getting close to setting up my first few live installations - say 1 to 2 months. The initial release will include General Ledger, Sales, Purchasing, Inventory, Accounts Receivable, and Accounts Payable. It will be multi-company, multi-branch, and multi-currency. Where to from here - It all depends upon the success of my business model (see Support above). If I can get a few dealers to get a few installations, and start to generate a revenue stream from support fees, I will plough this back into providing a full support and development infrastructure, employing staff as needed. My wish-list for ongoing development of the software is endless, but includes things such as full context-sensitive help, multi-language support, image support, web front end, etc. There will also no doubt be many requests for additional functionality. This can turn into a virtuous circle - the more I build in, the more people will want to use it, which will increase the revenue stream, which I can plough back into development, etc. However, I have to be realistic, which means I must get this past the vapourware stage and get a few live installations. My inclination is to not even release the source code until this has settled down, as there are bound to be teething problems. I estimate that this will take up to 3 months. I will me more than happy to discuss requirements, concepts etc in the meantime. Any comments will be very welcome. Frank Millman From dyoo at hkn.eecs.berkeley.edu Fri May 14 18:51:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 14 May 2004 22:51:22 +0000 (UTC) Subject: map del efficiency python2.2 and 2.1 References: Message-ID: Tim Peters wrote: : [John Hunter] :> pymalloc to the rescue. I rebuilt 2.2 --with-pymalloc and the :> interminable delay was vanquished. : Cool! It will be even better in 2.3 (see other posts in this thread). :> Now where do I go to get a deep understanding of my platform's (glibc :> 2.2.2) implementation of free and why it behaves so badly? : Study the source code, watch it in a debugger until your eyes bleed, and/or : try to engage its current maintainer(s) in discussion. Python grew its own : pymalloc because platform mallocs are a diverse, finicky, and ever-moving : target -- it would truly be a full-time job to keep up-to-date on the subtle : quirks and disaster-modes of all of them, but now we only have to understand : ours. And that's only a half-time job . From buzzard at urubu.freeserve.co.uk Thu May 27 13:07:31 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 27 May 2004 18:07:31 +0100 Subject: Can someone help me with this bug? Message-ID: Hello, I'm probably missing something that should be obvious, but can anyone tell me what's wrong with the following? temp.py --------------------------------------------------------------------- class Item(object): def __init__(self, id, data): self.id = id self.data = data class KeyedSet(dict): def __init__(self, items=None): if items is not None: for item in items: self[item.id] = item def __iter__(self): return self.itervalues() def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.keys()) def __contains__(self, item): return self.has_key(item.id) def intersection(self, other): res = self.__class__() for item in self: if item in other: res[item.id] = item return res def __and__(self, other): return self.intersection(other) def intersection_update(self, other): self &= other def __iand__(self, other): self = self.intersection(other) return self -------------------------------------------------------------------- >>> from temp import Item, KeyedSet >>> a = Item(0, 'W') >>> b = Item(1, 'X') >>> c = Item(2, 'Y') >>> d = Item(3, 'Z') >>> aset = KeyedSet([a, b, c]) >>> bset = KeyedSet([b, c, d]) >>> aset &= bset >>> aset KeyedSet([1, 2]) >>> aset = KeyedSet([a, b, c]) >>> aset.intersection_update(bset) >>> aset KeyedSet([0, 1, 2]) >>> I can't figure out why 'aset' is unchanged? Thanks. Duncan From NOSPAM at easyconnect.fr Fri May 14 12:40:40 2004 From: NOSPAM at easyconnect.fr (RosalieM) Date: Fri, 14 May 2004 18:40:40 +0200 Subject: NIC adress of incoming socket. Message-ID: <40a4f772$0$2280$afc38c87@news.easynet.fr> How can i know the nic adress from an incoming socket ? I can easily know the ip adress and port number but how do i have some information about arp level ? Thanks From raja0576 at yahoo.com Tue May 18 08:03:27 2004 From: raja0576 at yahoo.com (Raja) Date: 18 May 2004 05:03:27 -0700 Subject: Calling Jython code from Java Message-ID: <1a26ae5d.0405180403.db0e069@posting.google.com> I have a java class thats trying to call something in python. This works fine when i do a jythonc on the python script. When i call another python script from the __init__ of my called python script, things go bad.i get this message AttributeError: class 'configuration' has no attribute 'configuration' when calling the constructor. This is my python script thats called by the java class testconfig.py ============= import configuration import java.lang class testconfig(java.lang.Object): def __init__(self): """@sig public testconfig()""" self._cfg = configuration.configuration("/sources/jmxproto") def getValue(self, whatVar): pass and the other script is configuration.py class configuration: def __init__(self, runtimeDir=None): """@sig public configuration(java.lang.String dir)""" """ Some code in here """ When i call testconfig.py, i get the error mentioned above. Any clues? Thanks Raja From gregory_a_bakken at groton.pfizer.com Wed May 12 13:39:04 2004 From: gregory_a_bakken at groton.pfizer.com (Bakken, Gregory A) Date: Wed, 12 May 2004 13:39:04 -0400 Subject: zlib and gzip Message-ID: <75FBD3E83B69D711A9E600080261980C051B3ED7@groexmb04bak.pfizer.com> Below is a very simple sample, but I think it illustrates the problem. In short, I have a text string in readable format, and compressed/encoded by the other app. My getString function below can recover the original string from what is provided by the other app. If I take the original string and try to compress/encode and then recover it, both approaches I have tried fail. (In other words, the script below will actually crash with an error something like zlib.error: Error -3 while decompressing data: invalid block type import gzip, zlib, StringIO, base64 def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s def makeString1(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s def makeString2(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s previouslyMadeString = "81RIzFVIVChKTUxJTMpJVSguKcrMSwcA" readableString = "I am a readable string" print "Original string" print readableString print "" print "Decoded string form other program" print getString(previouslyMadeString) print "" ms1 = makeString1(readableString) gs1 = getString(ms1) print "Decoded from appraoch 1" print gs1 ms2 = makeString2(readableString) gs2 = getString(ms2) print "Decoded from appraoch 1" print gs2 -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 1:14 PM To: Bakken, Gregory A; python-list at python.org Subject: RE: zlib and gzip Ok, fair enough. Can you supply (if it's non-sensitive information) some samples? I'm on this conference call for the next hour or so, so I'm glued to my desk. I have time to tinker. It's just a general status call. I just have to chime in from time to time. -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: Bakken, Gregory A [mailto:gregory_a_bakken at groton.pfizer.com] Sent: Wednesday, May 12, 2004 1:10 PM To: Hornberger, Chris; python-list at python.org Subject: RE: zlib and gzip The short answer is I don't know. The longer answer is that I really don't know the driving force behind the compression/encoding that is being used. What I am doing is a more downstream process (so I am stuck with the chosen scheme). -----Original Message----- From: Hornberger, Chris [mailto:Chris.Hornberger at blackrock.com] Sent: Wednesday, May 12, 2004 1:04 PM To: Greg Bakken; python-list at python.org Subject: RE: zlib and gzip Silly questions first: Is it just a matter of 72 column-bounding to make it email-compliant? (keep in mind I haven't run your sample code yet, I'm sitting here perusing while on a conference call - meetings suck!!!) -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Greg Bakken Sent: Wednesday, May 12, 2004 12:57 PM To: python-list at python.org Subject: zlib and gzip I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg -- http://mail.python.org/mailman/listinfo/python-list LEGAL NOTICE Unless expressly stated otherwise, this message is confidential and may be privileged. It is intended for the addressee(s) only. Access to this E-mail by anyone else is unauthorized. If you are not an addressee, any disclosure or copying of the contents of this E-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. If you are not an addressee, please inform the sender immediately. From jepler at unpythonic.net Fri May 21 21:24:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 21 May 2004 20:24:46 -0500 Subject: [Python-Dev] SystemError: com_backpatch: offset too large In-Reply-To: <20040521143641.A721316341@front.interia.pl> References: <20040521143641.A721316341@front.interia.pl> Message-ID: <20040522012446.GB11411@unpythonic.net> On Fri, May 21, 2004 at 04:36:41PM +0200, Sebastian wrote: > I've got a problem with python script. > My script return exceptinon: > > SystemError: com_backpatch: offset too large > > I'm beginer in python programming, and don't known what do with this message. > For the reasons that Terry Reedy discussed, this message has been sent to python-list instead of python-dev. Here's a small script that produces the error Sebastian mentioned: exec "0" + " and 0" * 9363 Here's another: exec "if len:\n" + "\tNone\n" * 16383 + "else: pass" These programs hit a limit of the Python bytecode compiler, which (I think) currently assumes all branches fit in 16-bit offsets. This program produces a larger offset. Python supports a prefix opcode to give 32-bit operand values instead of 16-bit values, but the code generator isn't smart enough to use them. This is a limit of the implementation, I don't think the language is intended to have these rather arbitrary limits on program complexity. However, the implementation probably tried to trade-offs that were likely to accomodate most human-written code while allowing *cough* uncomplicated C code. Jeff From robin at reportlab.com Sat May 15 04:17:10 2004 From: robin at reportlab.com (Robin Becker) Date: Sat, 15 May 2004 09:17:10 +0100 Subject: bug in inspect (was cgitb vs traceback) In-Reply-To: References: <409F9B8B.60707@chamonix.reportlab.co.uk> <409FC899.9020604@chamonix.reportlab.co.uk> Message-ID: <40A5D206.3000901@jessikat.fsnet.co.uk> Fernando Perez wrote: > Robin Becker wrote: > > >>..... the above script demonstrates a bug in the inspect module's >>getinnerframes function which is using the frame f_lineno instead of the >>traceback's tb_lineno. > > > Have you reported this on SF yet? I think I now realize I've been bitten by > this myself recently a few times. Do you know if it's a new 2.3 bug, or has it > been present since 2.2? > > I wonder if the fix could make it into 2.3.4 or not... > > Best, > > f No I'll mosy on over and see if it's known. I have a fix in place in our code, but we had to modify it yesterday as we're delivering for 2.1. -- Robin Becker From noemail at noemail4u.com Fri May 7 09:53:03 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Fri, 07 May 2004 13:53:03 GMT Subject: Need Help in Python References: <77632a66.0405041826.37568aef@posting.google.com> <154eba01da3bc4d337e453163f9096e2@news.teranews.com> Message-ID: On Thu, 6 May 2004 07:57:50 -0700, Cousin Stanley wrote: >On Thu, 06 May 2004 12:12:37 GMT, Daniel 'Dang' Griffith wrote: > >> """ Starter module for drawing boxes with characters. >> No warranty or suitability for use is expressed or implied. >> Daniel 'Dang' Griffith sez, "Have a nice day!". >> """ > >Daniel .... > > Thanks for a nice generalization .... > > Preliminary tests indicate a problem > with indent strings NOT being applied to the FIRST, top, line > in the returned string .... > > I'll try to find the problem .... > That was intentional, as mentioned in the comments (perhaps poorly). The caller is responsible for positioning the cursor at the top left corner, which means the first line should not be indented. This allows things like this (excuse my poor ASCII art manual example:/---\ | | | | | | \---/ Nonetheless, it's Friday. Maybe this should go to the Useless Python site. http://www.uselesspython.com/oldindex.html (Did anyone check? Maybe there's something similar already there!) Here's an enhanced version that a) optionally prefixes the top line (the caller passes True after the specified indentation string), and b) fixes a bug if the fill value was longer than 1 character. --dang """ Starter module for drawing boxes with characters. No warranty or suitability for use is expressed or implied. Daniel 'Dang' Griffith sez, "Have a nice day!". """ # for reference boxchars = [chr(i) for i in xrange(129, 219)] # handy abbreviations; roll your own naming convention UL = upperleft = topleft = chr(218) LL = lowerleft = botleft = bottomleft = chr(192) LR = lowerright = botright = bottomright = chr(217) UR = upperright = topright = chr(191) vert = vertical = chr(179) horiz = hor = horizontal = chr(196) nl = newline = '\n' # precompute the invariants top = '%%s%c%%s%c' % (UL, UR) mid = '%%s%c%%s%c\n' % (vert, vert) bot = '%c%%s%c' % (LL, LR) all = '%s\n%%s%%s%s' % (top, bot) def box(w, h, fill=' ', indent='', top_also=False): """ Return a string that appears as an 'box' when printed. This is, of course, highly depending on the local character representation. The box is filled with spaces by default. The box is left-aligned by default. To indent it, provide the indentation string. This will be added to the middle and bottom of the box. By default, the caller is responsible for drawing the box at the appropriate starting position. To have to top line of the box indented, pass True as the last agrument. """ # exceptional cases if w < 1: raise ValueError("A box must have a width of at least 1.") if h < 1: raise ValueError("A box must have a height of at least 1.") # pathological cases--return value is not *really* a box if w == 1: return h * (vert + nl) if h == 1: return horiz * w # normal case if not fill: fill = ' ' fill = (fill * (w - 2))[:w-2] end = horiz * (w - 2) return all % (top_also and indent or '', end, (h - 2) * (mid % (indent, fill)), indent, end) # --dang From NOmanlio_perilloSPAM at libero.it Wed May 26 15:14:09 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Wed, 26 May 2004 19:14:09 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> Message-ID: On Sun, 23 May 2004 17:12:25 +0000 (UTC), Jarek Zgoda wrote: >Manlio Perillo pisze: > >>>>>You must use date in UTC format. >>>> This is the date format used by the server cookie! >>>See http://www.w3.org/TR/NOTE-datetime on how should date look in >>>cookies. If date is not in valid format, the module functions may have >>>trouble decoding it. >> >> It is not a my problem! > >As you see, it's your problem, since it's you who cann't decode this >cookie. ;) > The problem is also of Cookie module. >> The web server follow the Netscape specification for Cookies and in >> this spec the date is in the format I have posted. > >Netscape is not internet God, W3C is. > Unfortunately we don't live in a perfect world... ;) >I never tried to read cookies using Cookie module (I used Python only >for writing), so I cann't help more here. Good luck. Ok, thanks. Regards Manlio Perillo From greg at cosc.canterbury.ac.nz Wed May 12 23:06:01 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 13 May 2004 15:06:01 +1200 Subject: Idea for Python T-shirt In-Reply-To: References: Message-ID: <2gg70pF2hi98U2@uni-berlin.de> Hornberger, Chris wrote: > ack! Does that mean I shouldn't talk about the Sausage I "did" > for breakfast today? :) Probably best not to mention it. In fact, try to steer clear of any use of the verb "to do" at all, since it appears to be highly ambiguous... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From missive at frontiernet.net Sun May 16 10:47:11 2004 From: missive at frontiernet.net (Lee Harr) Date: Sun, 16 May 2004 14:47:11 GMT Subject: pexpect module References: Message-ID: On 2004-05-14, Gianluca Trombetta wrote: > Someone know pexpect module? > I've a problem working with it... > > I need to run some commands on remote hosts, like ls, df -k etc..All right. > Although, when i launch a command that have a "more" inside, i don't know > what i must expect! > An example: > > if i want to run an "ls -l | more" on a remote host, it don't return me a > prompt, but a "-------------More-------------"...thus i don't know how much > this. > The only reason I can see for piping the command through more would be if there were a person sitting there wanting to read the output before going on to read the next page of output. That seems counter to the idea of using pexpect to automate the process. Do you really need to pipe through more? From esj at harvee.org Sun May 30 10:20:18 2004 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 30 May 2004 10:20:18 -0400 Subject: Redirect stdout & stderr (similar to a daemon) In-Reply-To: <40b9cd69@news.starhub.net.sg> References: <40b9cd69@news.starhub.net.sg> Message-ID: <40B9EDA2.10502@harvee.org> Tsai Li Ming wrote: > Dear all, > > I have a problem with a redirecting stdout and stderr. I am a top level > module and has no control over the imported modules that are making > system calls such as os.system or popen2.* . I have tried the simplest > method of capturing stdout, stderr via: > > saveout = sys.stdout > sys.stdout = file_obj > > print 1 # works > os.system('w') # Doesn't work > > sys.stdout = saveout > print 1 # Restored > > ------------------------------------------------ > > Therefore, I changed to the following method, similar > to a daemon. However, I couldn't find a way to restore back stdout and > stderr. if I understand what you're looking to do, I solved a similar problem by pushing the redirection of standard out and standard error into the command that I executed. baseline_command ="somecommand 2> 1> /dev/null" and then on executing the command, standard I/O is redirected in the child process which eliminates the need to manipulate it in your program. The program fragment below should get you started. As you can see, it executes the command and then if the error file is non zero length, you retrieve the data and do something with it. The same technique can be applied to standard out just as easily. command_pipe = os.popen(command, "w") command_pipe.write(trapped_message.as_string(1)) result = command_pipe.close() if os.path.getsize(error_path) != 0: for line in file(error_path).readlines(): log("command error %s"% line) os.remove(error_path) hope this is close to what you need From dmq at gain.com Thu May 13 12:06:45 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 13 May 2004 09:06:45 -0700 Subject: classes vs dicts References: Message-ID: On 6 May 2004 03:12:15 -0700, charlvj at yahoo.com (Charlie) wrote: >Greetings, > >I am pretty new to Python and like it very much, but there is one >thing I can't figure out and I couldn't really find anything in the >docs that addresses this. > >Say I want to write an address book program, what is the best way to >define a person (and the like): create a class (as I would do in Java) >or use a dictionary? >I guess using dictionaries is fastest and easiest, but is this >recommended? My problem is similar, with the additional requirement that I need a convenient way to access data deep within a hierarchy of parameters. I chose classes over dictionaries because the syntax to access items in a deeply nested dictionary is awkward. dict[window1][plot2][xaxis][label][font][size] = 12 vs statefiles.window1.plot2.xaxis.label.font.size = 12 The problem is I can't easily save the whole hierarchy to disk. Pickle doesn't work with classes. Also, I worry about the overhead of classes when I am just needing a simple container. A typical statefile will have 1000 parameters in 300 classes nested up to ten levels deep. As a structure of nested classes this takes about 74KB on disk. Importing the file creates a .pyc file that is 157KB !! It does seem to import quickly, however, so speed may not be a problem. Seems like Python could use a "container" structure which would be like a class, but without the overhead and with the ability to "pickle" the whole structure. # ../CDP/Statefiles/bignest.py -- testfile with 960 parameters. c960: c480a: c120a: c30a: c10a: analyses: transient: start = '10u' stop = '20u' method = 'euler' readic = 'final50u' # . . . . . . . . . . . . . . wavescan: window1: xaxis: label: text = "Frequency (MHz)" position = -0.5 font: size = 12 family = 'arial' color = 'blue' bold = True # . . . . . . . . . . . . . . c10b: analyses: transient: start = '10u' stop = '20u' methd = 'euler' readic = 'final50u' -- Dave From SeeBelow at SeeBelow.Nut Tue May 4 12:29:42 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 04 May 2004 16:29:42 GMT Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> <109drk3erp8cm8c@news.supernews.com> <4096F56A.F9815BA7@shaw.ca> Message-ID: <4097C4FF.FAC68A6A@shaw.ca> Eric Brunel wrote: > Also note that you have no need to pack objects just after creating them. You > can just do: > > def stuff(master): > scale1 = Scale(master) > scale2 = Scale(master) > def init_classes(scales=[scale1, scale2]): > ... stuff ... > button = Button(master, command=init_classes) > button.pack() > scale1.pack() > scale2.pack() Thank You, that's what I was looking for. If I can define the scales early and pack them later, that solves my problem. m -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From pit.grinja at gmx.de Mon May 17 14:51:46 2004 From: pit.grinja at gmx.de (Piet) Date: 17 May 2004 11:51:46 -0700 Subject: GUI frontend for MySQL in wxPython Message-ID: <39cbe663.0405171051.fc8b0bd@posting.google.com> Hi there, I am currently developping a small app for the purpose mentioned above. The app connects to a MySQL database, can show the properties of tables (which are displayed as a wxGrid) and statements can be executed, the resuslts of which are also displayed in a wxGrid. Being a newbie, I wondered whether somebody has a similar project and wants to develop things together. My System: Win2000K, AMD AthlonXP2200+, Python 2.3.2, wxPython 2.4.2.4 and 2.5.1.2 Any feedback is welcome Peter From http Wed May 26 19:26:29 2004 From: http (Paul Rubin) Date: 26 May 2004 16:26:29 -0700 Subject: Cleaner idiom for text processing? References: Message-ID: <7xzn7uojmi.fsf@ruckus.brouhaha.com> mellis at frogwing.com (Michael Ellis) writes: > for line in infile: > tokens = line.split() > dict = {} > for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1] > do_something_with_values(dict['foo'],dict['bar']) Here's a pessimized version: for line in infile: tokens = line.split() d = {} while tokens: name = tokens.pop(0) value = tokens.pop(0) d[name] = value do_something_with_values(dict['foo'],dict['bar']) From greg at thirdstone.net Fri May 14 03:33:31 2004 From: greg at thirdstone.net (Juan Stang) Date: 14 May 2004 00:33:31 -0700 Subject: cmd Library Module trouble Message-ID: Hope someone can help ... My Python sys.version prints out as follows: '2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]' I'm also running Windows XP SP1 and I have installed PyGame 1.6, wxWindows 2.5 and the latest Twisted dist. I only include these for the sake of completeness. I'm trying to write something using the 'cmd' module, but I get the error below when I run the source included at the end of this post. It's pretty basic. This looks like a readline error, but the Python documentation states that the cmd module should be OS independent, and I'm not trying to use any readline features. Any ideas??? Please help! Juan Traceback (most recent call last): File "", line 1, in ? File "c:/DOCUME~1/CHROMO~1/LOCALS~1/Temp/python-3672MGt", line 15, in ? tn.cmdloop() File "C:\Python23\lib\cmd.py", line 109, in cmdloop self.preloop() File "C:\Python23\lib\cmd.py", line 153, in preloop self.old_completer = readline.get_completer() AttributeError: 'module' object has no attribute 'get_completer ## Source import os import cmd class TimeNote(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = ">> " self.intro = "Welcome to TimeNote" if __name__ == "__main__": tn = TimeNote() tn.cmdloop() From mcfletch at rogers.com Tue May 25 11:59:42 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 25 May 2004 11:59:42 -0400 Subject: Torontonian Pythonistas, don't forget PyGTA this evening! Message-ID: <40B36D6E.3040606@rogers.com> Two quicky presentations on this evening's agenda; one on the concepts behind Twisted, the other on the Art Interface Device. Details and directions here: http://web.engcorp.com/pygta/wiki/NextMeeting Have fun and see you all tonight, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From timh at zute.net Tue May 18 03:59:50 2004 From: timh at zute.net (Tim Hoffman) Date: Tue, 18 May 2004 15:59:50 +0800 Subject: better csv modules and where have object-craft gone? In-Reply-To: <40a98a20@news.highway1.com.au> References: <40a98a20@news.highway1.com.au> Message-ID: <40a9c270@news.highway1.com.au> Oops ignore my comment on the DNS front for object craft, seems my ISP's DNS just wasn't resolving it earlier today seems to have popped back up on the radar now though T Tim Hoffman wrote: > Hi > > I have been using object crafts csv module for quite a few projects, > mainly because I found the csv in python in it's current incarnation > is funtionally inferior to object crafts. The object craft module > for instance allowed you build up csv gradually (ie field at a time > rather the python csv module where the writer does the work a record at > a time) which isn't always the way I would like to work, > also I have always had encoding problems (specifcally it doesn't > support unicode as per the docs) everytime I used the python > module where as the object craft one always worked out of the box. > > Only problem is object craft seemed to have disappeared off the face > of the net (ie I can't even resolve their name in DNS). > > Which is a pity as I don't have a current copy for 2.3 (windows) > of their csv module. > > Does anyone have a copy of the object-craft csv module, or does > anyone know where they have relocated ? > > It is a pity if they have disappeared. > > Rgds > > Tim From andrew-pythonlist at puzzling.org Tue May 4 20:50:51 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 5 May 2004 10:50:51 +1000 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: References: Message-ID: <20040505005051.GB20777@frobozz> On Tue, May 04, 2004 at 04:54:30PM -0700, Stephen Ferg wrote: > I've been wondering how we can improve the quality of the Python > documentation. > > The problem with the Python documentation is that it is not being > handled like an open source product. The hallmark of open-source > development is that many people contribute. The Python docs in > contrast are being maintained by a very small group. The Python docs accepts contributions exactly the same way the Python interpreter and library does: by patches and bugs submitted to the SourceForge tracker (take a look, there have been quite a few there). > I'm sure that many people would like to contribute to the improvment > of the documentation... the problem is that there is no way that they > can do so easily. The solution is to move to a different model of the > documentation process, by developing a way to make it easy for > everyone in the Python community to contribute to the documentation. Is submitting a bug or patch to sourceforge really that much of a barrier? > One solution is a documentation wiki: see the request (below) for a > "corresponding wikiable page for every page here in the pydocs." A > similar but better solution is to follow the model created by the PHP > community. If you follow the link to > http://us2.php.net/manual/en/function.sort.php you'll see how > impressive the results can be. Something like this is clearly what we > need. Sorry, if the official docs lack sufficient description and examples to be clear on how to use a sort function, then the docs should be fixed by someone willing to spend the time to write a coherent addition to (or even just rewording of) the existing documentation, not augmented by twenty times as much commentary on randomly varying related topics. As a reader, I prefer properly written and edited and officially approved documentation to ten pages of advice from people I don't know and trust -- I've often seen well-meaning novices give bad advice on newsgroups and mailing lists. As a reader, I also don't want to see a tutorial when I'm looking for reference documentation. Thus most of those comments are completely irrelevant to me a lot of the time. In fact, those comments look like conversations that already occur on the newsgroup -- which is already a community-driven documentation resource, handily indexed by google. Some of them look like recipes -- but we already have http://aspn.activestate.com/ASPN/Python/Cookbook/ for that (and I've never seen 30+ line functions for case-insensitive sorting in our cookbook). > So I put this question to the entire Python community. Can we create > an interactive site, and the supporting organizational infrastructure, > that will enable everyone in the Python community easily to contribute > to the Python documentation? I've never felt that the Python documentation was particularly lacking, and searching google has always filled in few the gaps for me. I guess you're trying to solve a problem I don't have. Maybe I'm unusual. -Andrew. From peter at engcorp.com Fri May 21 11:24:57 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 11:24:57 -0400 Subject: Where's the demo for wxpython 2.5 In-Reply-To: References: Message-ID: john fabiani wrote: > Hi, > I can find the demo files for the older versions of wxpython but not the > new 2.5. Thanks What platform are you on? Under Windows, a link to the demo is put into your Start menu when you install and the code is under site-packages/wx/demo. -Peter From mcfletch at rogers.com Mon May 17 01:05:15 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 17 May 2004 01:05:15 -0400 Subject: What's active and worthwhile in the Python 3D world? In-Reply-To: References: Message-ID: <40A8480B.4040109@rogers.com> The Disney/CMU project Panda3D would likely be fun and is quite active (it's very new). Blender is active and more along the modeller lines. Pivy is keeping up with the joneses quite nicely AFAIK. All three are very high-level AFAIK, and thus likely suitable for a beginner. For a far more limited framework, VPython is a very-beginner-friendly starting point and is fairly active. HTH, Mike Kenneth McDonald wrote: ... >In fact, there seem to be quite a few--so many that I'm >not really sure what is active and growing, and what is >dying off. So I was wondering if there are Pythonistas >out there with similar interests, and if so, what you >might recommend looking at? > > ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From steve.menard at videotron.ca Fri May 28 13:31:31 2004 From: steve.menard at videotron.ca (Steve Menard) Date: Fri, 28 May 2004 13:31:31 -0400 Subject: "Private" Member Variables In-Reply-To: References: Message-ID: Scott Brady Drummonds wrote: > Hi, everyone, > > I'm still learning Python as I develop a medium-sized project. From my > previous experience with C++, I've burnt into my mind the notion of > information hiding. I'm having trouble understanding to what extent I > should follow this policy in my Python code so I thought I'd ask the group. > > I read from a previous post that to attain a private-like status of member > variables, I should prefix the variable name with two underscores ("__"). > This does work, but in another post someone asked me if this was really > necessary. Given that the very nature of the language precludes any > compile-time type dependencies I'm wondering if there is any benefit to > naming variables with leading underscores and providing accessor functions > like this: > class C: > ... > def value(self): > return self.__value > ... > > The problems that arise from directly relying on the member variable in C++ > (compile-time type dependency, as I said above) don't exist in Python. So > why provide an accessor at all? Why not just allow direct reading and > writing of the member variable? Is there something here I'm missing? > > What are your thoughts? How much privacy should I build into my code? > Should I be using variables beginning with "__" and accessors? Or is that > simply not necessary (or normal) in Python code? > > Thanks, > Scott > I see no problem with exposing the attribute directly, if that attribute may be freely modified without verification. The main problem with doing this in C++ and other languages, is that changing to a calculated value down the road would break existing code. In python, if an attribute suddenly needs to be validated at assignment time, of has to be calculated at "get" time, you can make it a property. Client code won;t see the difference. However, for the sake of consistency, I would make all get/set accessed that cannot be direct into properties. Steve From segphault at sbcglobal.net Sat May 8 04:19:25 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 08 May 2004 08:19:25 GMT Subject: __import__ References: Message-ID: On Sat, 08 May 2004 09:40:39 +0200, Heiko Wundram wrote: > Am Samstag, 8. Mai 2004 09:31 schrieb Coder Coder: >> Can someone help me with how to overload the __import__ function, >> so that I can call the old __import__ function and if it cannot find >> the library to be able to do something else. > > You shouldn't overload a builtin (at least if you expect to be compatible with > other programmers libraries), but rather do the following where you need it: > > try: > import > except ImportError: > > > Repeat after me: "Overloading a builtin is evil! Overloading a builtin is > evil!" > > HTH! > > Heiko. nothing evil about it, as long as you just EXTEND the functionality rather than replace it. If an overloaded import still behaves the way the rest of the libraries expect it to, you dont break anything. If there was a risk of dangerous compatibility issues, there wouldn't be a hook designed to facilitate overloading it. Repeat after me: "Its ok to use a language feature as long as I know what I am doing." ;-D From kveretennicov at yahoo.com Tue May 11 07:00:28 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 11 May 2004 04:00:28 -0700 Subject: where is str.itersplit() ? Message-ID: <5155aad2.0405110300.4016c792@posting.google.com> Don't you think an iterator version of str.split() could be handy in some cases? You may have to split() quite a long string, but really need only one chunk at a time, not entire list at once (looks like a typical use case for iterator/generator). I am well aware of re.finditer(), but that means pulling out regex bigguns, which may be undesirable. Has there been any discussion of this topic that i missed? Do you think introduction of string methods isplit() and isplitlines() would be worth it? With v2.3 itertools and v2.4 generator expressions the "lazy" trend is obvious. - kv From p at ulmcnett.com Wed May 12 20:23:59 2004 From: p at ulmcnett.com (Paul McNett) Date: Wed, 12 May 2004 17:23:59 -0700 Subject: Finding the name of a class In-Reply-To: <40a2be14$0$3014$61fed72c@news.rcn.com> References: <40a2be14$0$3014$61fed72c@news.rcn.com> Message-ID: <200405121723.59241.p@ulmcnett.com> Edward C. Jones writes: > X().__class__ returns "" which I could > parse. Ugh. How about X().__class__.__name__ -- Paul From E.A.M.Huijbers at REMOVEstudent.tue.nl Fri May 21 07:43:45 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Fri, 21 May 2004 13:43:45 +0200 Subject: free psp host In-Reply-To: <2h644mF9e18lU1@uni-berlin.de> References: <2h4ijhF8g1alU1@uni-berlin.de> <2h644mF9e18lU1@uni-berlin.de> Message-ID: lenk wrote: > python server page :) > My bad :). Well, since I obviously never heard of it, I'm afraid I can't help you. > > Rico Huijbers wrote: > >> lenk wrote: >> >>> Hi all >>> >>> Where can I find ? >>> >>> thanks >>> >> Paint Shop Pro? >> >> I wasn't aware that application required hosting :P > > From jacek.generowicz at cern.ch Mon May 24 09:01:00 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 May 2004 15:01:00 +0200 Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> <7x1xlf8p9z.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Carl Banks writes: > > > The example above kills any attempt to turn a.bar() into a static > > > procedure call. > > > > Of course it does--but it's one method. A compiler, if it's good, > > would only make the optization on methods named "bar", and it could > > probably pare the number of possible classes it could happen to down > > to only a few. > > How could it possibly know? The reassignment of a.bar could happen > anytime, anywhere in the code. Maybe even in an eval. > > > I mean you could have a Turing nightmare on your hands, with all kinds > > of crazy setattrs and execs and stuff, in both Python and Lisp, and > > then there's not much a compiler could do but emit totally general > > code. I assume Lisp compilers do this sometimes. > > Lisp compilers might have to do that sometimes, but Python compilers > would have to do it ALL the time. Psyco took one way out, basically > generating code at runtime and caching it for specific operand types, > but the result is considerable code expansion compared to precompilation. I see how seasoned Lispers can get pretty tired of these sorts of arguments. Please bear in mind that Lisp has been the playground for a lot of very clever people whose aim was to solve difficult problems efficiently ... and they've been at it for about 3 decades before Python was even thought of. Instead of claiming that Python is something revolutionarily new in the area of dynamicity (it isn't) and that compiling it is impossible or futile (it isn't) have a look at what the Lispers learned in their study of the subject over the four decades that they have been at it. (You should only do this, of course, if you are interested in how Python might benefit from being compiled; if you don't care, then at least don't hurl unfounded "opinions" about how it is impossible because Python is so amazingly dynamic.) Of course certain things are easier to compile to efficient machine code than others. How does the existence of the problem spots take away from the usefulness of compiling the easier parts? It's possible to have significant gains. Bigger gains come with harder work. Bigger gains can be had in some areas than in others. Certain areas are more likely to be speed critical than others to a larger proportion of users (number crunching, for instance). Different compiler implementors make different choices regarding which areas of the language they target with hard compiler optimizations. Imagine that I would like to be able to write effecient numeric code in pure Python, for example ... I really don't care that any instance methods that I add will not be dispatched within a single cycle, do I? From seefeld at sympatico.ca Tue May 18 12:56:41 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 18 May 2004 12:56:41 -0400 Subject: error converting list to tuple In-Reply-To: <20040518164202.GL14843@unpythonic.net> References: <40AA1A40.9090404@sympatico.ca> <20040518164202.GL14843@unpythonic.net> Message-ID: <40AA4049.1090905@sympatico.ca> Jeff Epler wrote: > You can't use a list in all the places you can use a tuple. > The most frequently encountered difference is that you can't use lists > as keys in dictionaries. indeed, which makes the error all the more puzzling: somewhere a list is used as a key, or so it appears. But why do I get this exception while calling 'list(my_tuple)' ? Regards, Stefan From dmq at gain.com Tue May 25 17:50:18 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 14:50:18 -0700 Subject: Unification of Methods and Functions References: <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: On Tue, 25 May 2004 07:17:35 -0600, "Dave Brueck" wrote: >David MacQuigg wrote: >> >> Still this is like saying names that start with the letter 'q' are way >> >> less common than all other names, so it is OK if we have a special >> >> form for functions with such names. >> > >> >Not at all - that's a flawed analogy because variable names can be pretty >> >arbitrary and interchangable. The different types of function calls, method >> >invocations, whatever, are neither arbitrary nor interchangable. >> >> Here is a better analogy than my "no-q" functions. I will use the >> term "global method" to mean any method containing a global variable. >> We now have "normal methods", "static methods", "global methods", and >> a few others. There is no difference in the calling sequence or the >> header line between a global method and a normal method. Yet we don't >> seem to have any need for a statement like >> myMethod = globalmethod(myMethod) > >Ugh, I'm sorry but this analogy seems as bad as the no-q analogy. That's like >saying methods that contain for-loops should be declared differently - but in >neither case is the thing that matters to the caller - the interface (both the >explict means by which the function is used as well as the explicit or implicit >contract and purpose of the function) - affected. Let's move on. OK, but this issue is definitely not settled. >> I'm new to Python and object-oriented programming. I make no claim of >> language expertise or vast programming experience. > >Doesn't it give you pause that many other people, both with and without that >background, have encouraged you to give the current feature set a chance? As >in, use these features for awhile, get some more experience with them, and in >time you'll come to understand the 'why' behind them? Again, I'm not asserting >that the current language is perfect, just that the way things are might have a >purpose and/or the proposal you've come up with has drawbacks worse than what >we already have... If nothing else, waiting until you have a lot of programs >under your belt will let you argue your point from a position of strength. OK, I will wait until I have earned the right to make such a bold proposal. If I still feel the same three months from now, I'll post again, assuming I still have the time and desire to debate the issue. That is the problem with saying that only experts can propose changes. Right now the issue is a hot topic for me, because I've just been through the learning experience. Three months from now, I will probably feel the same about the technical merits of the proposal, but won't have the desire to engage in a long debate. It does disturb me that I am the sole advocate for the proposal on this thread, but I don't consider this to be a reprentative sample of users either. I think the whole discussion may be a bit intimidating for the users I am most concerned about. I guess the best counter to the argument that "Everybody disagrees with you, recant!" is -- No, I don't think that the folks who developed Ruby or Prothon would disagree with me. Python is far from perfect when people feel the need to develop a whole new language that does basically the same thing. Just to head off some flames here -- in spite of the few minor faults I see in Python, it is by far the best language for me. >> offering a perspective on Python from a technical professional >> (circuit design engineer) who intends to use it as the basis for a new >> design platform, and intends to recommend it to students and other >> technical professionsls who could benefit greatly, but don't have time >> to learn the language as well as they should. > >Then what you really ought to do is not cover more advanced topics any sooner >than is needed. Really. Nobody taking an intro-to-programming course needs to >learn about e.g. classmethods. They just don't need to. In your course pass out >a link to a web page of advanced reading for those you want to know more, and >leave it at that. Burdening them with tools they won't use anytime soon won't >be doing them a favor. Instead, teach them how to find answers to their >questions, how to experiment, so that _if_ and when they do come across it then >they can go learn it then. Who said I was going to cover class methods? The three forms I see as important are bound and unbound methods, and static methods. For the rest, including lambda functions, I'll have a link to python.org/doc or a reference to the discussion in Learning Python, 2nd ed. >> >> What can you do in the current syntax that can't be done more easily in >the >> >proposed syntax? >> > >> >Understand my code 6 months from now. Modify the code with less risk. >> >Understand the level of intent in someone else's code I'm using. >> >> OK, here is what I can extract from all this: Having a separate >> syntax for static methods is beneficial because it tells the >> programmer at a glance that he can call a method from a class without >> having an instance of that class at hand. > >That's part of it, but there's more - a static method is used in different >scenarios and for different purposes. They generally aren't interchangeable >beasts. It's these mystical qualities of the "more" part that have me mystified. Whatever those qualities may be, the same can be done with the new syntax. That leaves the only difference as what I have stated above -- the visibility of a static method. There is no other difference in actual use of the two syntaxes. >> >another thread I suggested you take the time to learn what the 2 or 3 most >> >common uses are for each of the features that will be affected, and show >both >> >the implementation and use in current Python and after your proposed >changes. >> >Not only will doing this give a clear example to everyone, it'll also show >that >> >you are at least aware of how the different function/method forms are used >> >today in _real programs_ and not contrived examples - after re-reading some >of >> >your comments I have my doubts. >> >> I have shown the 4 function/method forms I'm aware of, and how to >> translate them to a simpler syntax, in Appendix 1 of Prototypes.doc at >> http://ece.arizona.edu/~edatools/Python Have you read that? > >Yes, but as I pointed out elsewhere, it may help to write about this in some >other context than your other proposals (the fact that this is buried in >Appendix 1 under a title of "Translating Python Classes to Prototypes" doesn't >lend itself to much reader traffic). I will soon post to my website translations of the programs I have received, and any others that someone cares to send me. >But, it's better than nothing, so here goes: > >1. Bound methods - the calling appears to be identical in either version, but >one of the real values of the bound method form is being able to call the bound >method _when you don't have the instance variable handy_ (I'm just trying to >point out why it's useful). In either syntax you don't need the instance handy to call the bound method. It was bound at the time the bound method was created, and it stays bound even if the instance is deleted. Bound functions in both syntaxes are immutable. >Anyway, the fact that the methods don't have a self >variable does make things seem a little magical - with 'self' in the arg list >it makes sense to me how self.foo grabs a variable from the current instance. >Yes, there is some magic in the current implementation in that the self arg >gets passed in, but the alternative is either uglier or more magical, so it >seems like a good compromise between explicitness and practicality. I see the two ways of passing self as equally magical, and the magic is *insignificant* in either case. In one case we insert a magic first argument 'self'. In the other we set a magic global variable __self__. If I had to chose solely on the basis of minumum magic, I would go with the global variable, because students already understand global variables at this point. They also understand function arguments, but the insertion of an argument is a little startling. Again, the magic in either case is so small that I would say this is in the realm of personal preference. By the way, both Ruby and Prothon have decided *not* to pass 'self' in the first argument, and they were well aware of Python's convention when these decisions were made. >2. Unbound methods - the example uses an unbound method to "bypass" a subclass >method - that seems like a really unrealistic example. Inserting the superclass >method into the subclass, but with a different name seems equally odd. Thus, >the whole argument in favor of the "Python 3" version is unappealing. What's >downright frightening, however, is that you can write something like '__self__ >= c' and get the same behavior (for many reasons, not the least of which is >that two seemingly unrelated statements are completely linked). Wanting to call >a superclass method with the current instance is a much more likely example, >but with either form of the "Python 3" syntax it's quite unclear that that is >what is happening - because it's indistinguishable from the other calls, it's w >ay less clear what the code is doing. Thus, both newbies and experts alike will >have a more difficult time understanding (and maintaining and modifying) the >code. I agree the example is unrealistic. Rarely, if ever, will you need to call an unbound method from the module level, or over-ride the default binding to __self__. The example merely shows that it can be done, if you must. I need to show a bunch of simple cases, so people don't dwell on these extremes. The more common case ( calling an unbound method from inside another method, keeping the same __self__ as the bound instance ) looks identical to current Python, except there is no 'self' in the arg list. >3. Static methods - your page doesn't list any examples of calling the >functions, but I assume that in both cases it's Mammal.show(). Not much to be >unified here, although I don't like the fact that the "Python 3" version loses >the information that it is a static method (I don't particularly like the fact >that for the current version the staticmethod call happens after the method >body - I like some of the proposals in the related PEP), but in current Python >you actually have two indicators - there's no 'self' parameter. And again, you >have the same problem in the calling code - it's not clear what is happening, >and yet what is happening is a pretty important piece of info. In the "new" >syntax, the call could be to a static method or to a superclass method, but the >reader of the code is left wondering which one it is. I wish I could understand why highlighting a method as being a staticmethod is so important to you. Others have said that staticmethods are really rare, and could even be deprecated. So if you really needed to scan a method body, and see if it has any instance variables, this would be a rare annoyance. What is the consequence of missing the fact that a method doesn't use 'self'? What if we were to unify the two forms by going the other way -- All methods use 'self'? If an instance doesn't exist, it is created, ignored, then deleted. I know you hate the "globalmethod" analogy, but there is actually *more* justifation here for having a special form. If you call a static method from an instance, nothing bad happens. The __self__ is just ignored. If you miss the fact that a method needs global variables, all hell could break loose. :>) >4. Class methods - this example just seems broken, but perhaps I'm misreading >it. In the Python 3 version, a string is getting passed in to the class method, >and the prototype of the *string* is then displayed - makes no sense to me. In >any case, class methods are IMO a pretty advanced topic - since a main point of >yours is that you want to make OO more accessible to the lay programmer, I >don't see how class methods would come up in the discussion at all - they'd be >more relevant to a metaclass or descriptor discussion. Your right. It is broken. I wish I had a "Python 3" interpreter to check these things. I believe this is the first time anyone has looked at this section carefully, and I appreciate your effort. You are also right about classmethods being an advanced topic, and I won't be covering them in my class. I needed to show this example, because rare as they are, if there were not an automatic translation of classmethods to the new syntax, some existing programs would not survive a migration, and that alone is a cost higher than the value of any changes I am proposing. I need to move this appendix out of the introductory chapter and make it an appendix to the syntax proposal. The example should have been Mammal.show(tiger), where tiger is an instance or a class, not a "string". >> I'm also continually adding new examples under the Examples and >> Exercises link on that same page. Many of these are contributed by >> readers of this thread, including some who would rather not post here. >> (Gentle Request: A little less intolerance from some others on this >> thread might encourage more contributions from people they really need >> to hear from.) > >Equally gentle request: don't be too hasty in assuming that because people >disagree with you, their previous experience has clouded their perceptions or >made them forget what it was like to walk the path you're currently on. If I have offended anyone with a statement like this, I sincerely appologize. The intolerance I was talking about was direct personal attacks, and angry or sarcastic remarks. This group has far less of it than most other groups I have participated in. >> As for a real program, it will be a few months before I have anything >> sizable. I showed you the statefile example (in response to your >> request), but you seemed to be insulted, like you thought I was >> talking down to you, or something. > >Not at all, just realize how your message sounds on the receiving end (whether >you intended it to come across this way or not): "Even though I haven't really >used these features much, I think they should be changed. Other people say the >features have a purpose, and that the purpose becomes clear over time, but I >disagree." That, in itself, is hard to take too seriously, although I'm >impresed at how many people apparently took the time to think about your >suggestion. I'm sorry that my "message" comes across as you suggest. I try always to start with an open mind. If I don't understand the purpose of a feature, I say "show me". Only after repeated attempts to get something more concrete, do I tentatively reach a different conclusion. I'm skeptical, but I think I'm more cautious than most in not making dogmatic statements without understanding an issue. I also have no hesitation to acknowledge when I'm wrong. I was pushing "prototypes" ( as done in Prothon ) until Michele Simionato showed that they could be done with the existing machinery in Python. They are still in my proposal, but with a clear statement that they won't make the next revision unless someone shows that Michele's "prototype.py" module is missing something important. On the issue of staticmethods, I use them more freely than most others on this thread would prefer. I disagree that they have a fundamental purpose in life, but I respect others' opinions, and I have my receiver at maximum sensitivity, in case someone were to post an example that would make me say - Oh cool, now I understand the true purpose of staticmethods, and the reason they deserve a special syntax. >Best of luck, >Dave You too. And again, thanks for the careful review. -- Dave M From bptonner at yahoo.com Sun May 2 17:53:44 2004 From: bptonner at yahoo.com (Brian) Date: 2 May 2004 14:53:44 -0700 Subject: Keyboard input magnetic stripe reader and wxPython Message-ID: <5b17ec49.0405021353.460ebdad@posting.google.com> This probably has a simple answer: I need to capture data from a magnetic stripe reader, which is fed through the keyboard port. I want to use wxPython for the application (under Windows). I can read this data in a text control, but only if the text control has the focus. Ideally, I'd use a text control that could be made invisible, and that could be forced to have the focus programmatically. That way I could use the other text control methods, and not have to write these methods from scratch. In other words, does a method exist in wxPython that will let me catch keyboard characters 'on demand' and store them in a string buffer? If you're curious, the application is a museum kiosk, where visitors will be able to swipe their credit cards, driver's licenses, etc., and see what information is stored there. I'd like to build this from as many high-level objects as possible. Thanks, Brian From andreas at kostyrka.org Mon May 31 08:13:19 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 31 May 2004 14:13:19 +0200 Subject: API : constness ? In-Reply-To: References: Message-ID: <1086005599.2280.76.camel@andi-lap> Am Mo, den 31.05.2004 schrieb Beno?t Dejean um 03:26: > it's also for a simple reason, eg using PyArg_ParseTupleAndKeywords > > using const helps gcc to move these data to the text segment Don't think so. At least not if you are compiling without -traditional or -fwritable-strings: andreas at andi-lap:~> cat t.c main() { char *x = "ABC"; x[0] = 'D'; } andreas at andi-lap:~> gcc -fwritable-strings -o t t.c andreas at andi-lap:~> ./t andreas at andi-lap:~> gcc -o t t.c andreas at andi-lap:~> ./t Speicherzugriffsfehler andreas at andi-lap:~> Andreas From davidf at sjsoft.com Fri May 14 10:07:23 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 14 May 2004 16:07:23 +0200 Subject: ANN: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: References: Message-ID: Paul McNett wrote: > David Fraser writes: > > >>My gzip doesn't like your dabo unix source tar.gz files ... >>are they OK? > > > No they weren't. My Python upload script was converting them > from binary to ascii by adding the linefeeds for the > appropriate platform. This 'feature' has been fixed, with good > files uploaded. Sorry for the inconvenience. > Thanks David From jcm at FreeBSD-uk.eu.org Thu May 6 18:35:20 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Thu, 6 May 2004 23:35:20 +0100 Subject: How to change tkinter GUI look-and-feel? Message-ID: <20040506223520.GA40806@dogma.freebsd-uk.eu.org> I saw some screenshots of mayavi. Is there any way we can set tkinter to use the motif (or some other toolkit under Unix) rather than the default? jm -- My other computer is your Windows box. From p_s_oberoi at hotmail.com Tue May 4 16:41:10 2004 From: p_s_oberoi at hotmail.com (Paramjit Oberoi) Date: Tue, 04 May 2004 15:41:10 -0500 Subject: doctest: address in output References: Message-ID: > > >>> mymodule.do_something() > > > > Why not just change your doctest to be > > >>> import mymodule > >>> isinstance(mymodule.do_something(), mymodule.coolObj) > True > > ? That avoids two problems, the issue of addresses and the possibility that > the repr() of your coolObj class changes. Because the former seems to be *much* easier to read than the latter. The return value of the function is designed to be ignored in normal use. Doing something with it, like assigning it to a variable or using isinstance() as you suggest, would make the documentation both unclear as well as harder to read than it should be. Making a doctest hard to read would go against the purpose of having doctests at all. I may as well use the unittest module then. -param From della at toglimi.linux.it Wed May 26 08:23:10 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 26 May 2004 12:23:10 GMT Subject: Some Newbie Questions In-Reply-To: <40b47710@e-post.inode.at> References: <40b47710@e-post.inode.at> Message-ID: Leopold Schwinger wrote: > (1) Is there any operator in Python in order to call a Member-Function > from a class without creating an instance of the class? (In C++ and PHP > there ist this operator "::" ::) Just call it. :-) When you are using methods from instances, the first argument (the one that is usually called "self") is automagically bound to the instance. When you access it from the class, this won't happen (and the method, in this case, is called "unbound"). For instance: >>> class A(object): ... def foo(self): ... print self ... >>> a = A() >>> a.foo() <__main__.A object at 0x401f7d6c> >>> A.foo(a) <__main__.A object at 0x401f7d6c> >>> A.foo >>> a.foo > You have an interactive prompt, try playing with it! :-) > (2) Is there any way to dynamically import modules, where the name of > the module is not known during implementation but can be defined durch > scipt execution? Think of lots of different config-Files, which differ > by Path & Name but the variables are all named equal, and i want to > import a special config-File during the execution of the script. You can use the __import__ built-in. For your problem, look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/283531 . > (3) Is there any way to obtain a kind of "trace"-Info (the actual > filename and codeline) in order to provide some debug-Info in the case > of errors (In C++ and PHP there are these "__line__" and "__file__" > functions, For Python I have only found .__dict__ and dir()) traceback module. Keep the Library Reference under your pillow! :-) -- Ciao, Matteo From Laura.McCord at doucet-austin.com Fri May 21 09:58:45 2004 From: Laura.McCord at doucet-austin.com (Laura McCord) Date: Fri, 21 May 2004 08:58:45 -0500 Subject: Deleting Directories Message-ID: <573C3D25471BAE4DB0CDA25B1FE6C3832E342A@aa16exc.int.doucetandassociates.com> Hi, I need to delete all directories in /var/www/html/test that are older than five days. I am new to python so how would I get started? Any tips or suggestions would be appreciated. Thanks, Laura From kveretennicov at yahoo.com Mon May 24 09:59:54 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 24 May 2004 06:59:54 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> <5sl4o1-crf.ln1@eskimo.tundraware.com> <10avdpe73rnj20d@corp.supernews.com> <8a0bb987.0405222327.78ef180e@posting.google.com> <10b2dvrfqhmbm5a@corp.supernews.com> Message-ID: <5155aad2.0405240559.48e2f7cd@posting.google.com> "Michael Geary" wrote in message news:<10b2dvrfqhmbm5a at corp.supernews.com>... > > import re > reWhitespace = re.compile( '\s+' ) > for line in file( 'inputFile' ).readlines(): > print reWhitespace.split( line.strip() ) > > But for a large file, the second version will be faster because the regular And you'll want to use "for line in file('inputFile')" instead of "for line in file('inputFile').readlines()", especially for large files ;) - kv From peter at engcorp.com Fri May 21 19:14:07 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 19:14:07 -0400 Subject: Where's the demo for wxpython 2.5 In-Reply-To: References: Message-ID: john fabiani wrote: > Peter Hansen wrote: >> What platform are you on? Under Windows, a link to the demo is >> put into your Start menu when you install and the code is under >> site-packages/wx/demo. > > Sorry, I met the actual files (I have the old files) for download. Every > time I attempt to download the file from wxpython's website it states > the files are not available or corrupt. Then I don't understand how you managed to get 2.5 in the first place. And if you did get it, why you don't already have the demo files. Did you delete them? -Peter From wolf_tracks at invalid.inv Tue May 4 08:05:48 2004 From: wolf_tracks at invalid.inv (W. Watson) Date: Tue, 04 May 2004 12:05:48 GMT Subject: Setting an Image File Values In-Reply-To: References: Message-ID: Mike C. Fletcher wrote: > W. Watson wrote: > >> I have a 640x480 b/w bmp image file that can be converted to a dat >> file. I would like to convert the value of each pixel that is below >> say 120 units to exactly 40 units. > > > ... > >> python -c "open('mask.dat','w').write(chr(40)*640*480)" > > > Well, if you're going to take this as the baseline, then we can do some > pretty darn simple stuff indeed: > > >>> import string > >>> def createMask( threshold=120, target=40 ): > ... """Create 256-char mapping of destination characters""" > ... return string.maketrans( "".join( [chr(x) for x in > range(threshold)]), chr(target) * threshold ) > ... > >>> data = open( "p:\\drawcurve.py", 'rb' ).read() # mode 'rb' is > important! use 'wb' to write > >>> mask = createMask() > >>> data > "'''Test of the glVertex function\r\n\r\nDrawing TT glyphs as Cubic > splines...\r\n\thttp://support.microsoft.com/support/kb/articles/q243/2/85.asp\r\n\r\n'''\r\nfrom > OpenGLContext import testingcontext\r\nBaseContext" > >>> data.translate( mask ) > '((((((((((((((((((((((x((((((((((((((((((((((((((y(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((x(((((((((((((((((((((x((((((((((((x(' > > >>> ord('x') # just to see why x and y show up... > 120 > > Of course, most Python programmers, when faced with a problem like this > would turn to either PIL (Python Imaging Library) or Numpy (Numeric > Python), but if all you need is quick-and-dirty, there you go. > > Have fun, > Mike Having only seen the example snipet I gave as an example of python coding, what you wrote comes as a real surprise. This reminds me of a programming language called APL. It really had odd syntax. What are >>>, ..., and all those {{{{{? Not to mention the 120 at the end. The snipet suggests that a python program can be run as a command line (python -c) like Perl. I would have thought a multi-line program to be executed would look something like python -c {line 1, line 2, line 3, etc.} It looks like I need to look at some python examples to get a feel for what this is about. From anthony at interlink.com.au Sat May 15 06:33:35 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 15 May 2004 20:33:35 +1000 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <16549.28439.793278.500088@montanaro.dyndns.org> References: <67B3A7DA6591BE439001F2736233351202B479BA@xch-nw-28.nw.nos.boeing.com> <16549.28439.793278.500088@montanaro.dyndns.org> Message-ID: <40A5F1FF.3040902@interlink.com.au> Skip Montanaro wrote: > Submit the necessary magic and I'm sure it would get incorporated into the > distribution. I think the basic pieces are there. Distutils can build RPMs > I believe. I know Sean Reifschneider builds RPMs with some small lag time > after a release. Perhaps what he does (a spec file?) can be incorporated > into the distribution and an extra target added to the Makefile to simplify > building it. It's not _quite_ that simple, as the RPMs have to be signed. Sean has most of the magic worked out, and hopefully one day this can be all included in the appropriate PEPs (101 and 102). Anthony -- Anthony Baxter It's never too late to have a happy childhood. From nospam-trice at comcast-nospam.net Tue May 11 02:55:42 2004 From: nospam-trice at comcast-nospam.net (Tim) Date: Tue, 11 May 2004 02:55:42 -0400 Subject: printing float as formatted dollars References: Message-ID: "Peter Hansen" wrote in message news:V72dncRoWf6o7gbdRVn-gw at powergate.ca... > Tim wrote: > > > "Larry Bates" wrote in message > > news:YtqdnZOyj_KSfArdRVn_iw at comcast.com... > > > >>Here is a function I wrote and use. Note: floats > >>have rounding "issues" when they get very large. > [snip long code] > >> > > Thanks for the code!, it was a big help. I had started trying to piece > > together some logic (below), but I know there are holes in it (negative > > numbers, for one). > [snip also long code] > > I still find this one much easier to swallow (from the > aforementioned other thread). > > >>> import re > >>> s = 1234567.89 > >>> '$' + re.sub(r'(?<=\d)(?=(\d\d\d)+(\.|$))', ',', str(s)) > '$1,234,567.89' > > -Peter I agree. This is a very concise solution. Since I'm new to both Python and regular expressions, it took some follow-up reading to understand how/why this works. So, I guess in addition to a solution you could say that it also led me to a basic understanding of regular expressions which seems well worth having (and which I otherwise probably would have regretfully continued to ignore). I appreciate your help, Tim From gherron at islandtraining.com Fri May 7 14:53:51 2004 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 7 May 2004 11:53:51 -0700 Subject: polymorphism w/out signatures? In-Reply-To: <997a06e0.0405071007.3b903c7b@posting.google.com> References: <997a06e0.0405061128.6768676d@posting.google.com> <997a06e0.0405071007.3b903c7b@posting.google.com> Message-ID: <200405071153.52052.gherron@islandtraining.com> On Friday 07 May 2004 11:07 am, pugnatio2 at yahoo.com wrote: > Thanks to all who replied. I think I've got it straight now, and by > the way I did use "polymorphism" incorrectly; I should have said > "method overloading." > > I guess I have my choice between separate callables and using type() > or isinstance(). > > What I had hoped to do was something like: > > xmlDoc = myFormat2XML(obj) > > where 'obj' could be either a text string or a sequence of lines. It's > not just a problem of whether a scalar or sequence object is passed > in. Strings, lists, and tuples are all sequences. > > The deprecation I read, about avoiding type() (p. 129 of _Python in a > Nutshell_) said it interfered with (true) polymorphism (via > inheritance). That deprecation is correct. Instead of using type(), use isinstance(param, type). The call to isinstance returns True if param is an instance of the given type or any subtype thereof. This works correctly for inheritance, giving you the polymorphism you want. Gary Herron From rdunning at bsc.edu Wed May 26 19:25:16 2004 From: rdunning at bsc.edu (Rodney Dunning) Date: 26 May 2004 16:25:16 -0700 Subject: Question from a beginner Message-ID: <44c2a239.0405261525.5b22cb88@posting.google.com> Hello, I've just picked up python to create some 3D visuals (using VPython) for a physics class I'm developing. While writing a program, I developed a "bug" that is reflected in the code below. When executed, *both* Test1 and Test2 are changed. Can someone explain this to me? Why is Test2 changed? from visual import * from __future__ import division ##Variable tester a = vector(1,0,0) Test1 = a Test2 = a print "Test1 = ",Test1 print "Test2 = ",Test2 Test1.x += 3 print "Test1 = ",Test1 print "Test2 = ",Test2 ##End code I've programmed extensively in Fortran-90. Is there anything in python analogous to the PARAMETER keyword in Fortran-90, such as integer, PARAMETER :: i = 10 !*** the value of i cannot be changed, period. Thanks for your help. -- Rodney Dunning Assistant Professor of Physics Birmingham-Southern College From anders.soendergaard at nokia.com Mon May 10 08:00:03 2004 From: anders.soendergaard at nokia.com (Anders =?UTF-8?B?U8O4bmRlcmdhYXJk?=) Date: Mon, 10 May 2004 12:00:03 GMT Subject: Processing huge datasets Message-ID: <79Knc.15953$k4.322398@news1.nokia.com> Hi, I'm trying to process a large filesystem (+20 million files) and keep the directories along with summarized information about the files (sizes, modification times, newest file and the like) in an instance hierarchy in memory. I read the information from a Berkeley Database. I'm keeping it in a Left-Child-Right-Sibling instance structure, that I operate on recursively. First I banged my head on the recursion limit, which could luckily be adjusted. Now I simply get MemoryError. Is there a clever way of processing huge datasets in Python? How would a smart Python programmer advance the problem? I'm looking at rewriting the code to operate on parts of the hierarchy at a time and store the processed data structure in another Berkeley DB so I can query that afterwards. But I'd really prefer keeping all things in memory due to the huge performance gain. Any pointers? Cheers, Anders From gumuz at NO_looze_SPAM.net Thu May 27 07:03:02 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Thu, 27 May 2004 13:03:02 +0200 Subject: Web services (xmlrpc) strategies Message-ID: <40b5cacd$0$4922$4d4ebb8e@news.nl.uu.net> Hi, I am planning on creating a system using a xml rpc webservice. Simple XML RPC examples are easy to find on the web, but I am actually looking for some strategies or 'best practices' information on the subject. I am using python+twisted to do this, but language/framework independant design information is equally welcome. I hope my request is clear enough. regards, Guyon From fumanchu at amor.org Mon May 3 19:22:53 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 3 May 2004 16:22:53 -0700 Subject: fixedpoint cmp conundrum Message-ID: Consider the following: PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import fixedpoint >>> a = fixedpoint.FixedPoint(3, 2) >>> bunch = [None, 12, a] >>> bunch.index(None) 0 >>> bunch.index(12) 1 >>> bunch.index(27) Traceback (most recent call last): File "", line 1, in ? ValueError: list.index(x): x not in list ...so far, this is normal and expected. >>> bunch.index(a) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\Lib\fixedpoint.py", line 316, in __cmp__ xn, yn, p = _norm(self, other, FixedPoint=type(self)) File "C:\Python23\Lib\fixedpoint.py", line 482, in _norm y = FixedPoint(y, x.p) File "C:\Python23\Lib\fixedpoint.py", line 255, in __init__ raise TypeError("can't convert to FixedPoint: " + `value`) TypeError: can't convert to FixedPoint: None Mmrph! I could fix this by: 1. Iterating through "bunch" by hand and trapping TypeError, 2. Overriding or hacking the __cmp__ function in fixedpoint, or 3. Overriding or hacking the _norm function in fixedpoint The question is: given that there are multiple places to "fix" this, where should I do so? Robert Brewer MIS Amor Ministries fumanchu at amor.org From paddy3118 at netscape.net Fri May 28 20:41:44 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sat, 29 May 2004 01:41:44 +0100 Subject: preftree 0.3 released In-Reply-To: <8765agba17.fsf@blakie.riol> References: <40B72942.8060200@sjsoft.com> <8765agba17.fsf@blakie.riol> Message-ID: Wilk wrote: > David Fraser writes: > > >>Following up on a promise in the Config discussion ... >> >>preftree has been released under the Python license. >>You can get version 0.3 from >>http://davidf.sjsoft.com/files/preftree-0.3.tar.gz > > > thanks, it look a lot like yaml... Don't you think it could be a layer > on top of yaml ? > The example shows string, integers and (nested) dictionary types. I presume floating point would be obvious, and is included but what about lists? Cheers, Pad. From xaver_hinterhuber at web.de Tue May 11 02:26:48 2004 From: xaver_hinterhuber at web.de (Xaver Hinterhuber) Date: Tue, 11 May 2004 08:26:48 +0200 Subject: function causing core dump References: Message-ID: Hi Robert, I don't show you codeString because it is a real string variable. And yes, its uncompiled. The user in my program enters a python program in this variable without a def statement and then the code is executed and the result returned. Maybe you can help me to add a "def f():" to the codeString, take care of the indentation and then execute the code? I really don't know how to handle the indentation thing. A "def f():\n"+codeString is easy, but this doesn't solve this issue. Greets Xaver "Robert Brewer" schrieb im Newsbeitrag news:mailman.398.1084203482.25742.python-list at python.org... Xaver Hinterhuber wrote: > I build a function with the following code segment: > > codeObject = new.code( > 0, # argcount > 0, # nlocals > 0, # stacksize > 0, # flags > codeString, # code > (), # consts > (), # names > (), # varnames > 'content', # filename > 'content', # name > 3, # first line number > codeString # lnotab > ) > f = new.function(codeObject, dict, 'f') > f() > > Everything runs fine, until the function is called with f(). > When python tries to execute f(), the core dump happens. > I don't have any clue why python core dumps. > The codeString is nothing complex, its a one-liner. > Could you plz give me some tips what I have to do? As usual, the tip is: include the one piece of information you left out of your post. What is the value of codeString? My first guess is that codeString is something like "return None", or some other string of uncompiled Python code, in which case, you should use eval() instead of new.code and new.function. Those two are used for creating code objects and functions from a _compiled_ codestring, like '\x88\x00\x00Sd\x00\x00S'. In addition, nearly all of the args passed to new.code are *very* important, and cannot simply be set to 0. If you want more info, show us the codeString! :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From scott.novinger at abxair.com Mon May 3 12:57:40 2004 From: scott.novinger at abxair.com (scott) Date: 3 May 2004 09:57:40 -0700 Subject: Best way to serve Python Web Pages? Message-ID: <9d393e9d.0405030857.787b2440@posting.google.com> In everyone's humble opinion, what do you think would be the best way to serve web pages using the Python Language? For example, would it be an Apache/MySQL/Python, Zope, or homebrewed approach? My personal requirements would include: 1. Relatively easy to program 2. Lot's of resources/ examples that I can leverage to reduce development time. 3. Something that I can administer easily and teach other people to manage. 4. Low cost and Open Source. 5. Something that is portable across various OS's. 6. Something relatively compact. Is it smart to compartmentalize an application by using the Apache/MySQL/Python approach? Or is it better to keep it all under one roof via the Zope approach? Just curious to see how other people are building web applications using Python. Thank you, Scott From tzot at sil-tec.gr Wed May 12 05:46:39 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 12 May 2004 12:46:39 +0300 Subject: OT: Idea for Python T-shirt References: <2472a0tgrcv1oc3mbu0ndljogpc5out9da@4ax.com> Message-ID: On Tue, 11 May 2004 15:03:13 -0400, rumours say that Peter Hansen might have written: >> [snip "nibbles exploding with desire"] >> >> >>>Also, I don't get it... >> >> >> Based on the hungarian phrase-book sketch from the Flying Circus... "my >> nipples explode with desire!" > >Yeah, that part was obvious (to an MP fan). But why the bit-eating >snake then? It's gratuitous at that point. Oh, wait, were the ones >and zeros supposed to be "exploded nibbles"? That's a reach... Well, I won't pretend that my pun was cleverly funny, I'll just say that I thought it was simply funny... My whole idea was of Python processing happily data, which grouped in fours were nibbles, and there came the pun of s/p/b/g as Tim said; the "desire" instead of "delight" part of course was a misteak due to weak memory. PS I would gladly buy an "import this" T-shirt too. I think that T-shirts could be an alternative income source for PSF. -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From greg at cosc.canterbury.ac.nz Tue May 18 23:45:47 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 19 May 2004 15:45:47 +1200 Subject: Circular imports In-Reply-To: References: Message-ID: <2h03jdF7cu1cU1@uni-berlin.de> Edward Diener wrote: > Can > anybody tell me if there are any situations where circular imports cause > problems and, other than a redesign to eliminate it, if there are any other > ways around those problems ? Circular imports can cause problems in this situation: # module A import B def foo(): print "Fooey" # module B from A import foo def blarg(): foo() If module A gets imported first, it immediately imports B, which tries to import foo from A before it's been defined. The problem can be avoided by rewriting B as follows: # module B import A def blarg(): A.foo() This defers the lookup of foo in A until B.blarg is called, by which time A will hopefully have finished initialising itself. In general, if circular imports are involved, always use "import X" and refer to "X.n", rather than using "from X import n". This will avoid most circular import problems. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From SzeplakiJ at spbinvest.hu Mon May 10 03:06:31 2004 From: SzeplakiJ at spbinvest.hu (Szeplaki Julianna) Date: Mon, 10 May 2004 09:06:31 +0200 Subject: Virus Found in message "Your document" Message-ID: Norton AntiVirus found a virus in an attachment you (python-list at python.org) sent to szeplakij at spbinvest.hu. To ensure the recipient(s) are able to use the files you sent, perform a virus scan on your computer, clean any infected files, then resend this attachment. Attachment: your_document.pif Virus name: W32.Netsky.D at mm Action taken: Clean failed : Quarantine succeeded : File status: Infected -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1659 bytes Desc: not available URL: From fernando at localhost.localdomain Tue May 4 14:33:44 2004 From: fernando at localhost.localdomain (fernando at localhost.localdomain) Date: Tue, 04 May 2004 18:33:44 GMT Subject: tkinter question... Message-ID: Hi there, When I try to run IDLE I get the error bellow. Can anybody help? Thanks! [fernando at exodus fernando]$ idle Traceback (most recent call last): File "/usr/local/bin/idle", line 3, in ? from idlelib.PyShell import main File "/usr/local/lib/python2.3/idlelib/PyShell.py", line 19, in ? from Tkinter import * File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter From john at neggie.net Thu May 20 15:02:10 2004 From: john at neggie.net (John Belmonte) Date: Thu, 20 May 2004 15:02:10 -0400 Subject: hash comments in interactive shell Message-ID: <40AD00B2.2020401@neggie.net> Hello, I'd like to know what the rationale is for hash comments yielding a continuation prompt (PS2) in the Python shell. I'd like to put such comments in interactive examples, but the output is hard to follow: >>> a = 5 >>> # and now for some multiplication ... >>> a * 10 50 I would prefer that the output be: >>> a = 5 >>> # and now for some multiplication >>> a * 10 50 For comparison, end of line comments don't behave this way, which seems inconsistent: >>> a = 5 >>> a * 10 # end of line comment 50 -John -- http:// ift ile.org/ From heikowu at ceosg.de Fri May 21 13:32:03 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Fri, 21 May 2004 19:32:03 +0200 Subject: Python2.2 + mailbox. Bug???? In-Reply-To: References: <70c4ef5f.0405210756.187b7f07@posting.google.com> Message-ID: <200405211932.03292.heikowu@ceosg.de> Am Freitag, 21. Mai 2004 18:18 schrieb Noam Raphael: > I assume that when you write "./program.py < mboxfile.txt", Python knows > that sys.stdin is a regular file, so it can do seek on it (for example, > go back to its beginning). It's not Python that knows that you can do a seek on the file, but what the shell does when you pipe a file to a program is to call filefd = open(file,"r"); fdup2(filefd,0) (0 = stdin) just before the shell forks to start the program. sys.stdin is always just connected to the filedescriptor 0 which was passed in, which in turn is connected to a file file-descriptor by the shell, which in turn is seekable. > When you write "cat mboxfile.txt | > program.py", the program cat outputs the file mboxfile.txt into > sys.stdin byte by byte, so you can't do seek on it. Now, when you pipe something into another program, exactly this gets generated: a pipe is generated using readfd, writefd = pipe() whose write end is connected to the stdout (fdup2(writefd,1); fd 1 = stdout) of the first program when the shell forks to start it, and whose read end is connected to stdin (fdup2(readfd,0); fd 0 = stdin, as before) of the second program, again when the shell forks to start it. This means that sys.stdin of the Python program, which again is connected to filedescriptor 0 is now connected to a pipe file-descriptor. Pipes are not seekable, and that's exactly what the exception is telling you. So, what do we learn from this? The mbox format needs a filedescriptor which is seekable to be able to parse it (err, I guess it wouldn't need this, but who knows, look at the source luke!), so you need to pass a reference to a file-like object which implements seek (or at least a file-descriptor which is seekable, which pipes are not). HTH! Heiko. From guineapig at pi.be Thu May 27 04:02:30 2004 From: guineapig at pi.be (GuineaPig) Date: Thu, 27 May 2004 10:02:30 +0200 Subject: calendar by week Message-ID: Hello gurus, Does anybody know of a function/module that can help me with the following problem: In my app the user can encode the starting and ending hours of his workdays. The app calculates the time the user worked (per week) and the user's overtime. The results are exported to an excel-sheet for printing. One thing that I would like to accomplish is that the user has to only give in the weeknumber of the year. The app should then write the dates in this week to the excel-sheet. I've been looking at the calendar and time modules but I don't quite see a solution there (maybe there is though, maybe I'm just too much of a newbie.) Tnx a lot! Tom From shalabh at cafepy.com Tue May 4 23:35:54 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Tue, 04 May 2004 20:35:54 -0700 Subject: Different values for property vs attribute??? In-Reply-To: References: Message-ID: j_mckitrick wrote: > I forgot to mention, I have another class like this: > > def getauditcheckpass(self): > return self.state[AUDITCHK] == PASS > > # properties > auditcheckpass = property(getauditcheckpass) > > > and it seemed to work ok. From http://www.python.org/2.2.3/descrintro.html#property : Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its __dict__ without calling the property's set method... -- Shalabh From lbates at swamisoft.com Tue May 11 14:55:20 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 11 May 2004 13:55:20 -0500 Subject: Make one GUI containing java and C++ componants ? References: <26079f73.0405102305.687f19e4@posting.google.com> Message-ID: <2a6dnVVE-sR5Tj7dRVn-vg@comcast.com> http://www.etc.cmu.edu/panda3d/ Might we worth a look. -Larry "bart59" wrote in message news:26079f73.0405102305.687f19e4 at posting.google.com... > Hello, > > I have two application: > one in java, which use awt and wing componants as a GUI. > one in C++, which is a 3d engine, then it display in a window a 3D > modele. > > I'm looking for a solution to combine these two interfaces in one > containing the Java componant + the C++ window . > > Is there a way to manage with that? > > JNI doens t seem to be the good approach, it should be difficult to > render the c++ output in a java component: moreover, interactions with > the mouse are required in the ed engine... > > I heard about python, but I can t see the real advantage that can give > me python. > > Any solution? > > thank you very much for your help. > > Bart From shalabh at cafepy.com Wed May 26 09:16:24 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Wed, 26 May 2004 06:16:24 -0700 Subject: modifying mutable list elements in a for loop In-Reply-To: <9d5509fa.0405260439.175797e@posting.google.com> References: <9d5509fa.0405260439.175797e@posting.google.com> Message-ID: Peter Ballard wrote: > Whew. I hope that title is descriptive! > > Hi all, > > The python tutorial tells me "It is not safe to modify the sequence > being iterated over in the loop". But what if my list elements are > mutable, such as lists or objects, e.g. > > a = [[1,2], [3,4], [5,6], [7,8]] > for coord in a: > coord.append(10) > print str(a) > > When I tried it, it gave the "expected" answer, i.e. > > [[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]] > > It worked, but is it safe? I can't see why it wouldn't be, but > technically I have broken the rules because I have modified the > sequence which is being looped over. You're fine. You didn't modify the sequence a, but other objects which happened to be in the sequence. What the tutorial warns you against is doing something like a.append([]) or a.pop() in your loop. Then you'd be modifying the sequence itself. -- Shalabh From winexpert at hotmail.com Thu May 27 13:49:43 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 17:49:43 +0000 Subject: how to store binary file data to a database blob Message-ID: Hi Ivan, Yep ur right. I'm hoping to avoid the politics of this. Basically I've been told to store it in the db and that's what will happen. The thought is that its easier to let the DB manage the data than it is to have to worry about some external process or person munging the data file stored on the filesystem at some location. With the db approach, if the db is munged you lose it all (up to the recovery point, backup, etc). With the file approach you could get just as hosed or worse, if the db loses its 'pointers' via fieldname contents to the files on the disk. So with all that in mind, we're storing blobs in our database. I have found out that I need to do something like this: insert a record (with no data) ask the DCOracle driver to hand me a 'pseudo file object for that record's blob' write the data to the pseudo file ... David ------- Tracfone: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html From: Ivan Voras To: python-list at python.org Subject: Re: how to store binary file data to a database blob Date: Thu, 27 May 2004 17:39:33 +0200 Benjamin Niemann wrote: using the % operator. This works at least for arbitrary strings (and that's the way to handle strings, if you don't like SQL injections ;) But I never tried this with blobs - perhaps they need some special treatment (thinking e.g. of laaarge files)... It is generally NOT a good idea to write large binary strings to a (sql relational) database, even if it has blobs. A much more robust (and faster) solution is to save general data about the blob in the database (its size, name, whatever, etc.) and the actual data in a separate file in the filesystem (or maybe in a "db" database (BDB, GDBM...), if you really like them). YMMV, mostly depending on the size of blobs. :) -- http://mail.python.org/mailman/listinfo/python-list _ _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From luked at xplantechnology.com Tue May 18 23:07:30 2004 From: luked at xplantechnology.com (Luke) Date: Wed, 19 May 2004 13:07:30 +1000 Subject: Is WeakValueDictionary thread-safe? Message-ID: Hi, Is weakref.WeakValueDictionary supposed to be thread-safe? This small example script (attached) uses two threads to add and remove items from a WeakValueDictionary. It is giving me a number of error messages on stderr (with 2.3.3 & 2.3.4rc1) which look like this: Exception exceptions.KeyError: 'bar' in ignored Should this work without printing these errors, or have I misunderstood? I just wanted to check with this newsgroup before filing a bug... Thanks, Luke. -------------- next part -------------- A non-text attachment was scrubbed... Name: tryweakref.py Type: text/x-python Size: 438 bytes Desc: not available URL: From jason at __no_spam__mobarak.name Tue May 18 00:36:19 2004 From: jason at __no_spam__mobarak.name (Jason Mobarak) Date: Mon, 17 May 2004 22:36:19 -0600 Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: Daniel Klein wrote: > Hello, > > I'm quite new to Python, and since a not-so-superficial look into the > docs didn't answer my question (although it still feels quite basic), I > decided to turn to this place: > > Is there a way to 'extract' a dictionary into the current namespace? > That is, if you have > {'foo' : 23, 'bar' : 42} > you would get a variable foo with value 23 and a variable bar with value > 42? Such a function would of course only work on string keys and would > probably have to check that, but still, it sounds practical enough that > surely someone else thought of it before. > > Daniel > Is this illegal? >>> import __main__ >>> d = {'foo':'oof','bar':'rab','baz':'zab'} >>> for k,v in d.items(): ... setattr(__main__, k, v) ... >>> foo,bar,baz ('oof', 'rab', 'zab') -- Jason From sean_berry at cox.net Wed May 12 00:47:18 2004 From: sean_berry at cox.net (Sean Berry) Date: Tue, 11 May 2004 21:47:18 -0700 Subject: Urllib.urlencode question? Message-ID: I have two lists... one like the following, list1 ... ['userid', 'username', 'email'] and the other like this, list2 ... [['sean', 'Sean Berry', 'sean_berry at cox.net'], ['pam', 'Pam Ward', 'pam_ward at cox.net']] Both lists are much more extensive, the first being a list of about 10 strings, and the second being a list of 20 lists each containing the values corresponding to the first lists 10 strings. But, in order to simplify an explanation I will use the previously described lists for my question. I am going to pass this info to Flash in a url encoded string. I can do this by parsing through the lists in list2 and appending a string to another global string, then print this final string. But I run into problems because the characters like '@', ' ', and '*' are not encoded. I have been experimenting with urllib.urlencode and zipping the two lists together. But the desired result will be in the form n=2&userid0=sean&username0=Sean%20Berry&email0=sean_berry%40cox.net&userid1= pam&username1=Pam%20Ward&email1=pam_ward%40cox.net How can achieve adding the numbers to the end of the variable names so that they can be used by Flash's loadVars function. Thanks for the help. From dpharris76 at msn.com Tue May 25 00:44:15 2004 From: dpharris76 at msn.com (Dave Harris) Date: Mon, 24 May 2004 23:44:15 -0500 Subject: Tkinter - One Canvas to Rule Them All? Message-ID: I derived two Frame classes and created a Canvas in each. I was extremely surprised when frame1.canvas.delete('all') erased the image in frame2.canvas! I resolved my trouble by assigning tags and doing the deletion by tag. No big deal. I deduce from this behavior that there is a single database behind the scenes for the Canvas implementation. Just an observation. Maybe it will save somebody some head-scratching... Dave Harris From grante at visi.com Thu May 13 22:26:58 2004 From: grante at visi.com (Grant Edwards) Date: 14 May 2004 02:26:58 GMT Subject: struct doesn't handle NaN values? References: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> Message-ID: <40a42e72$0$8517$a18e6209@newsreader.visi.com> In article , Jeff Epler wrote: > >> In order to provide robust translation between native and IEEE >> floating point formats, Python is going to have to know what >> the native format is. > > No, it merely needs to use ldexp() with the proper values. If you don't know what the native representations for NaN and infinity are, how do you know what to pass to ldexp() when the conversion routine has been passed an IEEE NaN/Inf and needs to create a native one? If you do pass ldexp() the proper exponent for a native NaN, are you sure it will work? I would expect that doing so would be an error. How do you detect a native NaN using ldexp() or frexp() or some other standard C library function? > Did you try reading what Python actually does? Yes. > See Objects/floatobject.c's function family _PyFloat_{Unpack,Pack}{4,8} I did. It states quite clearly in floatobject.h: Bug: What this does is undefined if x is a NaN or infinity. Bug: What this does is undefined if the string represents a NaN or infinity. I'd like to fix those Bugs so that the conversions between native NaN/Inf and IEEE NaN/Inf works. I don't see how you can get around the requirement for knowledge about the native representation of NaNs and Infinities. -- Grant Edwards grante Yow! I'm in ATLANTIC CITY at riding in a comfortable visi.com ROLLING CHAIR... From mrbiglesworth3 at yahoo.com Tue May 25 08:09:32 2004 From: mrbiglesworth3 at yahoo.com (Josh) Date: Tue, 25 May 2004 12:09:32 -0000 Subject: SSL Socket EOF protocol violation Message-ID: I'm getting an error I dont understand. Here is the output: Content-Type: text/html Traceback (most recent call last): File "C:\PROGRA~1\APACHE~1\APACHE2\CGI-BIN\test.py", line 12, in ? s.connect( host, port ) File "", line 1, in connect TypeError: connect() takes exactly one argument (2 given) Here is the code: #!c:/Python23/python.exe import socket print "Content-Type: text/html\n\n" host = "www.paymentsgateway.net" port = 6051 s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) s.connect( host, port ) ssl_object = socket.ssl( s ); I don't understand the error, because I think connect takes 2 arguments according to the docs at the python.org site. Thanks for any help, Josh From SeeBelow at SeeBelow.Nut Tue May 25 20:43:49 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 26 May 2004 00:43:49 GMT Subject: Why a class when there will only be one instance? Message-ID: <40B3E861.29B033D5@shaw.ca> I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a disadvantage of a whole lot of "self." being required everywhere, making the code less readable. Also, since a strength of Python is rapid application development, it slows one down to have to put in all those self.'s. The code seems much cleaner to me without classes that have only one instance. Oh, also, all the methods of this class will have to have the instance name prepended to them. I would appreciate it if someone could explain the advantages of doing this, or at least the sociological reasons why it occurs. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From timothy.williams at nvl.army.mil Wed May 19 08:20:11 2004 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 19 May 2004 05:20:11 -0700 Subject: alternatives to making blocks like { } or other ?? References: Message-ID: "Paul McGuire" wrote in message news:... > "Grant Edwards" wrote in message > news:slrncalqqf.8f2.grante at grante.rivatek.com... > > On 2004-05-18, CYBER wrote: > > >> Of course there is another way! > > >> > > >> Just use # in front of your favourite block separator. > > >> > > >> I'm too lazy now to search the archives on who first suggested this, > > >> but it works: > > >> > > >> def something(x): > > >> #{ > > >> return x > > >> #} > > > > > > Thank you. > > > > You realize that was a joke, right? > > > > > Actually, it was worse than a joke, in that it looks like it works, but > really doesn't. > > If you thought this was somehow magically doing grouping by reading the > commented-out braces, you could end up doing things like: > > if condition: #{ > do_something if condition is true > #} else: #{ > do_something if condition is false > #} > > which would have some surprising results (both true and false "paths" are > executed, because they are really the same path, the condition-is-true > path). > > So, no, CYBER, this doesn't really work, although most cases will not > complain, and *usually* do what you want. But in general, don't even start > this habit, just use the language features as-designed. > > -- Paul I have to put my 2 cents in here. I love Python, but the one thing I miss is using {} or something to enclose blocks. I edit in emacs python-mode, and believe in indentation, but sometimes I'll inadvertently change a line of code's indentation and it throws the logic off. I found a bug in one of my programs recently where a line of code should have been outside of an 'if', but wasn't because I hit TAB one too many times. A {} block would've caught that. I know that's just being careless, but I need all the help I can get! One thing I have done is to put a '#' at the end of the block so I know not to indent the next line when adding code. From SeeBelow at SeeBelow.Nut Fri May 21 20:09:42 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sat, 22 May 2004 00:09:42 GMT Subject: Pyrex - The speed of Python with the clarity of C? References: <40AE2C4E.CE1CE6C0@shaw.ca> Message-ID: <40AE9A5E.8F514E3B@shaw.ca> Terry Reedy wrote: > > "Peter Hansen" wrote in message > news:juidnTjQubr1szPd4p2dnA at powergate.ca... > > SeeBelow at SeeBelow.Nut wrote: > > > Am I wrong about this? Perhaps I don't understand how Pyrex works. > > > > Look at the primes.pyx example. There's a link just below it > > (above the Language Details section) showing the C code it is > > compiled to (and which is in turn compiled to machine code). True, > > there are many calls to the Python/C interface APIs, but there is > > also "pure" C code in there. > > In particular, lines 5-15 of the Python code, the 'guts' of the algorithm, > are compiled to pure C with no interface calls. But does this C code get compiled into machine code? If so, What compiler does that, and when? Thanks, m -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From fgeiger at datec.at Mon May 17 04:28:46 2004 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 17 May 2004 10:28:46 +0200 Subject: OPC Server in Python Message-ID: Hi all, I consider writing a control application in Python (realtime stuff would run on hw, i.e. a PCI card). If I decide to do so, I'd like to provide access to the control app's data for OPC clients. This means writing an OPC Server (OPC DA). Could I do this in Python too? At the core an OPC Server is a COM server, isn't it? Did anyone in this group do anything like that already? And if so, are you willing to share your experience? Right now I'm trying to get more info about OPC, i.e. there are some additional issues like OPC Groups and OPC Items and Browsing etc. Any books you would recommend? Other stuff to get me started quickly? Any hint welcome! Kind regards Franz GEIGER From h.b.furuseth at usit.uio.no Mon May 24 01:29:25 2004 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: 24 May 2004 07:29:25 +0200 Subject: Named integers and enums References: Message-ID: Thanks for the answers! Shalabh Chaturvedi wrote: >Hallvard B Furuseth wrote: >> Is this possible without too much code? >> >> class Named_int(object, int): > > (...) Why do you want to subclass object here anyway? int is already a > subclass of object, so just Named_int(int) should be enough. I didn't know that. Can't find it in the python doc either. But now I wonder: isinstance() says that even classic class instances are 'object' instances, even though they do not seem to be (since __slots__ does not work): >>> class o: __slots__ = () ... >>> isinstance(o(), object) 1 >>> o().foo = True >>> It works as expected with subclasses of 'int': >>> class n(int): __slots__ = () ... >>> isinstance(n(3), object) 1 >>> n(3).foo = True Traceback (most recent call last): File "", line 1, in ? AttributeError: 'n' object has no attribute 'foo' -- Hallvard From deetsNOSPAM at web.de Tue May 4 16:24:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 04 May 2004 22:24:21 +0200 Subject: Zero-fill shift References: Message-ID: Daniel Orner wrote: > I'm trying to port a (relatively) simple encryption algorithm from Java > code (mainly because the algorithm will be used identically in both > contexts). However, the code makes extensive use of Java's >>> operator, > which shifts right and fills in the leftmost bits with zeroes. I've been > unable to duplicate that effect in Python. > Apparently, a >>> b is equal to the following: > > if a >= 0: return a >> b > else: return (a>>b)+(2<<~b) > > However, Python complains when I try to do the left-shift, because ~b > is often a negative number. Does anyone have a better idea about how I > should go about doing this? from what I can see from the java and python docs, all you should need is a mask for the upper bits. masks = [0xffffffff] + [0x7fffffff >> i for i in xrange(31)] then your op is: (a >> b) & masks[b] -- Regards, Diez B. Roggisch From Chris.Barker at noaa.gov Thu May 13 13:22:02 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Thu, 13 May 2004 10:22:02 -0700 Subject: PEP: import version In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Somehow that version has to map to a different file being loaded, so it > seems to me the proper place to record this information is in sys.path (or > before the program runs, PYTHONPATH). Voila! No syntax changes required. This really needs to be done at runtime, not ahead of time with PYTHONPATH. We have been discussing this over at wxPython-users, and a number f workable solutions have been proposed. However, it would be great if there was an "official" Pythonic way to do it, rather than each package author coming up with their own system. So, I'm all for a PEP, even if it is just for a standard approach, and no change to python whatsoever. If someone is working on a proposal, you might want to consider these (from the wxPython Wiki): Basic Goals: * Multiple versions of wxPython being installed at the same time * Two or more programs, each using a different version could run at once. * Easy for developers - for testing with multiple versions etc * Easy for users - their apps detect the right version to run with * Cross-Platform solution More detail: * The ability for the programmer to specify the version used in the code, ideally only on (or before) the first import of wxPython * A default version that gets imported with "import wx", just like it's always been * The ability to specify the version wanted with an environment variable, so that multiple versions could be easily tested * The ability to specify multiple versions that all work, in a ordered list of some sort. * The ability to specify a "minimal" version, and higher versions could be used. * The ability for "from wx.lib import Something" to work as well, respecting the version -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From http Sat May 8 20:08:59 2004 From: http (Paul Rubin) Date: 08 May 2004 17:08:59 -0700 Subject: What I don't like about wxPython References: Message-ID: <7xr7tu5un8.fsf@ruckus.brouhaha.com> Peter Hansen writes: > > Just thought I'd play devil's advocate... > > I tried wxPython briefly, and it had some nice features. > > It has a huge list of dependencies. > > 1. Python. > 2. Windows. > > Unless I misunderstand, and I'm sure I do, I wouldn't call that > a huge list... If wxPython really depends on Windows, that's a huge obstacle for those wanting a portable system. If it doesn't literally depend on Windows, but uses Windows-centric interfaces and approaches, that's still pretty annoying for non-Windows developers. From lbates at swamisoft.com Mon May 24 11:37:51 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 24 May 2004 10:37:51 -0500 Subject: py2exe setup script problem References: <2hchapFbelulU1@uni-berlin.de> Message-ID: What do you expect to happen? If program creates output, you need a console window to display it (unless you use GUI interface). Without console output has no where to go. I actually use this to my advantage on some lights-out applications that write all their output to log files. Larry Bates Syscon, Inc. "Philipp Kruse" wrote in message news:2hchapFbelulU1 at uni-berlin.de... > I am trying to create an executable version of a python script using > py2exe 0.5 (Python 2.3.4c1). The basic script looks something like this: > > setup( > [...] > windows = [ 'src/__main__.py', > { 'script': 'src/__main__.py', > 'icon_resources': [(1, "data/small.ico")]} > ], > ) > > > After running py2exe I try to execute the created .exe file and - > nothing happens. > > > However, I tried changing the script to this: > > setup( > [...] > console = ['src/__main__.py'], > ) > > > Suddenly everything works fine. Even so, I simply need to get rid of > that console window. > > I tried reading through the wiki and searched this group but found > nothing that could solve the problem. > > Does anyone have an idea? > > > Philipp From peter at engcorp.com Fri May 21 13:21:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 13:21:31 -0400 Subject: Passing options between modules In-Reply-To: <939f49f8.0405210907.4f12a613@posting.google.com> References: <939f49f8.0405210907.4f12a613@posting.google.com> Message-ID: <1KqdncbpSO8GpzPd4p2dnA@powergate.ca> Chris wrote: > I'm trying to come up with a not-so-ugly manner of passing many > command-line options between modules. In a pinch (i.e. if the rest of your application is such that you don't have a cleaner alternative), create an empty module called something like Globals.py and set values in its namespace to reflect the command line options. Then any module that needs it can just "import Globals" to get access to the data. All the usual "don't do that" cautions about globals apply, including how they can make a mess of your code, make it very hard to tell how data gets passed around, reduce maintainability, etc. Without knowing more about the structure and purpose of the code, it's hard to suggest something that is clearer more suitable and would definitely work. -Peter From cookedm+news at physics.mcmaster.ca Mon May 10 15:15:55 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 10 May 2004 15:15:55 -0400 Subject: Iterating Dictionaries in a Function References: Message-ID: At some point, "Delaney, Timothy C (Timothy)" wrote: > Also, since you're using a non-changing dictionary, it's best to only > create it once. > > OPTIONS = {'a': 1, 'rty': 4, 'er': 2} > > def findx (st): > try: > item = OPTIONS[st.lower()] > except KeyError: > print 'Item not found: %s' % (st,) > return None > else: > print 'Item found: %s %s' % (st, item,) > return item > > or even better, don't bother catching the exception (I presume you're > only doing it for debugging, as with the printing): > > def findx (st): > return OPTIONS[st.lower()] > > which of course becomes > > OPTIONS[st.lower()] Or, without exceptions, and returning None like before, def findx(st): return OPTIONS.get(st.lower(), None) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From aahz at pythoncraft.com Sun May 9 21:01:24 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 May 2004 21:01:24 -0400 Subject: list comprehension References: Message-ID: In article , Guy Robinson wrote: > >Trying to change a string(x,y values) such as : > >s = "114320,69808 114272,69920 113568,71600 113328,72272" > >into (x,-y): > >out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" > >I tried this: > >print [(a[0],-a[1] for a in x.split(',')) for x in e] > >But it doesn't work. Can anyone suggest why or suggest an alternative >way? The text strings are significantly bigger than this so performance >is important. When in doubt, break a problem into smaller steps. Let me play Socrates for a minute: what's the first step in working with your dataset? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From harry.g.george at boeing.com Wed May 19 11:21:20 2004 From: harry.g.george at boeing.com (Harry George) Date: Wed, 19 May 2004 15:21:20 GMT Subject: unique number generator References: <5da2b26991d290ff30a502d392812f4b@news.teranews.com> Message-ID: Daniel 'Dang' Griffith writes: > On Wed, 19 May 2004 18:36:40 +0800, "Joe Wong" > wrote: > > > I need to implement a unique number generator that 1 or more processes on same or different machines will make use of it. Is there any library / project available already for this? > > Yes. Google for GUID (globally unique identifier) algorithm or UUID > (universally unique algorithm): > "http://www.google.com/search?q=GUID+algorithm", > "http://www.google.com/search?q=UUID+algorithm". > > If you need to use one, instead of implement one, and > you're running on Windows machines with Mark Hammond's > win32 extensions, you can do it easily: > > import pywintypes > guid = pywintypes.CreateGuid() > have_a_nice_day(guid) > > --dang Pyro.util.getGUID() is a cross-platform solution. Or, you can write a wrapper which uses MS's guid on Win** platforms, and Pyro's on *NIX platforms. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 342-0007 From sh at defuze.org Tue May 11 08:26:45 2004 From: sh at defuze.org (sh at defuze.org) Date: Tue, 11 May 2004 08:26:45 -0400 Subject: Performance of cPickle module Message-ID: <1084278405.40a0c685111a0@webby.idconseil.net> Hi guys, Well, I have a (maybe dumb) question. I want to write my own little blog using Python (as a fairly small but doable project for myself to learn more deaply Python in a web context). I don't want so far to use a database as a backend, I'd prefer use XML which is enough for a small amount of data the blog would have to deal with. My problem is that, as HTTP is stateless, I can't keep some objects alive across multiple requests like for instance an instance of a Users class which is an interface to manage my users. Let's say for example, that an user wants to access a resource (a simple web page), my code would call that Users class though an instance of it and would call something like getUser(self,login) returning an instance of an UserData class which would provide me with all the details of that user (name, email, etc.) I want to save my users not in a database like I said but in an XML file on the server. As HTTP is stateless, I believe that I will have to create again and again the Users object for every requests. I don't want to parse the xml file each time, instead I want to save the Users object (that keeps a map to all my UserData objects) into a file using the cPickle module. My question therefore is, is my architecture efficient enough ? If I had to use a database, the database would keep track of my users and I would only need to do a SQL statement. Would the cPickle more efficient in my case than a database ? To give a bit of code let's say that I have something like : import cPickle class UserData: def __init__(self,name,email): self.name = name self.email = email class Users: def __init__(self): self.users = {} self.hasChanged = false def _deserialize(self): if self.hasChanged == false: self.users = cPickle.load('users.dat') else: #parse the xml file... Is it an efficient method ? Thanks - Sylvain From travis at enthought.com Thu May 6 08:27:08 2004 From: travis at enthought.com (Travis N. Vaught) Date: Thu, 06 May 2004 07:27:08 -0500 Subject: ANN: SciPy 2004 Conference - Python for Scientific Computing Message-ID: <409A2F1C.7050801@enthought.com> Greetings, The 1st annual *SciPy Conference* will be held this year at Caltech, September 2-3, 2004. As some of you may know, we've experienced great participation in two SciPy "Workshops" (with ~70 attendees in both 2002 and 2003) and this year we're graduating to a "conference." With the prestige of a conference comes the responsibility of a keynote address. This year, Jim Hugunin has answered the call and will be speaking to kickoff the meeting on Thursday September 2nd. Jim is the creator of Numeric Python, Jython, and co-designer of AspectJ. Jim is currently working on IronPython--a fast implementation of Python for .NET and Mono. Registration is now open. More information can be found here: http://www.scipy.org/wikis/scipy04 You may register early online for $100.00. Registration includes breakfast and lunch Thursday & Friday and a very nice dinner Thursday night. After July 16, registration will cost $150.00. Call for Presenters: If you are interested in presenting at the conference, you may submit an abstract in Plain Text, PDF or MS Word formats to abstracts at scipy.org -- the deadline for abstract submission is July 1, 2004. Papers and/or presentation slides are acceptable and are due by August 20, 2004. We're also planning three days of informal "Coding Sprints" prior to the conference -- August 30 to September 1, 2004. Conference registration is not required to participate in the sprints. Please email the list, however, if you plan to attend. Topics for these sprints will be determined via the mailing lists as well, so please submit any suggestions for topics to the scipy-user list: list signup: http://www.scipy.org/mailinglists/ list address: scipy-user at scipy.org Please forward this announcement to anyone/list that might be interested. I look forward to seeing you at the conference. Best Regards, Travis N. Vaught From nid_oizo at yahoo.com_remove_the_ Fri May 14 18:39:29 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 14 May 2004 18:39:29 -0400 Subject: perl to python In-Reply-To: <85sme8ug0l.fsf@stowers-institute.org> References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <85sme8ug0l.fsf@stowers-institute.org> Message-ID: Michael Coleman wrote: > Olivier Scalbert writes: > >>Jarek Zgoda wrote: >> >>>Olivier Scalbert pisze: >>>Use sed. >> >>yes, but in python ? > > Jarek's answer is the correct one, for almost any real situation. I disagree, I think actually Perl is a better answer. Using grep, sed, tr, etc. on Windows is error-prone anyway, because of the shell difference. Perl is very complete as a parsing solution, personnally that's what I would prefer, and it's more scalable, since when you want to do more, you can copy your solution in a script and expand it. Using a python script makes a lot of sense also, as people have pointed two-lines solutions. Regards, Nicolas From pugnatio2 at yahoo.com Thu May 6 15:28:53 2004 From: pugnatio2 at yahoo.com (pugnatio2 at yahoo.com) Date: 6 May 2004 12:28:53 -0700 Subject: polymorphism w/out signatures? Message-ID: <997a06e0.0405061128.6768676d@posting.google.com> What's the standard way to implement polymorphic behavior in a python method, given that method arguments can't declare their types as they're being passed in, and method definitions don't have signatures? For instance, if I wanted to write a method that auto-detected whether it was being passed a string or a tuple/list, how would I do so without using type() to identify the parameter's type? Using type() is deprecated in the documentation I've read. Thanks in advance. From vonehr at ipm.fhg.de Tue May 18 09:12:01 2004 From: vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 18 May 2004 15:12:01 +0200 Subject: SWIG callback problem on win32 In-Reply-To: References: Message-ID: Markus von Ehr schrieb: > Hi, > > I tried to build the swig: callback example, > but when I run the runme.py file I get a message box: > abnormal program termination > > The error appears in already in the first line of the python > callback generation: > > # Add a Python callback (caller owns the callback, so we > # disown it first by calling __disown__). > > caller.setCallback(PyCallback().__disown__()) > caller.call() > caller.delCallback() > > When I call only PyCallback().__disown__() > alone, the error appears, too. > > Anybody knows a solution? > > Thanks a lot, > > Markus I made a new trial: The error appears in the following line of the Callback class: _camera_callback.disown_Callback(self) I guess the problem is in the static PyObject *_wrap_disown_Callback function? How could I get rid of it? Thanks for any hints to get rid of this error. Markus PS The application is a C++ Thread providing a callback function, when a new camera image on the firewire bus is available. Then I want to inform a python object that it can fetch the new image data. From indigo at bitglue.com Wed May 26 14:13:07 2004 From: indigo at bitglue.com (Phil Frost) Date: Wed, 26 May 2004 14:13:07 -0400 Subject: Embedding Python at the OS level - build problems [success] In-Reply-To: <20040526003414.GA2712@unununium.org> References: <20040526003414.GA2712@unununium.org> Message-ID: <20040526181307.GA28031@unununium.org> Success! They said it can't be done. "Python is too big", they said. "Too high level for an OS". And yet, it's done :) Here's a list of what I remember hacking: - manually set cross_compile=yes in the configure script, otherwise it expects that a program compiled with $CC will run, which it won't, for I'm cross compiling. - remove posixmodule from MODOBJS in Makefile. It wouldn't build, but probably would have with just a little tweaking. As of now the OS hasn't any filesystem (that's to be implemented in Python), so building modules doesn't make much sense anyway. - Build Parser/pgen using the host toolchain and copy it to the target build directory when the build system complains that it can't link it. That's it, I reckon. I now have a minimal OS that runs Python. If I add a filesystem, it will be something like preemptive, 32-bit PythonDOS. w00t. I'd like to thank those who have helped me, and those who have contributed to Python. This is some way cool stuff :) -- Phil Frost On Tue, May 25, 2004 at 08:34:14PM -0400, Phil Frost wrote: > Greetings all. I'm attempting to embed a python interpreter at a very > low level in an OS I am writing. Currently I'm stuck with build issues. > > [big chop] From http Tue May 11 04:03:34 2004 From: http (Paul Rubin) Date: 11 May 2004 01:03:34 -0700 Subject: efficient list reduction References: Message-ID: <7xd65bgzl5.fsf@ruckus.brouhaha.com> gnosticray at aol.com (A B Carter) writes: > [oldlist[key] for key in keys] > > Have I missed something? If the keys and values are all characters or small positive ints, maybe you can contort your program to let you use the very fast string.translate operation. Otherwise, use psyco, and if your listcomp is still not fast enough, write a C extension. From lbates at swamisoft.com Tue May 18 16:03:38 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 18 May 2004 15:03:38 -0500 Subject: alternatives to making blocks like { } or other ?? References: Message-ID: Blocks in Python are defined not with {} but rather with indention. You indent to start a block and stop indenting when you wish to end it. Seems odd at first, but turns out to be excellent way to handle blocks (and to properly format you code). HTH, Larry Bates "CYBER" wrote in message news:c8do0u$9fb$1 at news.atman.pl... > Hello > > Is there any other way under python to create blocks ?? > > instead of > > def sth(x): > return x > > > > could i use something else like > > def sth(x): > { > return x > } > > > ??? From amireallyfat at yahoo.com.au Mon May 24 17:51:37 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Tue, 25 May 2004 07:51:37 +1000 Subject: lists or tuples Message-ID: <40b2e203$1_1@news.iprimus.com.au> hey what is the many dif with them why bothere using tuples and how do you edit a list??? thanks From dmq at gain.com Tue May 25 20:55:33 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 17:55:33 -0700 Subject: Unification of Methods and Functions References: <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: <03q7b0dp0efitbjgkpkak9n0i8gup3j1p9@4ax.com> On Tue, 25 May 2004 07:17:35 -0600, "Dave Brueck" wrote: >David MacQuigg wrote: >> >another thread I suggested you take the time to learn what the 2 or 3 most >> >common uses are for each of the features that will be affected, and show both >> >the implementation and use in current Python and after your proposed changes. >> >Not only will doing this give a clear example to everyone, it'll also show that >> >you are at least aware of how the different function/method forms are used >> >today in _real programs_ and not contrived examples - after re-reading some of >> >your comments I have my doubts. >> >> I have shown the 4 function/method forms I'm aware of, and how to >> translate them to a simpler syntax, in Appendix 1 of Prototypes.doc at >> http://ece.arizona.edu/~edatools/Python Have you read that? > >Yes, but as I pointed out elsewhere, it may help to write about this in some >other context than your other proposals (the fact that this is buried in >Appendix 1 under a title of "Translating Python Classes to Prototypes" doesn't >lend itself to much reader traffic). I've put some simple examples comparing Python 2 to the proposed Unified Function Syntax at http://ece.arizona.edu/~edatools/Python These are all pretty simple, and show just the changes necessary to unify functions and methods. More examples are welcome. Send me anything you think will be difficult to translate to the new syntax. I've also moved the Appendix 1: Translating Python Classes from Prototypes.doc to PrototypeSyntax.doc. These are "edge cases". Unlike the simple examples above, the purpose is to show that all the existing classes in Python can be migrated to the proposed syntax. -- Dave From cookedm+news at physics.mcmaster.ca Tue May 4 13:34:31 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 04 May 2004 13:34:31 -0400 Subject: Question about glob.glob <--newbie References: Message-ID: At some point, Heather Coppersmith wrote: > On Mon, 03 May 2004 23:09:27 -0400, > cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: > >> At some point, "Sean Berry" wrote: >>>>>> r = glob.glob('/*') >>>>>> r >>> ['/dev', '/usr', '/stand', '/etc', '/cdrom', '/proc', '/bin', '/boot', >>> '/mnt', '/modules', '/root', '/sbin', '/tmp', '/var', '/sys', '/COPYRIGHT', >>> '/kernel.GENERIC', '/kernel', '/compat', '/home', '/kernel.old', >>> '/modules.old'] >>>>>> >>>>>> r = glob.glob('/usr/websites/*') >>>>>> r >>> [] >>> >>> I can do a >>>>>> import os >>>>>> dirs = os.system('ls /usr/websites') >>> >>> and that works. Why doesn't glob.glob work on /usr/websites? > >> Somehow, I doubt that actually works. I'll bet that dirs == 0 -- os.system >> returns the status code of the command, not the output. You'll want >> commands.getoutput. > >> What are the permissions on /usr/websites? What does 'ls -l >> /usr/websites' and 'ls -ld /usr/websites' give? > > Possibly picking a nit, but is there a difference between 'ls > /usr/websites' (without the trailing slash) and 'ls /usr/websites/' > (with the trailing slash)? Some OS's do strange things with some > symbolic links and/or mount points based on the presence/absence of that > slash. True (linux being no exception). But then glob.glob('/usr/websites/*') should still give the contents of whatever /usr/websites points to. For the OP: does os.listdir('/usr/websites') work? glob.glob uses it internally, but catches any errors it raises. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mwh at python.net Wed May 26 15:07:56 2004 From: mwh at python.net (Michael Hudson) Date: Wed, 26 May 2004 19:07:56 GMT Subject: sys.stdout linebuffered References: Message-ID: "Thomas Guettler" writes: > Hi, > > I start a long running script like this (unix): > > nohup foo.py > foo.log & > > Now Python thinks sys.stdout should not be > line buffered. How can I force linebuffering? > > I want to see the log file while the script is > still running. > > I don't like this solution (Wrapping sys.stdout > with an own class) > > http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&selm=u4rz0icqq.fsf%40ctwd0143.fitlinxx.com Why? It appears to solve your problem! Cheers, mwh -- I think if we have the choice, I'd rather we didn't explicitly put flaws in the reST syntax for the sole purpose of not insulting the almighty. -- /will on the doc-sig From cm at leetspeak.org Mon May 24 20:46:35 2004 From: cm at leetspeak.org (Michael Walter) Date: Tue, 25 May 2004 02:46:35 +0200 Subject: Method binding confusion In-Reply-To: References: <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> Message-ID: <2hfjb8FcmcvuU1@uni-berlin.de> Josiah Carlson wrote: > [fix] In my eyes the inconsistency is the other way around... the built-in function acts unexpected. Cheers, Michael From rtrocca_NO_SPAM_ at divitech.it Wed May 19 04:19:45 2004 From: rtrocca_NO_SPAM_ at divitech.it (Riccardo) Date: Wed, 19 May 2004 10:19:45 +0200 Subject: pyVideoIO source release In-Reply-To: References: <2gugfoF6p9rhU1@uni-berlin.de> Message-ID: <2h0jkcF7rbfvU1@uni-berlin.de> Peter Hansen wrote: > Riccardo wrote: > >> Hello, after a long time I'm releasing my extension to read AVI files, >> QuickTime and connect to WebCameras under win32. >> I do not have much time to create a decent website by now, therefore I >> released the sources and a binary for python 2.3 just to be prompted >> to do more. >> If somebody will find this useful I'll add any contribution I receive. >> >> the URL is: >> >> www.geocities.com/rtrocca/python >> >> Well, sorry for the lack of more information, >> I'll add docs and other stuff in the future. > > > You should probably add a copy of the LGPL to the source package... > the source files say they are LGPL'ed, and suggest that one should > contact the "Free Foundation, Inc." (sic) if a copy of the license > is not included... > > -Peter Hello, I checked my source package and I've seen that a copy of the LGPL tex is included in the VideoIO/src directory. Is it ok to do so or something is missing? Riccardo From andrew-pythonlist at puzzling.org Tue May 11 19:07:28 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 12 May 2004 09:07:28 +1000 Subject: Are assert checks unpythonic? (was: Passing objects to a function) In-Reply-To: References: Message-ID: <20040511230728.GB29720@frobozz> On Tue, May 11, 2004 at 03:03:35PM +0200, Holger T?rk wrote: [...] > That's my problem with foo-like objects implementing varying > interfaces that aren't checked. Why isn't there a superclass "FileLike" > with the standard methods that all raise NotImplementedError, "method > bar"? So when NotImplementedError is raised, it's absolutely clear Because inheritance isn't the only way to do polymorphism. If I have an object with 'write' and 'close' methods, then I expect there are plenty of functions that that will just fine with. Having to declare that it inherits from "FileLike" isn't right -- it doesn't implement even half of FileLike's methods. Raising NotImplementedError isn't significantly better than AttributeError here. If you need to check that the object has 'write' and 'close' attributes before you get half-way through the function, then first do: write = obj.write close = obj.close This will raise an AttributeError immediately, or else give you variables you can use later in the function. There are more formal approaches, such as Zope 3's interfaces (although Zope 3 then uses them to support stuff like object adaption, rather than just as a tool to verify that your arguments have the behaviour you expect). -Andrew. From peter at engcorp.com Fri May 7 07:36:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 07 May 2004 07:36:28 -0400 Subject: call scp from python In-Reply-To: <409b425a$1@pfaff2.ethz.ch> References: <409b425a$1@pfaff2.ethz.ch> Message-ID: Josef Meile wrote: > Coder Coder wrote: > > How can scp a file from one computer to another using python? > You can either use os.system or some of the popen functions of the os > module. But only if you can set it up to run in batch mode, without asking for passwords *or* a passphrase. Otherwise you need a pty to get it to work. Past threads in the newsgroup have covered this topic as well. Search Google Groups for "group:comp.lang.python scp popen" for more. -Peter From bhoel at web.de Sat May 15 15:08:09 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sat, 15 May 2004 21:08:09 +0200 Subject: Test error with Python 2.3.4c1 References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article , Berthold H?llmann wrote: >> >>The error desribed in SF error report No. 870120 (segmentation fault >>in test_re) still persists for me in 2.3.4c1. > > Is there a patch for it? Bugfix releases are mostly low-effort > collections of patches that already exist -- there's not much attempt > made to call for new patches before the release goes out. All that > bugfix release candidates are intended to do is make sure that no new > bugs have been created. The patch working for me is to reduce the default USE_RECURSION_LIMIT diff Modules/_sre.c~ Modules/_sre.c 98c98 < #define USE_RECURSION_LIMIT 10000 --- > #define USE_RECURSION_LIMIT 6835 Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From jacek.generowicz at cern.ch Mon May 24 08:19:58 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 May 2004 14:19:58 +0200 Subject: Python compilers? References: Message-ID: Heiko Wundram writes: > Am Dienstag, 18. Mai 2004 13:41 schrieb Jacek Generowicz: > > Native compilers for other languages just as dynamic as Python > > exist. These compilers manage to achieve very significant speed > > increases[*]. > > In Python this isn't true. Python, instead of LISP, is "completely" dynamic, In what way is Lisp less dynamic then Python? If what follows is the basis of your argument, then think again? > meaning that it's pretty impossible to do type-inference for each function > that is called (even checking types isn't possible). E.g. how do you expect > type-inference to work with the pickle module? string -> something/Error > would be the best description what pickle does. For the function which calls > pickle, do you want to create versions for each possible output of Pickle? > Which outputs of Pickle are possible? Which outputs of the standard Common Lisp function 'read'[*] are possible? [*] http://www.lisp.org/HyperSpec/Body/chap-23.html From rogerb at rogerbinns.com Sun May 16 22:33:37 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 16 May 2004 19:33:37 -0700 Subject: book on wxPython? References: <40a5a851$0$8512$a18e6209@newsreader.visi.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> <40a7a324$0$8513$a18e6209@newsreader.visi.com> Message-ID: Grant Edwards wrote: > Not realizing that the containment and layout trees are > _separate_ is half of what made wxPython apps appear to be a > mess. Many programmers aren't even used to the idea of layout hierarchies. It is very ingrained of you have ever done Tk or Motif, but not something you will know about as a Windows programmer. > Perhaps that fact was obvious to everybody else, but I missed it > completely. I don't think it is obvious at all. There is an overview about them in the doc, as well as some pages in the wiki. > [I still think the whole integer ID thing should be hidden from > the programmer, but perhaps a light will come on one of these > days and that will then make sense to me as well.] I use them because I have menu items, toolbar buttons and buttons in HTML that all need to reference the same thing. An integer ID does the trick nicely. > [I'm still a bit > foggy on the function of the parent-child relationship in > wxWidgets.] A child widget is within its parent - it will be clipped to its parent, and is drawn on top of its parent. Some events (eg command events) are delivered to a widget and if it doesn't handle them then sent up the containment hierarchy. > I've heard all sorts of nasty things > about Motif, so I never tried it. I worked for the company that at one point had 70% of the worldwide Motif market. At that time it had i18n features, a resource system noone used (not the same as Xt resources, but more like XRC in wxWidgets), and portability to the many flavours of UNIX. (I once used Sony UNIX - yes it really existed). Then CDE came along and the rest is history. > I'm definitely going to stick with it. I blundered my way > though writing and shipping one small wxWindows app a while > back. Now that I've figured out the two-tree thing, it should > be easier. The best advice I can give you is to seriously examine the XRC stuff. The XRC editor even comes with wxPython. That will let you abstract out your user interface code (especially the issues to do with layouts and parent relationships). I just wish I had done it. Roger From dmq at gain.com Wed May 12 19:31:44 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 12 May 2004 16:31:44 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> Message-ID: <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> On 11 May 2004 18:54:56 -0700, moughanj at tcd.ie (James Moughan) wrote: >Sure; you have to have some understood conventions. In effect that's >all any higher-level programming language than assembler is. IMO, in >the case in point, the explicit self makes OO easier to undersstand; >YMMV, of course, as it does with Dave. :) I really hate to get involved in this "explicit self" debate, as I know it has been debated ad-nauseum for many years, but I wish people would not attribute to me a point-of-view that I do not have. For me the "explicit self" is *not* the issue. I have a slight preference for .var over self.var or $var, but this is a matter of personal preference, not an implicit vs explicit question. My definition of explicit is that you can tell the meaning of a statement without reference to the surrounding code. By that definition all of the above forms are explicit. They are all instance variables, and there is no other interpretation. The choice between them is a *minor issue*, and I trust GvR to make these choices. The real issue is whether we can unify all forms of functions and methods. This requires we do something different with 'self'. From a unification standpoint, an equally acceptable solution is that we add 'self' to *all* functions and methods, whether they need it or not. The problem with rules like "explicit is better than implicit" is that some people take them too literally. Sometimes it seems like quoting a rule is a substitute for thinking. We need to balance all these rules, and add a good measure of common sense to reach the true goal. My goal is overall simplicity for the syntax needed to solve the kind of problems that a non-CIS technical professional might encounter. That includes static methods, but not metaclasses. That could change if someone convinced me that static methods are unnecessary or that metaclasses are essential to solve a real-world problem. Meanwhile I'm happy to just watch the wizards play with metaclasses, and I don't care if their brains explode. :>) I'm also happy to use what they develop with metaclasses. Case in point - Michele Simionato's prototype module. This is easy to use, even if I don't understand how it works. To me, its like a C module. I don't feel I need to understand the internals. I feel entirely differently about excess complexity in syntax my students and clients are likely to write or need to understand. -- Dave From forget-it at no-spam.com Wed May 19 15:12:17 2004 From: forget-it at no-spam.com (Phillip) Date: Wed, 19 May 2004 21:12:17 +0200 Subject: Serious trouble with https (Python 2.2.3 & 2.3.3), How to check for working ssl? Message-ID: Some people tipped me off on some possibilities to tackle my https problem. Those have definitely gotten me further in cornering the problem. Thank you. But: No matter what I do to open a webconnection with httpS I always get something in this Area: urllib2.URLError: With both versions of Python mentioned above. My strong suspicion is that the socket stuff (dunno exact libname right now...) is compiled without ssl support. What I would like to know now is following: 1) What is the default setting for the compilation of the original Python source? _With_or _without_ ssl support? I just downloaded the sources onto Debian Linux and did the configure, make, make install dance. No fumbling on my side done here. Is there anybody I could ask who could know? Appart from bugging Guido van Rossum over this that is. :-) 2) If this can't be said for shure _how_ can I find out if my version of Python was compiled with ssl support? Apart from trying to connect via https that is. Like I said: I've got a seriously growing suspicion that it _is_ unsupported ssl due to compilation. 3) Where do I change the compile options (???), switches (???) - I don't know how excactly this stuff is called - to set such stuff as what things are compiled into the installation and which aren't. This is a more general Linux/make/configure/gcc/whatnot sort of question, I know, but I would be gratefull for any help. Thank you. Phillip From bignose-hates-spam at and-benfinney-does-too.id.au Mon May 10 01:48:51 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 10 May 2004 15:38:51 +0950 Subject: How do you register cleanup code to be run after script execution? References: <20040508090936.21319.00000994@mb-m04.aol.com> Message-ID: On 08 May 2004 13:09:36 GMT, use dmgass at hotmail dot com wrote: > I'm writing a module and when it is imported by a script I want some > code automatically executed when the importing script is finished > executing. I'm not aware of any way to do what you want at the module level. What are you trying to accomplish that isn't satisfied by having objects do their cleanup themselves, in __del__() functions? -- \ "We must become the change we want to see." -- Mahatma Gandhi | `\ | _o__) | Ben Finney From garry at sage.att.com Fri May 14 12:11:40 2004 From: garry at sage.att.com (Garry Hodgson) Date: Fri, 14 May 2004 16:11:40 GMT Subject: how to run an arbitrary function with timeout? Message-ID: <2004051412111084551099@k2.sage.att.com> i'm building a test suite on top of unittest, and some of the tests involve things that might hang, like trying to connect to a wedged server. so i'd like a simple function that i can call that will run a given (func,args) pair and return either the value or raise an exception if it times out. this seems like it should be straightforward, but i've not had much luck getting it to work. my latest attempt, below, raises the exception ok, but still doesn't return until snooze() completes: --> xx going to sleep Traceback (most recent call last): File "./xx", line 26, in ? print RunWithTimeout( snooze, (10,), 2 ) File "./xx", line 16, in RunWithTimeout raise TookTooLong, 'fsdfsdf' __main__.TookTooLong: fsdfsdf ...8 second delay here... waking up can someone tell me what i'm doing wrong? thanks ------------------------ #!/usr/bin/env python2.3 from threading import * from time import sleep class TookTooLong( Exception ): pass def RunWithTimeout( func, args, timeout ): t = Thread( target=func, args=args ) t.start() t.join( timeout ) if t.isAlive(): del t raise TookTooLong, 'fsdfsdf' return 'ok' def snooze( duration ): print 'going to sleep' sleep( duration ) print 'waking up' if __name__ == '__main__': print RunWithTimeout( snooze, (10,), 2 ) ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From eric_brunel at despammed.com Wed May 19 03:54:44 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 19 May 2004 09:54:44 +0200 Subject: Tree control with TKinter References: Message-ID: Marco Terzuoli wrote: > Hi, > I would like to implement a tree control inside a Python application. It > should be similar to GTK's TreeStore widget, but I need it for TKinter. > Any ideas? > thanks > Marco There is a tree widget in IDLE, which is part of all Python distribution. With Python 2.1, it's located under Tools/idle in the Python installation directory and is named TreeWidget.py. AFAIK, there's no documentation for it, but it is quite easy to use and also includes an example application. There are many others alternatives around; Google is your friend. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From swerdlow at maine.rr.com Wed May 26 11:53:03 2004 From: swerdlow at maine.rr.com (Bob Swerdlow) Date: Wed, 26 May 2004 15:53:03 GMT Subject: problem installing MySQLdb on Solaris 8 Message-ID: I'm trying to install MySQLdb 0.9.2 so I can access my MySQL database from python under Solaris 8. I found the notes on changing the include and lib paths and it seems to find them okay, but when I run 'python setup.py build', I get these errors: ... building '_mysql' extension creating build/temp.solaris-2.8-sun4u-2.3 gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/ usr/include/mysql -I/usr/local/include/mysql -I/usr/local/mysql/include/ -I/ usr/local/include/python2.3 -c _mysql.c -o build/temp.solaris-2.8-sun4u-2.3/_mysql.o -fPIC _mysql.c: In function `_mysql_ConnectionObject_info': _mysql.c:1150: warning: assignment discards qualifiers from pointer target type _mysql.c: In function `_mysql_ConnectionObject_stat': _mysql.c:1379: warning: assignment discards qualifiers from pointer target type _mysql.c: At top level: _mysql.c:2007: warning: initialization from incompatible pointer type _mysql.c:2096: warning: initialization from incompatible pointer type gcc -shared build/temp.solaris-2.8-sun4u-2.3/_mysql.o -L/usr/lib/mysql -L/usr/local/lib/ mysql -L/usr/local/mysql/lib/ -Wl,-R/usr/local/lib:/usr/openwin/lib:/usr/dt/ lib -lmysqlclient_r -lz -o build/lib.solaris-2.8-sun4u-2.3/_mysql.so ld: warning: file /usr/local/lib/mysql/libmysqlclient_r.a(libmysql.o): wrong ELF class: ELFCLASS64 My configuration is: bash-2.05$ python Python 2.3.3 (#1, Feb 11 2004, 14:47:54) [GCC 3.3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import zlib >>> zlib.__version__ '1.0' >>> ^D bash-2.05$ The server is a Sun Netra T1, which has a 64-bit SPARC in it. I tried adding '-m64' to the extra_link_args in setup.py, then I removed the 'build' directory and built again, but then I got: ... ld: fatal: file build/temp.solaris-2.8-sun4u-2.3/_mysql.o: wrong ELF class: ELFCLASS32 ld: fatal: File processing errors. No output written to build/lib.solaris-2.8-sun4u-2.3/_mysql.so What do I need to do to get MySQLdb installed on Solaris 8? Thanks, Bob From antoine at vanmaarle.nl Fri May 7 10:57:56 2004 From: antoine at vanmaarle.nl (AnToine van Maarle) Date: Fri, 7 May 2004 16:57:56 +0200 Subject: invalid page in PYTHON23.DLL Message-ID: After installing ARM and starting it up it comes with the following Windows ERROR message (in partly Dutch): ARM heeft een fout met betrekking tot een ongeldige pagina veroorzaakt in module PYTHON23.DLL at 018f:1e01561d. Registers: EAX=00000000 CS=018f EIP=1e01561d EFLGS=00010202 EBX=00776930 SS=0197 ESP=0064ead4 EBP=00000001 ECX=00000000 DS=0197 ESI=00776a80 FS=943f EDX=1e0bb488 ES=0197 EDI=00c08088 GS=0000 Bytes in CS:EIP: 8b 08 41 89 08 8b 0e 85 c9 89 06 74 11 8b 01 48 Stackdump: 00000000 0137eb04 01cea4b0 00000000 00000000 17edbb04 00000000 00776a84 00770870 1e040998 01b62860 00000002 00776930 0137eb04 00000002 00000000 Who has any experience with this problem? From roy at panix.com Thu May 13 17:44:25 2004 From: roy at panix.com (Roy Smith) Date: Thu, 13 May 2004 17:44:25 -0400 Subject: perl to python References: Message-ID: "Andy Baker" wrote: > Here is a small feline amongst the pigeons... > > Surely support for regular expressions is 'un-pythonic'? > > The Python way would be to code regex's explicitly, surely? In what way is Python's support for regex's un-pythonic or un-explicit? Regex support is similar to SQL support. Both are little languages (in the case of SQL, maybe not so little), with syntax and semantics finely tuned for a specific purpose, and defined/standardized by entities outside of the Python community. To a certain (lesser) extent, LDAP support falls into the same category. The common theme here is that the operation you want to perform is defined entirely by a text string. If I want to search for "((spam)|(eggs)|(bacon)){10,}", that is the exact string I want to use, regardless of the host language. This implies that you either need to build knowledge of regex syntax into the core language (like Perl, sed, and awk do), or you need to pass strings down into functional API (like Python, C, and Java do). I don't think anybody can deny that building regexes into the language makes it more convenient. The problem is, where do you stop? Do you also build SQL support right into the language? LDAP? For each individual extension, it sure would be convenient for performing certain specific tasks, but the overall result would be a mess. From olivier.scalbert at algosyn.com Sun May 9 15:44:03 2004 From: olivier.scalbert at algosyn.com (Olivier Scalbert) Date: Sun, 09 May 2004 21:44:03 +0200 Subject: perl to python In-Reply-To: References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Message-ID: <409e8a04$0$22988$a0ced6e1@news.skynet.be> Jarek Zgoda wrote: >Olivier Scalbert pisze: > > > >>What is the python way of doing this : >>perl -pi -e 's/string1/string2/' file >> >> > >Use sed. > > > yes, but in python ? From j_mckitrick at bigfoot.com Fri May 21 14:22:59 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 21 May 2004 11:22:59 -0700 Subject: Problem with PyGTK/Glade2 ComboBox vs ComboEntryBox Message-ID: Hi all. Here is a tiny container for one of each combo box, along with the glade file. Just 2 widgets, so hopefully not too large. How the heck do I get the selection from the ComboBox, as opposed to the ComboEntryBox? I'm pulling my hair out over this one! jonathon #!/usr/bin/env python import sys import pygtk; pygtk.require('2.0') import gtk import gtk.glade class tinytest: def __init__(self): gladefile = 'project4.glade' windowname = 'window1' self.wTree = gtk.glade.XML(gladefile, windowname) dic = { 'on_window1_destroy' : (gtk.mainquit), 'on_comboboxentry1_changed' : self.cbe, 'on_combobox1_changed' : self.cb } self.wTree.signal_autoconnect(dic) def cbe(self, widget): s = self.wTree.get_widget('comboboxentry1').get_children()[0].get_text() print 'cbe changed %s' % s def cb(self, widget): # s = self.wTree.get_widget('combobox1').entry.get_text() # print 'cb changed %s' % s s = self.wTree.get_widget('combobox1').get_children()[0].list s = self.wTree.get_widget('combobox1').list.get() print 'cb changed %s' % s s = self.wTree.get_widget('combobox1').active print 'cb changed %d' % s tinytest() gtk.main() True window1 GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False True False True False False GDK_WINDOW_TYPE_HINT_NORMAL GDK_GRAVITY_NORTH_WEST True False 0 True Entry 1 Entry 2 Entry 3 0 True True True Item 1 Item 2 Item 3 0 True True From timr at probo.com Mon May 24 01:57:44 2004 From: timr at probo.com (Tim Roberts) Date: Sun, 23 May 2004 22:57:44 -0700 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: moma wrote: > >What about unichr() ? > >#!/usr/bin/python2.3 -u >t="abc"+unichr(174)+"def" That's an easy trap to fall into, but it isn't right. unichr(174), which is U+00AE, is the ? (R) registered trademark symbol. We don't have any idea whether or not the \xae character in his original 8-bit string was actually the registered trademark symbol. The meaning of the original \xae, and therefore the Unicode equivalent of that character, depends COMPLETELY on the character set of that original string. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From newsgroups at jhrothjr.com Sun May 9 18:38:48 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 9 May 2004 18:38:48 -0400 Subject: Passing objects to a function References: Message-ID: <109tcor9ojjn01d@news.supernews.com> "Thomas Philips" wrote in message news:b4a8ffb6.0405091315.5ecadf92 at posting.google.com... > I'd like to write the parameter list of a method or function in a way > that makes the class of each parameter crystal clear, thus decreasing > the likelihood of a programming error. > > I am programming a blackjack game with Card and Hand objects, and > these in turn have methods that require Card objects, Hand objects or > both. For example, the class Hand has a method BlackJackValue that > computes the value of a hand using the rules of blackjack. I'd like to > write the method (approximately) in the form > > def BlackJackValue(hand=Hand): > adfsadf > adfasdf > . > . > . > > It takes only one look at this method's definition to realize that it > requires an object of type Hand. Unfortunately, my mangled syntax > describes the way in which default parameters are passed, and does not > allow me to document the class of each parameter. What's the right way > to achieve my goal? > > Sincerely > > Thomas Philips Since Python is not a language that supports manifest typing (that is, type declarations) there is no "right" way to do what you want. When I want to do something like that, I may go Smalltalkish and say something like: def BlackJackValue(aHand): or I may go a bit more conventional and say something more like: def BlackJackValueOfHand(theHand): In either case, you can always write a parameter name so that it tells you something. Beyond that, it's simply a matter of setting a convention and sticking to it rigorously. John Roth From adalke at mindspring.com Thu May 13 02:06:23 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 13 May 2004 06:06:23 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: > > Kirk Job-Sluder wrote: > >> Write me a two-line script in python that reads a character delimited > >> file, and printf pretty-prints all of the records in a different order. Carl Banks wrote one, convoluted so it can be on the command line. Kirk Job-Sluder replied > This looks like using the proverbial hammer to drive the screw. But you asked use to use the hammer to drive in the screw. In real life I have more tools to use. For this case I would use Perl or awk. Here's one for you. I had several mailbox files arranged like Inbox.mbox/mbox Send.mbox/mbox OBF&BOSC.mbox/mbox Work Email.mbox/mbox I wanted to raise the "*/mbox" files one directory so that Inbox.mbox/mbox --becomes--> Inbox.mbox My solution was to use the interactive Python shell. Something like (untested) import glob, os filenames = glob.glob("*.mbox") for name in filenames: os.rename(name + "/mbox", "."+name) os.rmdir(name) os.rename("."+name, name+".mbox") Trying doing that sanely with any programming language expressed all on the command-line. No credit if you can't handle the '&' and space. Andrew dalke at dalkescientific.com From R.Brodie at rl.ac.uk Tue May 25 06:40:20 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 25 May 2004 11:40:20 +0100 Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: "Peter Hansen" wrote in message news:N9KdnVD1v92IlS7d4p2dnA at powergate.ca... > The idea that 'i' is mnemonic for 'integer' is interesting, though. > If the mathematical field is really the origin, rather than FORTRAN, > it would be interesting to know if that was how "they" picked it. > > Googling to little avail, the best I could find to help was Hilbert's > 1900 address on "23 Mathematical Problems" which he gave to the Int'l > Congress of Mathematics in Paris, proving a usage which predates > FORTRAN by 50-some years. I would assume vector algeba was the origin; Google can go back to 1843 on that line: http://www.wordiq.com/definition/Quaternion That suggests that i, j, k notation is an extension of complex notation so i must be the Euler i (1777) presumably standing for imaginary. From __peter__ at web.de Sun May 23 17:53:43 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 May 2004 23:53:43 +0200 Subject: Named integers and enums References: Message-ID: Hallvard B Furuseth wrote: > Is this possible without too much code? > > class Named_int(object, int): > def __str__(self): return self.name > __repr__ = __str__ > __slots__ = 'name' > # This does not work: > def __init__(self, name): self.name = name > # ...and it would be nice to freeze the name: > __setattr__ = __delattr__ = None > > x = Named_int(3, "foo") > print "%s = %d" % (x, x) # print "foo = 3" You need __new__() instead of __init__(): class Int(int): _all = {} def __new__(cls, name, value): try: return cls._all[value] except KeyError: cls._all[value] = self = int.__new__(cls, value) self.name = name return self def __str__(self): return self.name def __repr__(self): return "%s:%s" % (self, int.__str__(self)) >>> from namedint import * >>> debug, info, warn = map(Int, "DEBUG INFO WARN".split(), range(3)) >>> debug DEBUG:0 Instances are cached in _all and thus only created once per value: >>> Int("too late", 0) DEBUG:0 >>> debug < info 1 >>> info + warn 3 >>> Addition etc. will continue to return ints: >>> info + warn 3 Peter From eriksp at attbi.nospam.com Sat May 15 09:51:28 2004 From: eriksp at attbi.nospam.com (EAS) Date: Sat, 15 May 2004 13:51:28 GMT Subject: Input Types Message-ID: How do you make a loop where the program keeps asking for an integer or float until it gets one? (No letters or other input.) From jcarlson at uci.edu Mon May 10 23:41:24 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 10 May 2004 20:41:24 -0700 Subject: Ideas for Python 3 In-Reply-To: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> References: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> Message-ID: >>>>>L = [:x:x**2, :x:x+4, :x:x/5, :x:2-x, :x:x*7 ] >>>> >>>>Ick. >>> >>>Could you be more specific? :>) >> >>Sure, the general format of your anonymous function syntax given above >>does not offer anything that a new user can search for. > > > This is a good point, and one I hadn't thought of. The counter is > that function definition syntax is so basic and so prevalent that any > user of Python will already know it. Lambdas are seldom used, but by > making their syntax almost identical to normal functions, we can make > them self-explanatory. I would add one very short paragraph at the > end of an introduction to functions. > """ > Nameless Functions > ------------------ > There is a short form of a function definition, which is sometimes > used in lists or other places where space is tight. If you can write > your function as a single expression, you can use the short form by > just leaving off the function's name and the return keyword. > .... example above showing long form and short form. > """ > [snip further discussion on searchability] After reading the remainder of your post, I have come to the opinion that of all your offered syntaxes, there exists only one syntax for named and nameless functions that /doesn't/ have severe handicaps of one kind or another. def funct(arg): ... #body return result funct = def(arg): result The above has both a searchable keyword, is easy to describe (you gave a sufficient explanation), and doesn't suffer from the "looks like a slice" (seq[:x:x**2]), "looks like a function call in a slice" (seq[f(x):x**2]), due to the existance of the 'def' keyword. Ultimately it will come down to what people find most intuitive to program with. I think the "lamdba replaced with def adding parenthesis" syntax is preferential to the other options (with removing lambdas a far second, and all other options not even in the running), and I would expect that other current Python users would agree. I've read the link you posted, and I've previously taken a look at Prothon. Prototype syntax does not suit my taste in programming languages. If Python 3.0 becomes Prothon, I'll fork the most recent Python 2.x codebase that I prefer, maintaining it myself if necessary. Just as my anti-prototype perspective colors my opinions on what is reasonable, I would imagine that your pro-prototype perspective colors yours. I would also expect that someone who enjoys using lisp or perhaps SML would have their opinion on what is reasonable, colored by their preferences. Considering that Python is not a prototype-based language today in 2.3 (or the forthcoming 2.4 in the fall), having it become one in Python 3 would be quite a drastic change, quite literally like going from Python 2.3 to Prothon. - Josiah From Joseph.V.Laughlin at boeing.com Fri May 21 18:46:25 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Fri, 21 May 2004 15:46:25 -0700 Subject: Python Newbie Message-ID: <67B3A7DA6591BE439001F2736233351202B47D89@xch-nw-28.nw.nos.boeing.com> > -----Original Message----- > From: Brian [mailto:blugerz at yahoo.com] > Sent: Friday, May 21, 2004 3:35 PM > To: python-list at python.org > Subject: Python Newbie > > > Hi I am new to this newsgroup and new to programming. I have > had this interest in learning to program because.......well > just because. It's just a curiosity that I have. The reason > I am starting with Python, well some of the websites I went > to recommended Python, so here I am. > Ok on to the question. > > I am currently using the book "Python programming for > absolute beginners" by Michael Dawson. The program I am > working on is a password program....dont laugh I know it's > really simple to some, but I am kinda stuck. The book shows > how to code a password program like > this: > > password = raw_input("Enter your password:") > > if password == "secret": > print "Access Granted" > else: > print "Access Denied" > > raw_input("Press the enter key to exit") > > Ok that is easy enough I understand what is going on here. > As the book goes on it also talks about elif, and while > loops. At the end of the chapter it gives various challenges > that the reader is asked to complete. One of the challenges > is to take the password program from above and change it so > that the user gets only three attempts to enter the correct > password. Well I ain't got it to work yet, I thought I came > close, but no cigar. This is what I have so far: #Limiting > password atempts to three > > password = raw_input("Enter your Password: ") > count = 0 > > > while password != "secret": > print password = raw-input("Enter your Password: ") > count += 1 > The above part will loop until password is equal to "secret".... Control of the program will not go continue to the below parts of the program until password == "secret". Joe > if password == "secret": > print "Welcome in." > > > elif count > 3: > print "Please come back when you remember your Password." > > else: > raw_input("Press enter to exit.") > > Ok, I know I may be way off course here but any help would be > greatly appreciated. I dont want to get frustrated and say > the heck with it, especially if it is something minor. > Thanks in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > From greg at cosc.canterbury.ac.nz Tue May 25 22:54:17 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 26 May 2004 14:54:17 +1200 Subject: why i In-Reply-To: References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: <2hif6pFd56hrU1@uni-berlin.de> Dennis Lee Bieber wrote: > However, FORTRAN had the "Indian" {my mnemonic for the > range} -- the default for undeclared variables beginning in the range I > .. N is INTEGER. A .. H, O .. Z are REAL/FLOAT. Hence the well-known saying, "GOD is REAL, unless declared INTEGER." -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jdoyon at ccrs.nrcan.gc.ca Fri May 14 14:08:17 2004 From: jdoyon at ccrs.nrcan.gc.ca (Jean-François Doyon) Date: Fri, 14 May 2004 14:08:17 -0400 Subject: Debugging leaking refcount Message-ID: Hello, I'm working with Zope 2.7 and Python 2.3.3, and I have some leaks I'm trying to track down. So, more generally, I'm wondering what might be good techniques to track down where references are not getting released as they should and so on. As someone who's never done anything like this in the past, here's what I'm thinking: 1) Is there anyway to find out who owns the references? Or at least who/what incremented/decremented the refcounts for a given instance? 2) Or could I add some print statements somewhere that will tell me when a refcount is being increased for a given class, and who is doing it? Maybe by doing some Python/C if I have to? 3) Is there any way to inspect the suspect instances? Connect with gdb or pdb or something like that? I've never used a debugger like that unfortunately, any HOW-TO's out there on this topic? Any help, pointers, tips on this topic would be greatly appreciated! Thanks, J.F. From loic at fejoz.net Mon May 24 04:48:34 2004 From: loic at fejoz.net (Yermat) Date: Mon, 24 May 2004 10:48:34 +0200 Subject: iterator expression - please explain In-Reply-To: <40B1B532.D236209B@alcyone.com> References: <2hdobkFbkjkoU1@uni-berlin.de> <40B1ABFB.B6F854BA@alcyone.com> <40B1B297.6040802@igpm.rwth-aachen.de> <40B1B532.D236209B@alcyone.com> Message-ID: Erik Max Francis wrote: > Helmut Jarausch wrote: > > >>Many thanks for pointing out that silly mistake. >>But why isn't it legal? > > > It's not legal because you typed it in, rather than cutting and pasting > it. You meant: > > myfun([x**2 for x in xrange(10)]) > I don't think so ! It seems to be the new feature "generator expression" or something like that... See http://www.python.org/peps/pep-0289.html -- Yermat From jasvo77 at gmx.net Wed May 26 08:41:47 2004 From: jasvo77 at gmx.net (Jan Voges) Date: Wed, 26 May 2004 14:41:47 +0200 Subject: Bad interpreter References: Message-ID: <9mbg9oay60xg$.xi6k111ljna5$.dlg@40tude.net> Hi! Am Wed, 26 May 2004 13:21:28 +0200 schrieb BaBS: > Thanks for the tips but ... i don't have CR Character ... Are you sure? Aren't there "^M"s at the line ends, when you type 'cat -v myscript.py'? Jan From ark at acm.org Tue May 11 14:46:52 2004 From: ark at acm.org (Andrew Koenig) Date: Tue, 11 May 2004 18:46:52 GMT Subject: Inverse of int(s, base)? References: <2gac73Fk1ooU1@uni-berlin.de> Message-ID: > Is there an inverse function of int(s, base) where base > can be any number up to 36? How about this? )esab ,s(tni :-) From peter at engcorp.com Tue May 11 15:01:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 May 2004 15:01:45 -0400 Subject: OT: Idea for Python T-shirt In-Reply-To: References: Message-ID: Richie Hindle wrote: > [Christos] > >>"With Python your nibbles explode with desire" > > > [Peter] > >>Also, I don't get it... > > > Both you and Christos need to brush up on your Monty Python: > > http://www.intriguing.com/mp/_scripts/phrasebk.txt (about halfway down) No, I got that part, although I didn't remember it was "delight" and not "desire". I just don't understand the combination of things in the image: bits in the stomach of the snake, with that having nothing to do (that I can see) with the "explode with delight" part... I guess it's the mixture of the snake and the Monty Python reference... seems somehow "wrong". -Peter From peter at engcorp.com Fri May 21 13:30:03 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 13:30:03 -0400 Subject: Specify start and length, beside start and end, in slices In-Reply-To: References: Message-ID: Peter Hansen wrote: > For an extremely short list, it's possible that it would be faster > to do Grant's method, but what I was trying to say is that even > if that's true, I expect that for a list of more than a few dozen > elements it would not be faster. Looking at it again, I suspect > that it would actually never be faster, given that probably > about as many bytecode instructions are executed, and then there's > the extra memory allocation for the temporary list, the copying, timeit confirms this with variations on this: c:\>python -c "import timeit as t; t = t.Timer('x[y:][:10]', 'y=10000; x=range(y)'); print t.timeit()" and this: c:\>python -c "import timeit as t; t = t.Timer('x[y:y+10]', 'y=10000; x=range(y)'); print t.timeit()" -Peter From simoninusa2001 at yahoo.co.uk Thu May 20 13:34:47 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 20 May 2004 10:34:47 -0700 Subject: wxPython: Fit() works on wxPanel, but not on surrounding wxFrame References: <39cbe663.0405200528.7182e07c@posting.google.com> Message-ID: <30260531.0405200934.2513290d@posting.google.com> pit.grinja at gmx.de (Piet) wrote: [snip] > class myDialog(wxFrame): > def __init__(self,parent,title): > wxFrame.__init__(self,parent,-1, title, style=wxDEFAULT_FRAME_STYLE) > self.panel = wxPanel(self,-1) > > The position of the controls on the wxPanel inside the frame is > controlled by sizers, which are initialized as follows: > > self.MasterSizer=wxBoxSizer(wxVERTICAL) > self.panel.SetSizer(self.MasterSizer) > self.panel.SetAutoLayout(True) > self.MasterSizer.Fit(self.panel) > self.panel.Fit() > self.Fit() > > To ensure that the size of the window and its layout always take into > account the number of the controls, every function that will change > the number of controls ends with the following threelines: > > self.MasterSizer.RecalcSizes() > self.panel.Fit() > self.Fit() I don't think Fit() is needed, it's implied by: self.MasterSizer.SetSizeHints(self) But you've not used that. You've also not added the panel to the sizer: self.MasterSizer.Add(self.panel, 1, wx.ALL|wx.EXPAND, 0) Also, I think you need a self.Layout() at the end of those three lines. Finally, beware of scrollbars, they're not at all well handled by wx's sizers. To get past the initial layout differing from the resized layout, I usually would call your EVT_SIZE handler to do the initial layout too, then you can just fix one function.... It's a bit hard to debug with only a snippet of code. From loic at yermat.net1.nerim.net Sat May 8 08:50:29 2004 From: loic at yermat.net1.nerim.net (Yermat) Date: Sat, 08 May 2004 14:50:29 +0200 Subject: Preferences Files In-Reply-To: References: Message-ID: Mark Fairchild a ?crit : > Is there a good preferences modules for Python? I know that the Mac > version has one, but I need something cross-platform. > > I just started my first Python project, and I'm used to Java. The > java.util.logging package of the JDK is an amazing resource, and I was > pretty surprised when the Python documentation didn't mention any similar > module for Python. Given that Python API has almost EVERYTHING that the > Java API does and more, I'm sure there must be something like the Java > logging module. > Yes, it has one : logging ! http://www.python.org/doc/2.3.3/lib/module-logging.html And for your preferences module, a simple python file called prefs.py for example can be enough... -- Yermat From brian at sweetapp.com Thu May 20 15:53:56 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 20 May 2004 21:53:56 +0200 Subject: ANN: Vancouver Python Workshop - talk proposals open Message-ID: <40AD0CD4.1090804@sweetapp.com> What's new? =========== The Vancouver Python Workshop is now accepting talk and tutorial proposals. To propose a talk, see: http://www.vanpyz.org/conference/submissions.html The deadline for talk submissions is June 15th. About the Vancouver Python Workshop =================================== The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Talk submissions: until June 15th Attendee registration: June 1st to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From newsgroups at jhrothjr.com Thu May 13 16:18:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 13 May 2004 16:18:10 -0400 Subject: struct doesn't handle NaN values? References: Message-ID: <10a7m0aj181spc5@news.supernews.com> "Grant Edwards" wrote in message news:slrnca7k1l.an4.grante at grante.rivatek.com... > Perhaps I'm doing something wrong: the struct module docs say > it's IEE 754, but I can't figure out how to get it to handle > NaN values correctly (either packing or unpacking). > > >>> x = float('nan') > >>> struct.pack(" Traceback (most recent call last): > File "", line 1, in ? > SystemError: frexp() result out of range > > >>> struct.unpack(" (-6.8056469327705772e+38,) > > I don't have my copy of 754 at hand, but I'm pretty sure that > 0xffffffff is a NaN (printf on IA32 Linux agrees) and not > -6.8056469327705772e+38 as claimed by struct.unpack(). I believe that struct uses the c library as is, like the float support in general. Unfortunately, that leaves everyone at the mercy of the rather inconsistent and ideosyncratic implementations of corner cases in existing c libraries. See PEP 754 for a discussion of the issues. John Roth > > -- > Grant Edwards grante Yow! Of course, you > at UNDERSTAND about the PLAIDS > visi.com in the SPIN CYCLE -- From rogerb at rogerbinns.com Tue May 4 03:34:13 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 4 May 2004 00:34:13 -0700 Subject: Newbe-books References: Message-ID: <0ktjm1-d3q.ln1@home.rogerbinns.com> Adelein and Jeremy wrote: > some other language(s). What you do not need (if my thinking is > correct) is a book about programming using Python. Unfortunately, I > doubt that such a book exists The Python Cookbook published by O'Reilly is a very good example of such a book. It has something like 200 "recipes" in many different areas. All of the recipes are solving a real problem, and in doing so teach you what is Pythonic, what is available in the standard library and many good (and some bad) practises. You can see the complete list at http://www.oreilly.com/catalog/pythoncook/toc.html Roger From winexpert at hotmail.com Wed May 26 08:46:07 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 26 May 2004 12:46:07 +0000 Subject: modifying mutable list elements in a for loop Message-ID: Hi, I'm no expert in python (only a beginner), so my words here probably should be taken with caution... Anyways i would think you are fine. You didn't modify the sequence that comprises 'a'. A is a list of objects. the list stayed the same. Each object did indeed change, but the reference to them (stored in a) hasn't changed). Therefore I would think its ok. However, I will eagerly wait and see how the gurus answer this question as it will be a good learning experience. David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: pballard at ozemail.com.au (Peter Ballard) >To: python-list at python.org >Subject: modifying mutable list elements in a for loop >Date: 26 May 2004 05:39:07 -0700 > >Whew. I hope that title is descriptive! > >Hi all, > >The python tutorial tells me "It is not safe to modify the sequence >being iterated over in the loop". But what if my list elements are >mutable, such as lists or objects, e.g. > >a = [[1,2], [3,4], [5,6], [7,8]] >for coord in a: > coord.append(10) >print str(a) > >When I tried it, it gave the "expected" answer, i.e. > >[[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]] > >It worked, but is it safe? I can't see why it wouldn't be, but >technically I have broken the rules because I have modified the >sequence which is being looped over. > >[It seems to me that the list elements are pointers (in C-speak), so I >can safely modify the data they are pointing to, because I am not >modifying the list elements themselves. Or is that an implementation >detail (i.e. not safe)?] > >Actually the more I think about it the more I think it must be OK, >because how else can one perform an operation on a list of objects? >But that phrase "It is not safe to modify the sequence being iterated >over in the loop" in the tutorial has me slightly worried. > >-- >Regards, > >Peter Ballard >Adelaide, AUSTRALIA >pballard at ozemail.com.au >http://members.ozemail.com.au/~pballard/ >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Learn to simplify your finances and your life in Streamline Your Life from MSN Money. http://special.msn.com/money/0405streamline.armx From and-google at doxdesk.com Fri May 21 11:53:48 2004 From: and-google at doxdesk.com (Andrew Clover) Date: 21 May 2004 08:53:48 -0700 Subject: Help w/ HTMLParser lib References: <40ad7619$0$3114$61fed72c@news.rcn.com> Message-ID: <2c60a528.0405210753.6b7e7192@posting.google.com> Kevin T. Ryan wrote: > HTMLParser.HTMLParseError: bad end tag: "", at line 411, HTMLParser is correct. You can't include the sequence ' block in standard HTML. The ', hiding the problem. The usual solution at the HTML side - for those who care - is to use a JavaScript string literal escape like: document.write('<\/script>'); At the Python side you can't hope to deal with all the crap markup on the web, so unless you know the site you're reading uses valid HTML you should use Tidy to sanitise the input first. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From sridharinfinity at yahoo.com Thu May 6 10:00:59 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 6 May 2004 07:00:59 -0700 Subject: Private identifiers - naming Message-ID: <930ba99a.0405060600.17e076bc@posting.google.com> In python, to hide (from direct access) identifiers from outsiders (not current module), we usually prefix the variables with '__'. But this is usually _difficult_ to read. Imagine a module (which is a common one) containing more private variables than public variables. How cryptic it would be to see text with lot of __ in front of them !! Any thoughts? From marco.terzuoli at libero.it Tue May 18 18:38:08 2004 From: marco.terzuoli at libero.it (Marco Terzuoli) Date: Tue, 18 May 2004 22:38:08 GMT Subject: .py to binary Message-ID: Hi, I would like to convert a .py file into a stand-alone executable, so that anyone can run it without having to install the python interpreter. I know there is a py2exe program for Windows, but I would like to do the same for Linux. Is it possibile or Linux only allow to use python scripts? Thanks for helping, Marco From martin at v.loewis.de Thu May 13 17:30:19 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 13 May 2004 23:30:19 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <40a3d090$0$571$e4fe514c@news.xs4all.nl> References: <40a39511$0$560$e4fe514c@news.xs4all.nl> <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> <40A3BC7E.1010200@v.loewis.de> <40a3d090$0$571$e4fe514c@news.xs4all.nl> Message-ID: <40a3e8e7$0$27036$9b622d9e@news.freenet.de> Irmen de Jong wrote: > Would it be an idea to 'announce' this on the newsgroup, a certain > period before releasing a new Python version? I announce statements like this every year or so. Sometimes, this causes a burst of help, but unfortunately, nothing sustainable. > "There are at least N patches in need of reviews. Please review the > patches to improve their chance of getting included in the next > python version, due in X weeks".... to bring it to people's attention? There are constantly more than 200 patches that need review; starting with that when the next release approaches is often too late. IOW, many of the pending patches won't make it in 2.4.0, and can't make it into any 2.4.x release because of backwards compatibility issues. Targeting them at 2.5.0 makes a tight schedule already... Regards, Martin From dmq at gain.com Fri May 28 14:36:55 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 28 May 2004 11:36:55 -0700 Subject: Unification of Methods and Functions References: <2hic07Fd9q7fU1@uni-berlin.de> Message-ID: On 28 May 2004 08:10:46 GMT, Duncan Booth wrote: >David MacQuigg wrote in >news:eu9cb0tkf674ob8u595sqk9kncs8nvm8k9 at 4ax.com: > >> To summarize our discussion on static methods, we have four ways to >> accomplish the purpose of making a method callable without an >> instance. >> >> 1) Add the staticmethod wrapper. >> 2) Create a dummy instance, and use it to call the method. >> 3) Move the method outside of the class, and if that disturbs the >> modular structure of the program, make the class and its external >> function a new module with its own namespace. >> 4) Move the method outside of the class, but make sure it is still >> "associated" with the class by giving it a special name. >> >> Is there any reason we *should not* use solution #1? > >You missed 5) Use a classmethod wrapper. > >The commonest reason I know of for wanting to a method callable without an >instance is to provide the class with factory functions, and in that case >you definitely don't want to use solution #1 as solution #5 gives you >support for subclassing at no extra charge. I haven't added any classmethod examples to my OOP chapter, because until now I've thought of them as very specialized. I'm searching for a good textbook example, but all I can find is trivially replacable with an instance method or a static method. If you have an instance already, the class can be resolved via self.__class__. If you don't have an instance, the desired class can be passed as an argument to a static method. I sounds like you may have a good use case for classmethods. Could you give us an example, and a brief explanation of what it does that can't be done as easily with other method forms? Your help will be greatly appreciated. -- Dave From bignose-hates-spam at and-benfinney-does-too.id.au Tue May 25 02:45:29 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 May 2004 16:35:29 +0950 Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: On Tue, 25 May 2004 08:10:51 +1000, mr_vocab wrote: > i never got this its always in my tutial bookfor i in range(...) "Index". i.e., the variable will be the index of an array you want to iterate over. The usage of "i" was promulgated by the FORTRAN language, which allowed only single-letter variable names (and was all upper case, too, so it was actually I). The FOR statement was commonly used to iterate over an array, and I and J were the commonly used index variables for that purpose. -- \ "If you write the word 'monkey' a million times, do you start | `\ to think you're Shakespeare?" -- Steven Wright | _o__) | Ben Finney From dialton3#NOSPAM#.despammed at virgilio.it Sat May 15 19:14:31 2004 From: dialton3#NOSPAM#.despammed at virgilio.it (Valentino Volonghi aka Dialtone) Date: Sat, 15 May 2004 23:14:31 GMT Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> Message-ID: <87k6zdl1xv.fsf@vercingetorix.caesar.org> Ville Vainio writes: > Just a thought: it would be more s-expr like if it just had the > "function"ish part inside the list in the normal prefix notation: > > [T.html, > [T.head, > [T.title, 'Hello']], > [T.body, [T.p, 'Welcome...]]] > > In a way this seems slightly clearer (especially the , chars n/w ] > chars seem very suspicous to me. Sure, but I think this is less pythonic than the nevow version, and I find that version also clearer, but I also think that this is a matter of tastes :). -- Valentino Volonghi aka Dialtone Linux User #310274, Proud Gentoo User Blog: http://vvolonghi.blogspot.com Home Page: http://xoomer.virgilio.it/dialtone/ From dmq at gain.com Mon May 24 18:36:21 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 15:36:21 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <2h55ajF9alv2U1@uni-berlin.de> <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> <2hd390Fak5g8U1@uni-berlin.de> Message-ID: On Mon, 24 May 2004 13:59:55 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> Given the goals of the level one and two examples ( cover all the >> basic features in two simple examples ) I think any example will be >> contrived. > >But I don't think you should be trying to cover all the >features of OOP before showing any real examples. That >approach seems almost guaranteed to lose people's interest, >the way you criticised supplier-part examples for. > >Wouldn't it be better to do things the other way around? >Pick some (simplified if need be) examples based on >real-world problems, and, one by one, show how the >features of OOP can be used to solve them. There are lots of ways to write a book. The way I've chosen is following a pattern which I really liked in Introduction to Quantum Theory by David Park. He has a brief, but thorough presentation of all the basics, supplemented by many examples in a second section of the book. Read a few pages of theory, then read the examples and work the exercises. The first time through, it takes a while. Then reviewing the course later is a pleasure. I think it is possible to present the basics of OOP in 8 pages. Supplementary topics like robust programming techniques might add a few more. Examples and exercises could bring the total to 30, maybe 50 pages. We're not planning any discussion of design patterns, which could fill a whole book. This is basic syntax only. All of this depends on the students already understanding the topics prior to Chapter 19, e.g. functions, modules, and global variables. -- Dave From dmq at gain.com Mon May 24 18:22:13 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 15:22:13 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <2h55ajF9alv2U1@uni-berlin.de> <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> Message-ID: On 24 May 2004 19:44:32 GMT, bokr at oz.net (Bengt Richter) wrote: >On Fri, 21 May 2004 05:08:20 -0700, David MacQuigg wrote: > >>On Fri, 21 May 2004 13:45:52 +1200, Greg Ewing >> wrote: >> >>>David MacQuigg wrote: >>>> I'm still waiting for that one simple example that you say will do it >>>> all, and do it right. >>> >>>I don't think you should be trying to cram all the features >>>of OOP into a single example. >> >>I agree. Digestible chunks is the right approach. Animals_1.py is >>the first example of classes, including data, methods, instance >>variables, and inheritance. Thats a pretty large chunk, but what >>makes it digestible is the student's prior knowledge of modules, >>functions, and all forms of data. >> >>Animals_2a1.py (the current version) adds more levels to the >>hierarchy, a special method __init__, static methods, bound and >>unbound methods, the odd scoping rule for class variables, and >>_private variables. This is all the basics that students will need if >>they will be writing their own classes. >> >>There probably won't be an Animals_3, but instead, "level 3" will be a >>bunch of examples to illustrate various techniques, like the robust >>programming that JM has been pushing, and maybe some topics from >>chapters 21 - 23 of Learning Python. >> >>>Also, I worry that the zoo topic will seem contrived. Why >>>not base your examples on some real problems from your >>>audience's subject area? >> >>Given the goals of the level one and two examples ( cover all the >>basic features in two simple examples ) I think any example will be >>contrived. The level 3 examples will be the right place to introduce >>real circuit design problems. >> >If you take some wood and saw off pieces to make a box >with some fasteners, and then you put the leftover pieces >of wood *in* the box, you have pieces of wood with two different >kinds of relationship to the box. Spoken like a Zen Master :>) >I suspect reflecting on this distinction in terms of your examples >might be fruitful. > >I can't spend the time to participate more than stolen moments right now, >so I haven't seen all of the thread. Sorry if I am rehashing something. No need for appologies. I appreciate any and all suggestions. Even better -- a sample program that you think would be right for introducing students to Python OOP. This can be a piece to add to the existing box, or even an alternative box. There is room for both. -- Dave From donn at drizzle.com Sun May 30 12:11:49 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 30 May 2004 16:11:49 -0000 Subject: terminological obscurity References: <1085248385.210031@yasure><51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <55ijb01a95i9ccfn2hut9q8dv1gvogut4c@4ax.com> Message-ID: <1085933508.579296@yasure> Quoth Arthur : | On Tue, 25 May 2004 08:19:49 +0200, "Fredrik Lundh" | wrote: ... |> nonsense. Python has always used duck typing (what's important is what |> you can do with x, not what type(x) happens to be). this hasn't changed a |> bit. | | Putting together what you and Martin are saying, am I correct then | that what type(x) returns in Python is something other than x's type. Python's typing isn't all about what type(x) returns. Donn Cave, donn at drizzle.com From max at alcyone.com Thu May 20 21:40:02 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 20 May 2004 18:40:02 -0700 Subject: Confused about while statement References: Message-ID: <40AD5DF2.69F2015A@alcyone.com> EAS wrote: > In theory, the following code should ask for the user to enter a value > for h > until he/she enters hello or goodbye. > > h = "hi" > while h != "hello" or "goodbye": > h = raw_input("Value for h:") > > But the program keeps asking for a value no matter what I enter. Why > doesn't > it work? You meant while h != "hello" and h != "goodbye": ... -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ She glanced at her watch ... It was 9:23. -- James Clavell From me at privacy.net Fri May 28 09:19:59 2004 From: me at privacy.net (Duncan Booth) Date: 28 May 2004 13:19:59 GMT Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> <40b72a41$0$128$3a628fcd@reader3.nntp.hccnet.nl> <1epn0wa5bqb0r$.heo8w4umjuxm$.dlg@40tude.net> Message-ID: Rodrigo Daunaravicius wrote in news:1epn0wa5bqb0r$.heo8w4umjuxm$.dlg at 40tude.net: > I couldn't find in the docs what > is the meaning of the asterisk in zip(*d), though. Nothing to do with C > pointers, I guess? Python Reference Manual, section 5.3.4 Calls: If the syntax "*expression" appears in the function call, "expression" must evaluate to a sequence. Elements from this sequence are treated as if they were additional positional arguments; if there are postional arguments x1,...,xN , and "expression" evaluates to a sequence y1,...,yM, this is equivalent to a call with M+N positional arguments x1,...,xN,y1,...,yM. From greg at cosc.canterbury.ac.nz Tue May 4 02:44:55 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 May 2004 18:44:55 +1200 Subject: ANN: Pyrex 0.9.2 Message-ID: Pyrex 0.9.2 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Enhancements: * Global variable and attribute names are now interned. * String literals are only converted to Python strings once, instead of each time they're used. * Python string literals may now contain NUL characters. Also fixed a few more problems with the 0.9.1.1 distribution. What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From jbenson at sextans.lowell.edu Fri May 14 12:07:17 2004 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Fri, 14 May 2004 09:07:17 -0700 (MST) Subject: Real-time graphs In-Reply-To: <8A535151-A512-11D8-B27E-000A95AA5CB4@yahoo.com> Message-ID: On Thu, 13 May 2004, snrkiwi-lists wrote: > seems only a couple of possibilities stand out. > > - VPython > - matplotlib > > > Does anyone have any direct experience with either of these inside of > wxPython? It appears that matplotlib will directly work with wxPython, Hi, I started using matplotlib with wxPython a few months ago. I started from the very nice example from Jeremy O'Donoghue: http://matplotlib.sourceforge.net/examples/embedding_in_wx.py The package that i'm writing that uses this combination doesn't do real-time plots but rather provides plots for analysis of our data. I am very happy with the combination wxPython<->matplotlib. Another perk is that both the wxPython and matplotlib newsgroups are very active...either other users or the authors themselves respond very quickly to questions etc. my $0.02 Jim From htx1 at gmx.de Wed May 26 16:30:22 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Wed, 26 May 2004 22:30:22 +0200 Subject: prefix matching In-Reply-To: References: Message-ID: Christian Gudrian wrote: > Given a list with strings. > > What is the most pythonic way to check if a given string starts with one of > the strings in that list? > > I started by composing a regular expression pattern which consists of all > the strings in the list separated by "|" in a for loop. Then I used that > pattern to do a regexp match. > > Seems rather complicated to me. Any alternatives? I'd use something like this: reduce (operator.or_, [string_to_test.startswith (x) for x in list_with_strings]) Greetings, Holger From tuure at laurinolli.net Sat May 29 18:10:26 2004 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Sun, 30 May 2004 01:10:26 +0300 Subject: mod_python confusion In-Reply-To: <153fa67.0405281046.331b1b19@posting.google.com> References: <153fa67.0405281046.331b1b19@posting.google.com> Message-ID: Kylotan wrote: > I thought mod_python would be the answer to my CGI performance issue, > but I can't seem to make much sense out of it. All the examples are > too trivial to be of much use. I recommend using some framework that abstracts the web server - page code interface out of the way. Jonpy is very lightweight, can be used with standard CGI, FastCGI or mod_python without many changes and has pretty nice interface. It is probably relatively easy to write a new "backend" for it if you ever need to. > Given that I have an application consisting of several CGI scripts, > what is the simplest way to go about converting it to run on > mod_python, not using the CGI-handler which is allegedly slow and > buggy? Everything seems to suggest a major rewrite because I not only Converting some simple speed-needing CGI script into something jonpy can handle should be trivial - and with FastCGI it really helps the speed when the interpreter starting overhead is the biggest cause for slowness. Then there are more comprehensive frameworks, which usually have their own server processes to which the webserver of your choice proxies the requests. I don't know much about those, and converting to them probably isn't as easy. From snake at bizportal.co.il Tue May 4 13:11:20 2004 From: snake at bizportal.co.il (snake at bizportal.co.il) Date: Tue, 4 May 2004 19:11:20 +0200 (CEST) Subject: This is an alert from snake Message-ID: <200405041711.i44HBK6U048127@mxzilla7.xs4all.nl> *** detected hostile content in this email. *** Time: 04 May 2004 20:12:29 Scan result: Mail rejected Protocol: SMTP in File Name\Mail Subject: mail_1083895640: Private document Source: python-list at python.org Destination: yael at bizportal.co.il Details: document342.zip\document.txt .exe Infected with Win32.Netsky.q (Non-Removable), Whole File Blocked From alanmk at hotmail.com Mon May 10 04:56:32 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Mon, 10 May 2004 09:56:32 +0100 Subject: Python for Nokia Series 60 In-Reply-To: <2g7siqF57e6rU1@uni-berlin.de> References: <2g7c6lF52kr4U1@uni-berlin.de> <2g7siqF57e6rU1@uni-berlin.de> Message-ID: [jarod] > But on Symbian there is J2ME support, why not use Jython ? and [jarod] > But you haven't answered to my question. Why not think to the use > of Jython? Because jython won't run on J2ME. J2ME doesn't support the reflection API that jython requires to do its magic. [jarod] > Do you know nothing about Java ? Maybe not. Or maybe he just checked the facts before posting? http://groups.google.com/groups?meta=group%3Dcomp.lang.python.*&q=J2ME -- alan kennedy ------------------------------------------------------ check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/contact/alan From sbard at lexpert-auto.com Tue May 25 09:44:40 2004 From: sbard at lexpert-auto.com (sbard at lexpert-auto.com) Date: Tue, 25 May 2004 15:44:40 +0200 Subject: hard disk serial References: Message-ID: THANK'S david !!!! it's works very well !! i feel like a student, but sometimes it's good ! a ?crit dans le message de news: c8vevf$9g4$1 at s1.read.news.oleane.net... > Hi every one > I try to get hard disk serial number > how can i do this ? > > -> THANK'S A LOT > > From ramen at lackingtalent.com Sat May 1 03:16:01 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 01 May 2004 07:16:01 -0000 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com> <69cbbef2.0404291209.7a98a799@posting.google.com> <8ef9bea6.0404292307.66b78b83@posting.google.com> <84Kdnfu3OoN4oA_dRVn-vg@powergate.ca> <69cbbef2.0404301243.451c7b26@posting.google.com> Message-ID: In article , Dave Brueck wrote: > Personally I don't really care much about the discussions about purity or > theoretical language simplicity - the fact of the matter is that having modules > and classes is _useful_. If, under the covers, they are (nearly) identical - so > what? In practice it just so happens that they are handy ways to think about > things (one of the things that annoyed me about Java was that it _didn't_ have > modules). I completely agree with you. I've done a fair amount of both Java and Python programming, and I have to say I really appreciate Python's module system, and I always feel like I'm putting a round peg in a square hole when I use Java's inner classes as a namespacing mechanism. I think Python gets it right in this respect. PHP and JavaScript both try to blur the distinction between object and dictionary. The result is that you can't tell a key from an attribute, and this can sometimes be problematic. PHP goes a step further and removes the distinction between array and dictionary. Perhaps this is easier for people to learn, since they can master one concept and apply it everywhere, but I much prefer having arrays, dictionaries, and objects as separate concepts with their own protocols. I like having classes and modules for the same reasons. Sometimes, it's nice to treat different things as if they were the same. Other times, it's nicer to treat different things as being different. I like a language that gives me a choice in the matter. -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. : please talk to your son or daughter about parametric polymorphism. : From ptmcg at austin.rr._bogus_.com Sat May 15 12:33:23 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 15 May 2004 16:33:23 GMT Subject: python-dev Summary for 2004-04-01 through 2004-04-30 References: Message-ID: Brett - Thanks a bunch for taking the time to do this!!! -- Paul From nospam at nospam.com Thu May 13 11:53:54 2004 From: nospam at nospam.com (3c273) Date: Thu, 13 May 2004 08:53:54 -0700 Subject: Logical AND question Message-ID: Hello, Can someone explain to me why only one of these two if/print statements prints something? Thanks! Louis IDLE 1.0.2 >>> s = '' >>> t = '' >>> if s and t == '': print "This doesn't work!" >>> s and t '' >>> if s == '' and t == '': print "This does!" This does! >>> From matthiasjanes at gmx.net Sun May 16 12:00:58 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 16 May 2004 09:00:58 -0700 Subject: Smalles Possible Browser to display python cgi program References: Message-ID: JanC wrote in message news:... > matthiasjanes at gmx.net (matthiasjanes) schreef: > > > I would like to know what would be the smalles possible WebBrowser for > > displaying Python CGI application. > > > > I developed a few small application with an WebInterface. > > > > The appplication runs just locally. > > > > I use CGIHTTPServer.py Module as a small webserver and Mozilla > > Firebird as Browser. > > > > Does anyone know of a very small browser which I can directly > > integrate. > > > > Just the very minimum for this purbose, no bookmarks, no tools, no > > javascript, no flash ...... > > > > just displaying frames, html, forms, python cgi files and images. > > For Windows there is OffByOne: > Only 450 KiB if you don't need SSL support. Thanks so far to everyone - I forgot to mention that surly I need it crossplatform at least Ms-Windows and Linux compatible. maybe some more explanations: My application is an python database (pysqlite) financial report software, I use the at the moment just python cgi scripts to access and display all. (no javascript at all) I use the CGIHTTPServer.py Module as a small webserver and Mozilla Firebird as Browser. I would like to intigrate with the app also the Webbrowser - as small as possibly. I use frames. I might give wxHTML a try or maybe find a downgraded Firebird Browser. Thanks so far and if anyone has still some more ideas - happily welcomed. Matthias Janes From paul.van.dam at planet.nl Sun May 23 18:54:53 2004 From: paul.van.dam at planet.nl (Paul van Dam) Date: Mon, 24 May 2004 00:54:53 +0200 Subject: newbie: why it does not work: command=sys.exit? Message-ID: I have got a problem with een example from the book "Programming Python" - Mark Lutz I do not understand why it not work for Windows XP and Linux (Fedora Core 1.0). Exactly the same problem was raised by DrPhil: http://coderforums.com/showthread.php?s=16f49a79ed298097f695b0a5fcb27197&threadid=2615&goto=nextoldest import sys from Tkinter import * widget = Button(None, text='Hello widget world', command = sys.exit) widget.pack() widget.mainloop() ---------------------------------------------------------------------------- -------- Traceback (most recent call last): File "I:\Python\Projecten\#Prog_in_Python\Hfst06\gui02.py", line 5, in -toplevel- widget.mainloop() File "D:\Python23\lib\lib-tk\Tkinter.py", line 965, in mainloop self.tk.mainloop(n) File "D:\Python23\lib\lib-tk\Tkinter.py", line 1347, in __call__ raise SystemExit, msg SystemExit From andrew-pythonlist at puzzling.org Wed May 19 22:11:50 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 20 May 2004 12:11:50 +1000 Subject: Sending file to print server using ftplib In-Reply-To: <000d01c43e0b$6a4bc750$f002a8c0@sydney.mri.com.au> References: <000d01c43e0b$6a4bc750$f002a8c0@sydney.mri.com.au> Message-ID: <20040520021150.GD7975@frobozz> On Thu, May 20, 2004 at 11:40:20AM +1000, Joshua Burvill wrote: > Hello, > > I am trying to print something to a print server using the following > function > but I get errors, does anyone have any pointers? It looks like your FTP server doesn't support the PASV command. Try calling "ftp.set_pasv(0)" after logging in. -Andrew. From dmq at gain.com Sat May 1 11:47:00 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 01 May 2004 08:47:00 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> Message-ID: On 28 Apr 2004 02:20:06 -0700, michele.simionato at poste.it (Michele Simionato) wrote: >So far, I have not installed Prothon, nor I have experience with Io, Self >or other prototype-based languages. Still, from the discussion on the >mailing list, I have got the strong impression that you do not actually >need to fork Python in order to implement prototypes. It seems to me >that Python metaclasses + descriptors are more than powerful enough to >implementing prototypes in pure Python. > >I wrote a module that implements part of what David MacQuigg discussed in >http://apache.ece.arizona.edu/~edatools/Python/Prototypes.htm in few lines >of code (disclaimer: this is an horrible hack that changes Python semantics >and makes "super" and "self" kinda of implicit reserved >keywords, highly unpythonic). It requires Python 2.2+. >I have not read the whole David MacQuigg's document, nor I have done any >serious testing of the module, nor I claim I do understand what prototypes >are; also I guarantee there will be bugs and surprising behaviors, but >still I think they could be fixed if I was willing to spend more time >on the issue. This is amazing! I don't understand how it works, but it does provide what I think the "classless" advocates are looking for, an ability to "clone" one object from another, and avoid any "two-tier" organization of instances and classes. >>> cat3 = cat1("Fluffy", "Purr") # Make a new cat from a previous. >>> cat3.talk() My name is Fluffy I am a Feline from Earth Feline talking: Purr! It is a shame that the discussion has degenerated to the point where most people are ignoring threads relating to prototypes. I have tried repeatedly to get a simple requirements statement or use case, and get nothing but sarcastic remarks. I have no experience with prototype languages either, except a little with Prothon. I started to read a paper, but fell asleep after a discussion on the "theory of knowledge". In spite of all this, there are some nuggets along the way. The unification of methods and functions is the one I am most interested in. The code below seems to have the machinery to do that, with the elimination of 'self' from the argument list. That alllows static methods to have exactly the same form as normal methods. ( The 'show' methods below are actually static methods if you remove any references to 'self', and replace them with explicit references, i.e. self.numAnimals --> Animal.numAnimals ). I agree with you that Python has the capability to implement prototypes. Perhaps we can do that using metaclasses for some initial experiments. Then if we get some constructive feedback, we can put together a PEP to make prototypes part of the core language, add better syntax, and fix whatever might not work quite right using metaclasses. I'm collecting ideas for Python 3 and 4 and putting them on my webpage at http://ece.arizona.edu/~edatools/Python Python 3 includes features that are not compatible with Python 2, but I believe are consistent to the extent that Python 2 programs can be automatically translated to Python 3. Python 4 has no such contraint. All that matters is that the language is simple and elegant, and does useful things, as opposed to things that are theoretically interesting. Your comments and suggestions are welcome. -- Dave >Here is an example of usage: > >from prototype import Prototype # prototypes are implemented as classes > >class Animal(Prototype): > numAnimals = 0 > home = "Earth" > def __init__(): # no need to pass self around > Animal.numAnimals += 1 > def show(): > print "Animals:", self.numAnimals > >class Feline(Animal): > genus="Feline" > def __init__(name,sound): # no need to pass self around > super.__init__() > self.name=name > self.sound=sound > def talk(): # no need to pass self around > print "%s talking: %s!" % (self.genus,self.sound) > >class Cat(Feline): # how to call the super prototype > numCats = 0 > def __init__ ( n = "unknown", s = "Meow" ): > super.__init__(n,s) > Cat.numCats += 1 > def show(): > super.show() > print " Cats:", self.numCats > def talk(): > print "My name is", self.name > print "I am a %s from %s" % (self.genus, self.home) > super.talk() > >cat1 = Cat() # abuse of notation: makes a new prototype, not an instance > >print cat1 # => ># > >cat2 = Cat("Garfield") >cat2.home = "Tucson" > >print cat2 # => ># > >cat1.talk() # => ># My name is unknown ># I am a Feline from Earth ># Feline talking: Meow! > >cat2.talk()# => ># My name is Garfield ># I am a Feline from Tucson ># Feline talking: Meow! > >cat2.show() # => ># Animals: 2 ># Cats: 2 > >I am not sure this does what prototype people wants, but still it is >a nice example of how to abuse Python ;) Originally, I tried to use >"_" for "self" and "__" for "super", but with my fonts it was >difficult to distinguish between them. With a preprocessor one >could replace .name -> self.name and ..name -> super.name, but >I did no bother to do that. > >Here is the module (not at all optimized): > >$ cat prototype.py >import sys >from types import FunctionType >from inspect import isfunction > >class methodwrapper(object): # descriptor > def __init__(self,func,cls): > self.__func__=func > self.__cls__=cls > def __get__(self,none,cls): > globs=sys.modules[cls.__module__].__dict__.copy() > globs["self"]=cls > globs["super"]=super(self.__cls__,cls) > return FunctionType( > self.__func__.func_code, > globs, > self.__func__.func_name, > self.__func__.func_defaults, > self.__func__.func_closure) > >class _Prototype(type): # metaclass > def __init__(cls,name,bases,dic): > for k,v in dic.iteritems(): > if isfunction(v): > setattr(cls,k,methodwrapper(v,cls)) > super(_Prototype,cls).__init__(name,bases,dic) > def __call__(cls,*args,**kw): > newcls = type("Prototype:%s" % cls.__name__,(cls,), > {"__module__": cls.__module__}) > newcls.__init__(*args,**kw) > return newcls > >class Prototype(object): # mother of all prototypes > __metaclass__=_Prototype > def __init__(*args,**kw): > pass > >#### END #### > > Michele Simionato From martin at v.loewis.de Fri May 14 14:30:28 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 14 May 2004 20:30:28 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <3064b51d.0405140758.4c556d8e@posting.google.com> References: <3064b51d.0405140758.4c556d8e@posting.google.com> Message-ID: <40a5103e$0$13036$9b622d9e@news.freenet.de> beliavsky at aol.com wrote: > I wonder why the Linux installation needs to be more tedious than the > Windows counterpart. The problem is of course not specific to Python. > There are many Linux distributions, running on different kernels, but > maybe binaries that have been tested on the "major" distributions like > Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. Volunteers are welcome. Martin From apardon at forel.vub.ac.be Fri May 7 04:50:03 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 May 2004 08:50:03 GMT Subject: Scope rule pecularities References: Message-ID: Op 2004-05-07, Josiah Carlson schreef : >> Well I would say that seems to go against the intention as stated >> in the reference manual. += and associated should attempt the >> operation in place. If you do an operation in place there is >> no need to rebind the variable. > > Except when the /referenced object/ is immutable. Name rebinding is > necessary to reference the newly created immutable object that was > created through the +=, -=, /=, %=, *=, &=, |=, or ^= operations. IMO having operators that should work in place for object that are immutable, sound contradictory. Having the following code: a = ... b = ... c = a a += b I now expect a and c still to be the same object. -- Antoon Pardon From htx1 at gmx.de Mon May 10 02:24:41 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Mon, 10 May 2004 08:24:41 +0200 Subject: Passing objects to a function In-Reply-To: References: Message-ID: Robert Brewer wrote: > Thomas Philips wrote: >>def BlackJackValue(hand=Hand): >> adfsadf >> adfasdf >> . >> . >> . >> >>It takes only one look at this method's definition to realize that it >>requires an object of type Hand. Unfortunately, my mangled syntax >>describes the way in which default parameters are passed, and does not >>allow me to document the class of each parameter. What's the right way >>to achieve my goal? > > > Since it's a bound method, the "right" way for the above would be to use > "self". ;) > > Barring that, however, the right way to document a function is: the > documentation string, of course! > > >>>>str.join.__doc__ > > 'S.join(sequence) -> string\n\nReturn a string which is the > concatenation of the strings in the\nsequence. The separator between > elements is S.' > > ...following the example for the 'str' builtin, you might write: > > def BlackJackValue(hand): > """BlackJackValue(Hand_instance) -> int\n\nReturn an integer, which > is the value of the Hand according to the rules of BlackJack.""" > pass > This could be supported by an assert statement: def BlackJackValue(hand): """BlackJackValue(Hand_instance) -> int\n\nReturn an integer, which is the value of the Hand according to the rules of BlackJack.""" assert isinstance (hand, Hand) [...] The method will throw an AssertionError if hand is not an instance of Hand. Assertions can be turned off later for performance reasons; with -O I guess. Greetings, Holger From aahz at pythoncraft.com Mon May 3 12:14:43 2004 From: aahz at pythoncraft.com (Aahz) Date: 3 May 2004 12:14:43 -0400 Subject: PEP 328 update References: <40967109$1@nntp0.pdx.net> Message-ID: In article <40967109$1 at nntp0.pdx.net>, Scott David Daniels wrote: >Aahz wrote: >> >> PEP 328 (``import`` changes) has been updated and is available at >> http://www.python.org/peps/pep-0328.html >> >> Comments on the revised version are welcome. One area where feedback is >> particularly desired is on the frequency of relative imports inside >> packages in current code, both in absolute terms and as a percentage of >> all imports. > >I am unclear as to why "import ..moduleA as A" is not allowed. The only >rationale given for disallowing relative imports like "import .foo" is >that .foo is unacceptable as a name. I'd propose a mandatory AS-clause >if the MODULE begins with a period. > >This would allow me to do something like "import . as mypackage" -- a >case which is perhaps unnecessary. I just found the "must use the >from-style imports" surprising (I agree the change is not vital). I'm no expert, but I'd bet that Python's grammar can't support this. Someone will be by to correct me if I'm wrong. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I used to have a .sig but I found it impossible to please everyone..." --SFJ From deetsNOSPAM at web.de Mon May 17 14:06:54 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 17 May 2004 20:06:54 +0200 Subject: html to image or html to postcript to image References: <6LqdnQ67eel2cTXdRVn-gQ@comcast.com> Message-ID: Larry Bates wrote: > Python used pdfTEX to generate their .PDF manual from > their HTML manual. It located at: Thats unlikely - they used pdftex to generate the pdf from latex, and whatever to generate html from latex. So it won't help the OP. -- Regards, Diez B. Roggisch From PeterAbel at gmx.net Wed May 26 03:36:11 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 26 May 2004 00:36:11 -0700 Subject: alter / modify a list as well as iterate on its items / objects References: Message-ID: <21064255.0405252336.2f3c7418@posting.google.com> Derek Basch wrote in message news:... > Hello, > > Can anyone point me towards an article or explain > how to properly alter a list as well as iterate > on its items? For example: > > input: > > word = ["albert", "likes", "surfing!"] > > for word in sentence: > word += "foo" > > result: > > word = ["albertfoo", "likesfoo", "surfingfoo"] > > Thanks, > Derek Basch > . . . An solution No. 992345739219242.... is:-): >>> from operator import add >>> word = ["albert", "likes", "surfing!"] >>> map(add,word,['foo']*len(word)) ['albertfoo', 'likesfoo', 'surfing!foo'] >>> Regards Peter From imbosol at aerojockey.invalid Sat May 22 20:15:46 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Sun, 23 May 2004 00:15:46 GMT Subject: What is the name of this Python programming style References: <2ha8alFaq80qU1@uni-berlin.de> Message-ID: Dave Kuhlman wrote: > In this style or pattern, a high level class is given an instance > (or a class from which it creates an instance), then uses that > instance to perform its tasks. Delegation. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From aweil at mail.ru Wed May 19 16:14:59 2004 From: aweil at mail.ru (alejandro david weil) Date: Wed, 19 May 2004 17:14:59 -0300 Subject: Serious trouble with https (Python 2.2.3 & 2.3.3), How to check for working ssl? In-Reply-To: References: Message-ID: <200405191714.05254.aweil@mail.ru> On Wed May 19 2004 16:12, Phillip wrote: > No matter what I do to open a webconnection with httpS I always get > something in this Area: > urllib2.URLError: > > With both versions of Python mentioned above. > > My strong suspicion is that the socket stuff (dunno exact libname right > now...) is compiled without ssl support. > > What I would like to know now is following: > > 1) What is the default setting for the compilation of the original > Python source? _With_or _without_ ssl support? > > I just downloaded the sources onto Debian Linux and did the configure, > make, make install dance. No fumbling on my side done here. > 2) If this can't be said for shure _how_ can I find out if my version of > Python was compiled with ssl support? Apart from trying to connect via > https that is. Like I said: I've got a seriously growing suspicion that > it _is_ unsupported ssl due to compilation. I'm using python 2.3 in debian (package: python version 2.3.1-3) and has ssl support. You may try: aweil at tenuki:~$ python Python 2.3.1 (#2, Sep 30 2003, 00:50:40) [GCC 3.3.2 20030908 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.ssl(-1) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) TypeError: ssl() argument 1 must be _socket.socket, not int socket.ssl function is used to handshake ssl over a socket.. Sometimes I had problems using ssl with urllib, and proxies. So I wrote: http://ahttplib.sf.net/ There aren't packages for install ready, but you can download it from cvs (*) (its 4 files). The main file, includes some usage example, in its unittest section. Good luck and tell me if I can help you. david (*) http://cvs.sourceforge.net/viewcvs.py/ahttplib/ahttplib/ -- + There is no dark side of the moon really. Matter of fact it's all dark. From peter at engcorp.com Wed May 26 07:51:42 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 07:51:42 -0400 Subject: Bad interpreter In-Reply-To: References: Message-ID: BaBS wrote: > Le Wed, 26 May 2004 07:08:50 -0400, Peter Hansen a ?crit : >>BaBS wrote: >>>I've a problem whith my python script, >>> i chmod'ed it to +x, addes the line : >>>#!/usr/bin/python2.3 >>>and i verified that /usr/bin/python2.3 exists >>>but i've something like >>>: bad interpreter: No such file or dir ... >>> >>>What's the matter ?? >> >>Remove the hidden CR character which you got at the end of the >>lines by moving the file to a Windows system and editing it. ;-) >> >>This one is pretty tricky to figure out the first few times... > > Thanks for the tips but ... i don't have CR Character ... > i edit my file with notepad and editplus but no matter what > It's the same message :/ It's either that or /usr/bin/python2.3 doesn't really exist. If you type "/usr/bin/python2.3" at the prompt, does the interpreter come up properly? If it does, try creating a new file without using an editor. Type the commands below at the Linux $ prompt: $ cat >test.py #!/usr/bin/python2.2 print 'works' (hit Ctrl-D here to close the file) $ chmod +x test.py $ ./test.py works If you don't get the final output, but still get the "bad interpreter" thing, yet if the interpreter works properly when you execute it directly, then I have no idea and will be quite interested to learn the final solution. -Peter From dave at pythonapocrypha.com Fri May 28 13:35:50 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 28 May 2004 11:35:50 -0600 Subject: "Private" Member Variables References: Message-ID: <028501c444da$385e25f0$6b1e140a@YODA> Scott wrote: > I'm still learning Python as I develop a medium-sized project. From my > previous experience with C++, I've burnt into my mind the notion of > information hiding. I'm having trouble understanding to what extent I > should follow this policy in my Python code so I thought I'd ask the group. Holy cow, Scott! Congratulations - many people come to Python from other languages and are completely unable or unwilling to believe that Python's approach to information hiding isn't broken. Many of them, upon seeing that it is more relaxed than C++ even postulate that Python doesn't support object-oriented programming (which is funny, but annoying). I'm sure other people will better answer your question, but I just wanted to say 'thanks' because it's refreshing to hear "This is different, what are some good practices?" as opposed to "This is different, it must be broken!". > why provide an accessor at all? Why not just allow direct reading and > writing of the member variable? Is there something here I'm missing? > > What are your thoughts? How much privacy should I build into my code? > Should I be using variables beginning with "__" and accessors? Or is that > simply not necessary (or normal) in Python code? IMO the thing that matters most is consistency. For a given class, just make sure you go all one way or another - all direct access or all accessor functions. I like the fact that you have the freedom to choose - some classes are closer to C structures (they are mostly dumb data containers), so it makes "sense" to access them in that way. Other classes more closely represent the traditional notion of an object (data + operations on the data), so access through functions is a cleaner interface and safeguards against fiddling with class internals that could break things. -Dave P.S. The only time I use underscore prefixes is for the direct-access classes. If I document the class as one in which you should use the accessors instead of going direct, then I generally don't bother with the underscores. From YuZH at spdb.com.cn Sun May 9 21:07:20 2004 From: YuZH at spdb.com.cn (=?gb2312?B?0/TWvruq?=) Date: Mon, 10 May 2004 09:07:20 +0800 Subject: list comprehension Message-ID: <79903392541AF5408A94A82B53A17A680131DF1E@hdqsmsg01sexg2k.HDQ.SPDB.COM> >>> ' '.join(map(lambda x:x[0]+',-'+x[1],[a.split(',') for a in s.split()])) '114320,-69808 114272,-69920 113568,-71600 113328,-72272' -----????----- ???: Guy Robinson [mailto:guy at NOSPAM.r-e-d.co.nz] ????: 2004?5?10? 8:32 ???: python-list at python.org ??: list comprehension Hello, Trying to change a string(x,y values) such as : s = "114320,69808 114272,69920 113568,71600 113328,72272" into (x,-y): out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" I tried this: print [(a[0],-a[1] for a in x.split(',')) for x in e] But it doesn't work. Can anyone suggest why or suggest an alternative way? The text strings are significantly bigger than this so performance is important. TIA, Guy -- http://mail.python.org/mailman/listinfo/python-list From bac at OCF.Berkeley.EDU Sat May 15 01:37:32 2004 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Fri, 14 May 2004 22:37:32 -0700 Subject: python-dev Summary for 2004-04-01 through 2004-04-30 Message-ID: <40A5AC9C.2010807@ocf.berkeley.edu> python-dev Summary for 2004-04-01 through 2004-04-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from April 01, 2004 through April 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 thirty-ninth and fortieth summary written by Brett Cannon (Should be doing homework instead). 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-04-01_2004-04-30.html .. _original text file: http://www.python.org/dev/summary/2004-04-01_2004-04-30.ht ===================== Summary Announcements ===================== Well, as you may have noticed, I wasn't able to keep up the pace of releasing the summaries twice in a month. Joys of school. Hopefully over the summer I will be able to semi-monthly releases since I will only be working and not have homework hanging over my head 24/7. To give everyone a a heads-up, a release candidate for Python 2.3.4 is going to be released May 13/14 (depending where you are on the globe). If you have time, please download it and run the regression test suite (instructions can be found in the module documentation for the 'test' package) and report any issues you have. ========= Summaries ========= -------------------------------------------------------- Method decorators and the discussion that will never end -------------------------------------------------------- Method decorators and `PEP 318`_ were discussed ad nausea this past month. The PEP should be updated in the near future. .. _PEP 318: http://www.python.org/peps/pep-0318.html Contributing threads: - `PEP 318 -- a couple use cases `__ - `PEP 318: Decorators last before colon/bakeoff `__ - `PEP 318 bake-off? `__ - `PEP 318: Is decorators the right term for these things? `__ - `Re: PEP 318: Let's propose some useful built-in decorators `__ - `Help with PEP 318 `__ - `PEP 318: Properties `__ - `PEP 318: More examples of decorator use `__ - `PEP 318: How I would implement decorators `__ - `PEP 318 - check for consensus `__ ------------------------------------------------------------ Relative imports: the *other* discussion that will never end ------------------------------------------------------------ `PEP 328`_, which covers relative imports, has been updated to cover its lengthy discussion. It seems the PEP is pretty much finalized. .. _PEP 328: http://www.python.org/peps/pep-0328.html Contributing threads: - `Re: PEP 328 -- relative and multi-line import `__ - `Some comments on PEP 328 (absolute/relative imports) `__ - `PEP 328: __path__ `__ - `from ...sys import path `__ -------------------- stdlib: Python or C? -------------------- The question of whether stdlib modules should be coded in Python or C came up again. Armin Rigo posted some numbers comparing performance of heapq using the Python version both in a stock Python interpreter and in Psyco_ and then the C version. Armin's quick timings showed that the Python version of heapq was actually faster than the C version when used in Psyco. If it is possible to get the Python version to go faster, should it and future modules be coded in Python? The usual arguments over maintenance and readability were brought up. In the end the Python version of heapq was put back into the library with the C version renamed to _heapq. .. _Psyco: http://psyco.sf.net/ Contributing threads: - `Python is faster than C `__ ----------------------------------- Getting an Interest Group on Artima ----------------------------------- Bill Venners of Artima_ asked if there was anyone who wanted to act as a moderator for an interest group for Python on the site. If you are interested, read the email for details. .. _Artima: http://www.artima.com/ Contributing threads: - `Python Interest Group `__ ------------------------------- Informative reprs for iterators ------------------------------- Raymond Hettinger suggested having the repr of iterators for built-in types list the first three objects returned by the iterator. That way you would actually know what was in the iterator. It was suggested only for iterators where the length of the iterator was known and extracting the first three objects from the iterator to display them would be cheap. In the end, though, it was not added for built-in types. Some itertools iterators, though, did get more informative reprs. Contributing threads: - `More imformative iterator representations `__ - `Proposed iterator representations `__ ------------------------------ Turning globals into constants ------------------------------ Raymond Hettinger came up with some code that could take a code object and make all globals constants, thus speeding up access and removing code that did this explicitly (``_len = len``, etc.). It was proposed for the stdlib in `PEP 329`_, but was rejected in the end for being too "hackish" in terms of fiddling with bytecode directly. It did bring up the idea of trying to come up with a way to flag built-ins that might be masked. If the compiler knew what built-ins were not going to be masked a direct lookup in the built-in namespace would be all that was needed to access a built-in. As it stands now, though, since an external module could inject a shadowing function into the global namespace of a module (such as having module bar having the code ``import foo; foo.len = lambda x: 42`` to shadow 'len' in the module foo), Python has to check the global namespace first, and then the built-in namespace for all non-local name accesses. That is costly and it could possibly be avoided since the common case is to not shadow a built-in. Guido suggested having programmers have to specify when a built-in could be shadowed. This could be compared to the 'volatile' keyword in C; the programmer has to specify when the compiler should not try to optimize access. This seemed like the best way to go since forcing the programmer to flag when a built-in will *not* be shadowed would be more work for the common case. Obviously this would all break backwards-compatibility and thus would either require a __future__ statement initially or would be like true division and always be a __future__ import until Python 3.0 . But it was all just being thrown around with no concrete ideas on implementation and such. .. _PEP 329: http://www.python.org/peps/pep-0329.html Contributing threads: - `Candidate Function Decorator `__ - `PEP 329: Treating Builtins as Constants... `__ - `peps 329, 266, 267 `__ ----------------------------- Decimal "stuff" was discussed ----------------------------- Two big topics came up about the Decimal package. The first one was over whether there should be an exponent limit. The discussion went back and forth, but in the end it was decided that having a limit is good since it will prevent undetected overflow and underflow. The second topic was about adding extra methods. This was shot down since the point of the Decimal module is to follow the standard as put forth at http://www2.hursley.ibm.com/decimal/decarith.html . After the module has been in the library and seen some wide usage then possible additions beyond the standard could be made. exponent limit repr (passable to eval if possible) sticking to spec initially Contributing threads: - `Decimal data type issues `__ - `Decimal conversion to string `__ - `Decimal - context manipulation `__ ------------------------------------------------- Magic hashing numbers segues into JIT compilation ------------------------------------------------- Raymond Hettinger suggested using a different number for hashing since it could be expressed in terms of shifts and additions. But Tim Peters said it was a bad idea to futz with the number since the current one had proven its usefulness for so long and had been studying in a Python-specific way years ago. Since part of the justification for changing to another number was the number of cycles it would take to do the calculations, the discussion shifted to JIT compilation. Clarification for JIT compared to specialized compilation (former does single compiled version of a function while the latter does multiple versions based on the argument types) came up along with wondering how some of the optimizations used in the Self_ language could be applied to Python. .. _Self: http://research.sun.com/self/language.html Contributing threads: - `String hash function multiplier `__ - `Optimization targets - refcount `__ ---------------------------------- Modules that need some documentin' ---------------------------------- Yours truly compiled a list of modules that need documentation that can be found both in the email starting this thread (although I made one mistake on that list of including the imp module) or at http://www.python.org/cgi-bin/moinmoin/ModulesThatNeedDocs where Michael Chermside was nice enough to put it on up on the wiki. Writing docs for modules is not that hard and is a great way to help out. See http://www.python.org/dev/doc/devel/doc/doc.html on how to do documentation using LaTeX. And if that scares you, even just writing the docs in reST_ is helpful since someone else can volunteer to convert it to LaTeX. Contributing threads: - `Possible modules that could use docs `__ -------------------------------------- A change in the name of the CVS server -------------------------------------- SourceForge_ started forcing people to use cvs.sf.net:/cvsroot/python as the location of the CVS server as compared to the previously supported (but not "official") path of cvs.python.sf.net:/cvsroot/python that shows up as SSH reporting a possible man-in-the-middle attack. Barry Warsaw posted a Python script by Greg Ward that would traverse a CVS checkout and change the name of the CVS server. That script can be found at http://mail.python.org/pipermail/python-dev/2004-April/044593.html . Contributing threads: - `SSH problems getting into SourceForge's CVS? `__ --------------------------- A ConfigParser replacement? --------------------------- Dan Gass presented his `config.py`_ to python-dev to see if there was any interest in adding it. While he was given the standard response that no new modules will be accepted for inclusion in the stdlib until it has seen widespread acceptance and use by the community, Barry Warsaw suggested a possible ConfigParser replacement shootout ala the `getopt-sig`_ and how it was decided that optparse (aka Optik_) should be the suggested command-line parser used. This won't happen for 2.4, but if people are interested enough this could be done for 2.5 if someone decides to spear-head this. People also immediately pointed out ZConfig_ (by our very own Fred Drake) as another possibility. .. _config.py: http://config-py.sf.net/ .. _getopt-sig: http://mail.python.org/mailman/listinfo/getopt-sig .. _Optik: http://optik.sourceforge.net/ .. _ZConfig: http://www.zope.org/Members/fdrake/zconfig/ Contributing threads: - `Proposal: A more powerful alternative to ConfigParser `__ - `Proposal: A more powerful alternativeto... `__ ----------------------------------------- Moving forward with generator expressions ----------------------------------------- Guido said he wanted to get generator expressions into CVS. While this is good and all, it still doesn't address the whole argument over whether early or late binding for variables in the genexps should be used (in case you have not been following, early binding would have a genexp save the state of the variables used in the genexp at creation time while late binding will use the state of the variables at the time of each execution of the genexp). Since Guido prefers the late binding for simplicity, he suggested using it for 2.4a1 and a2. If it was found that late binding was bad then for 2.4b1 early binding could be used. No one had issues with that idea. What people did have issue with was the whole thing about late bindings period. Basically the issue boils down to whether late binding is too much of a surprise for the cases where they can have issues. But Greg Ewing pointed out that the use case that genexps were being created for were for arguments to functions; a use case where the genexp is used immediately and whose possible abuse of variables would not be an issue. It was realized that genexps are not exactly the same as listcomps and thus not a direct replacement. Genexps are meant for places where memory is going to be an issue; if a listcomp would do just a good of a job, then just go ahead and use a listcomp. Contributing threads: - `PEP 289 - Generator Expressions - Let's Move Forward `__ --------------------------------------------------- How should gettext return strings from an .mo file? --------------------------------------------------- Gustavo Niemeyer noticed that if you called 'gettext.gettext' it would return the exact bytes stored in the .mo file. Apparently `GNU gettext`_ translates the bytes according to the current locale instead of just passing them through untouched. Gustavo wanted to make Python match the GNU implementation. Barry Warsaw and Martin v. Loewis disagreed, though. Since Python's way of doing it has been that way for so long, they didn't want to break backwards-compatibility. It was also stated that code should use 'gettext.ugettext' anyway. In the end it was agreed upon that if Gustavo wanted this functionality he should add another function to 'gettext' (such as 'lgettext') that did what he wanted. .. _GNU gettext: http://www.gnu.org/software/gettext/gettext.html Contributing threads: - `Small issues in gettext support `__ ----------------------------------------------- And how long have you been hacking on the core? ----------------------------------------------- Anthony Baxter, fearless release manager, decided to run the Misc/ACKS file through ``cvs annotate`` which prints out who edited every line and when it was edited and then he sorted it. This was to see when people were added to the ACKS file and thus find our roughly how long people have been hacking on the Python core. The file wasn't started until January 26, 1994 so a lot of the "old-timers" don't have exact dates (of which Anthony is one of them). Yours truly was added on July 19, 2002. Contributing threads: - `today's pointless, yet slightly terrifying, factoid(s) `__ From cm at leetspeak.org Sat May 15 17:48:15 2004 From: cm at leetspeak.org (Michael Walter) Date: Sat, 15 May 2004 23:48:15 +0200 Subject: Stackless python and microthreads In-Reply-To: References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <2gk1k2F3li0jU1@uni-berlin.de> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> Message-ID: <2gnhh0F4r098U1@uni-berlin.de> Ville Vainio wrote: >>>>>>"Michele" == Michele Simionato writes: > Michele> of learning Zope TAL/TALES/METAL, which I do not like > Michele> that much; I would rather prefer to generate HTML pages > Michele> with Lisp macros and use real s-expressions instead of > Michele> XML/HTML, but I can't :-( > What would you do with macros? [..] Syntactic abstraction. I would love to see macros in Python (actually working on some ideas for adding them to Python). Cheers, Michael From none at shall.pass Sat May 15 05:03:38 2004 From: none at shall.pass (Thomas) Date: Sat, 15 May 2004 11:03:38 +0200 Subject: updating (Cheetah) html in twisted webserver with Gadfly Database Message-ID: <20040515110338.2259e094.none@shall.pass> Hi, i have a webserver with (approx.) the code below, but whatever i do the html code sent to the browser stays the same. The strangest is, if i insert a local variable in the class which is incremented upon each call to self.render_GET() and append it to the html code, it increments correctly on the browser. Could it be a probem with gadfly? from twisted.web import resource, server class webserv(resource.Resource): isLeaf = True def __init__(self): #filling self.template with html code #filling self._namespace with data for Cheetah def update_namespace(self): #call upon a gadfly- database and update the namespace def render_GET(self, request): return Template(self.template, searchList=[self._namespace]).__str__() WebServer = webserv() site = server.Site(WebServer) reactor.listenTCP(80, site) reactor.run() From newsgroups at jhrothjr.com Mon May 10 18:47:38 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 May 2004 18:47:38 -0400 Subject: How to read files written with COBOL References: Message-ID: <10a01sgq4olc459@news.supernews.com> "asdf sdf" wrote in message news:VYSnc.46990$v46.35205 at newssvr29.news.prodigy.com... > Batista, Facundo wrote: > > People: > > > > I'm trying to convert my father from using COBOL to Python, :) > > > > One difficult thing we stuck into is how to read, from python, files written > > with COBOL. > > > > Do you know a module that allows me to do that? > > > > It should avoid us the work to write a COBOL program that open the COBOL > > file and write a CSV one (easily readable from python). > > > > Thank you all! > > > > Facundo Batista > > Desarrollo de Red > > fbatista at unifon.com.ar > > (54 11) 5130-4643 > > Cel: 15 5132 0132 > > > > > > > i'm going to watch this thread with interest. a couple of weeks ago, i > asked about python to legacy mvs particularly for DB2 and Adabas access. > i got zero responses which suggested to me that no tools or modules > are in wide use. I missed seeing it, somehow, but you're also right: I don't know of any tools either. > i think you are undertaking a simpler problem generally. if all your > records are text it should be fairly straightforward. if not, you'll > need to figure out how to map COBOL data representations into python. In other words, take the 01s under the FD and create an object that would expose all the converted data elements for the record? Could be a somewhat interesting project, and it shouldn't be all that hard since data descriptions are a fairly limited syntax. > you also need to handle REDEFINES which is used to produce a c-union > sort of arrangement, where multiple formats can be used to access the > same record. Redefines in implicit - it's just multiple level 01s under the same FD. > 88-Levels are a similar problem. Aren't an issue. 88s are basically an isXXX type function call. That's not how they're implemented, but that's the basic semantics. > after Y2K, a lot of COBOL files contain some non-obvious date handling, > which could involve bit manipulation. > > if you learn of any sorts of tools at all, please post them back here. > python screen scrapers, python compatible database drivers, anything at all. > > interesting project idea: a COBOL to python _code_ converter. should > be feasible, in light of COBOL's very limited syntax. > > ah, COBOL fun. all us old guys are reflecting on how glad we are we > left it behind. Ain't that the truth! John Roth From mwilson at the-wire.com Fri May 21 19:22:25 2004 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 21 May 2004 19:22:25 -0400 Subject: TypeError: unsubscriptable object. References: <494182a9.0405211340.49873a72@posting.google.com> Message-ID: In article <494182a9.0405211340.49873a72 at posting.google.com>, balaji at email.arizona.edu (Balaji) wrote: >Hello Everybody... > >I have a problem.. [ ... ] >---------------------------------------------- >I'm getting the following error TypeError: unsubscriptable object... >Traceback (most recent call last): > File "", line 1, in ? > File "generation.py", line 175, in stackManagement > self.stackManagement(expr.left) > File "generation.py", line 176, in stackManagement > self.stackManagement(expr.right) > File "generation.py", line 199, in stackManagement > self.a+= self.peekF() > File "generation.py", line 168, in peekF > rval= self.stackF[-1] >------------------------------------- >I 'm at my wit ends.. > >Can anyone help... Something has come unstuck. I would try wrapping the failing statement: try: rval= self.stackF[-1] except TypeError: print "TypeError, self.stackF:", repr(self.stackF) sys.exit (-1) and see what comes out. Regards. Mel. From jeanmarc.ranger at smisrd.com Wed May 5 15:12:44 2004 From: jeanmarc.ranger at smisrd.com (Jean-Marc Ranger) Date: 5 May 2004 12:12:44 -0700 Subject: Improvement ? Message-ID: Just wondering: With Python 2.3.3 for Windows, I understand why os.makedirs("C:\SomeDirectoryThatDontExist\.\AnotherDirectory") fails throwing an exception saying "OSError: [Errno 17] File exists" - the period is like a request to create the same directory a second time. But is this the expected behavior ? I personaly would prefer to see this operation succeed - and don't like the idea of writing a workaround :) Comments ? Thanks, Jean-Marc Ranger From no.email at please.com Tue May 4 11:46:04 2004 From: no.email at please.com (Stevie_mac) Date: Tue, 04 May 2004 15:46:04 GMT Subject: Best IDE? References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> Message-ID: <0VOlc.1485$Nm3.13548612@news-text.cableinet.net> Thanks for the heads up "SM" wrote in message news:99230dbb.0405011406.7f37c033 at posting.google.com... > Hi, > Just to let you all know that there is a new version of SPE being > developped with a much faster class/index/todo browser (can be even > realtime!), wxPython 2.5 support, simultaneous view of source code, > you can choose between MDI or SDI both with tabs, better control of > calltips (only first paragraph or all doc) ... If you are curious, > you can download it from http://projects.blender.org/projects/spe/ The > windows XP version is already quite stable, for linux and mac os x, > I'm dependent of other users. > Stani > > hemanth_sethuram at yahoo.com (Hemanth P.S.) wrote in message news:<9be5e130.0404160049.257ce8e1 at posting.google.com>... > > If you are looking for an IDE only for Python development, take a look > > at SPE.(http://spe.pycs.net). It looks quite cool with PyCrust > > integrated. > > Here is the blurb from the site: > > """ > > Spe is a python IDE with wxGlade GUI designer, auto-indentation, auto > > completion, call tips, syntax coloring, syntax highlighting, class > > explorer, source index, auto todo list, sticky notes, integrated > > pycrust shell, python file browser, recent file browser, drag&drop, > > context help, ... Special is its blender support with a blender 3d > > object browser and its ability to run interactively inside blender. > > Spe is extensible with boa. > > """ > > > > --Hemanth > > > > Josiah Carlson wrote in message news:... > > > > This has prolly been asked 100 times - so please refrain from flaming if you can... > > > > > > > > What's the best MSwindows editor for python? I'm currently using PythonWin (ActiveState) at the moment, its a bit > > > > buggy - but not too bad. I mean, its got autocomplete & tips & help & autoindentaion (not always good tho). > > > > > > > > Thing is, I'm sure there is something better. Is there? > > > > > > Many people stick with the standard Python-included Idle. > > > > > > Others use their favored *nix editor on Windows (usually Emacs or VI(M)) > > > > > > Some have found they love SciTE. > > > > > > If you could get Eric3 running on Windows, it'd probably be /very/ nice. > > > > > > The editor component of Boa Constructor is pretty good (haven't used it > > > in a while), but is a bit sluggish. > > > > > > SPE (Stani's Python Editor) is also pretty good, though can be slow at > > > times, and uses MDI, which people usually love or hate. > > > > > > I use PyPE, find it to be a satisfactory replacement for Idle, and is > > > quite fast. I wrote it, which is why I place it at the bottom. > > > > > > > > > There are many other general text editors with some sort of Python > > > support, but I don't use any of them, so I'll not talk about them. > > > > > > - Josiah From segphault at sbcglobal.net Wed May 12 20:34:17 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Thu, 13 May 2004 00:34:17 GMT Subject: Finding the name of a class References: <40a2be14$0$3014$61fed72c@news.rcn.com> Message-ID: On Wed, 12 May 2004 20:10:07 -0400, Edward C. Jones wrote: > Is there a function or method that returns the name of a class or class > instance? > > class X(object): > pass > > X.amethod() or X().amethod() should return the string "X". > > X().__class__ returns "" which I could parse. Ugh. > > Or I could use module pyclbr. Ugh**2. I havent found any better way to do it: def classname(c): sl = `c`.split(' ')[0][1:].split('.') return len(sl) > 1 and sl[1] or sl[0] From paul at prescod.net Mon May 24 13:58:10 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 24 May 2004 10:58:10 -0700 Subject: Prothon vs. Python integers Message-ID: <40B237B2.4020608@prescod.net> I think that in this case, Python is demonstrably better than Prothon. C:\temp\prothon\Prothon>python ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print 2**65 36893488147419103232 >>> print 2**65 == (2**65 + 1) False C:\temp\prothon\Prothon>prothon Prothon 0.1 Interactive Console, Build 532, May 21 2004 (Ctrl-D to exit) >>> print 2** 65 3.68935e+19 >>> print 2**65 == (2**65 + 1) True If Prothon is a language designed for the next ten years then it should be tuned for correctness and ease of use, not for limitations of today's hardware. Paul Prescod From jerryg at softimage.com Mon May 10 20:38:50 2004 From: jerryg at softimage.com (Jerry Gamache) Date: Mon, 10 May 2004 20:38:50 -0400 Subject: Debuggin a ptyhon extension References: <409ab831_3@127.0.0.1> <5_Pmc.73807$j11.882729@weber.videotron.net> Message-ID: On Fri, 07 May 2004 21:06:05 +0200, Thomas Heller wrote: > - Grab the pywin32 source from CVS, and build it with distutils by > entering 'python setup_win32all.py build' in the command prompt. This > builds everything in release mode, which takes quite some time. Build > in debug mode with 'python setup_win32all.py build -g'. Now create a > windows installer by 'python setup_win32all.py bdist_wininst'. I found out that setting the following environment variables before building PyWin32 in release mode forces the generation of PDB files and allows some limited debugging in MSDEV. This will help you get call stacks and trace through the code, but variable values might become difficult to inspect due to code optimizations: set CL=/Zi set LINK=/DEBUG The install part of the code understands PDB files and will copy them to the proper locations when they are present. This is not necessary when building in debug mode. From peter at engcorp.com Tue May 18 10:43:21 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 May 2004 10:43:21 -0400 Subject: pyVideoIO source release In-Reply-To: <2gugfoF6p9rhU1@uni-berlin.de> References: <2gugfoF6p9rhU1@uni-berlin.de> Message-ID: Riccardo wrote: > Hello, after a long time I'm releasing my extension to read AVI files, > QuickTime and connect to WebCameras under win32. > I do not have much time to create a decent website by now, therefore I > released the sources and a binary for python 2.3 just to be prompted to > do more. > If somebody will find this useful I'll add any contribution I receive. > > the URL is: > > www.geocities.com/rtrocca/python > > Well, sorry for the lack of more information, > I'll add docs and other stuff in the future. You should probably add a copy of the LGPL to the source package... the source files say they are LGPL'ed, and suggest that one should contact the "Free Foundation, Inc." (sic) if a copy of the license is not included... -Peter From news at contrado.com.au Thu May 13 07:41:10 2004 From: news at contrado.com.au (gsm) Date: Thu, 13 May 2004 21:41:10 +1000 Subject: Real-time graphs References: Message-ID: <40a35edb$0$16606$5a62ac22@freenews.iinet.net.au> look at http://www.advsofteng.com/ ChartDirector is free and really good, best package that I know for graphing, also provides you with a base livbrary for designing your own, its engine is very small and design for the web etc, its output is exceptional in terms of font quality etc supports NET, ASP, COM, VB, JSP,Java, PHP, Perl, Python, C++ wrote in message news:mailman.463.1084375754.25742.python-list at python.org... > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? > > TIA > Stephen > From dmq at gain.com Thu May 13 16:54:01 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 13 May 2004 13:54:01 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> Message-ID: <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> I'm beginning to understand what you are saying. Thanks for hanging in there. On 12 May 2004 20:51:20 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:... >> On 10 May 2004 16:53:06 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> >David MacQuigg wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... >> >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> < snip topics we have finished > >> >> >You are not solving a problem; that's the problem. :) If there were a >> >real programming task then it would be more trivial to show why your >> >object model is broken. >> >> I could give you an example from IC Design, but for the course I >> teach, I chose to use a similar hierarchy based on something everyone >> would understand - a taxonomy of animals. Nothing in this example is >> something you wouldn't find in a real program to model an integrated >> circuit. Instead of animal names like Cat, we would have the names of >> cells in the hierarchy, names like bgref25a. Instead of a variable to >> count the number of animals at each level, we might have several >> variables to track the total current on each of several supply lines. >> Like the counts in the Animals.py hierarchy, we need the total current >> to each cell, including all of its subcells. > >As far as I understand it, this is fairly different; the way I would >implement it, each cell would be an instance, not a class. I would >have to look at some kind of code/spec to really know, though. Do you >have an example of a piece of software were you follow this approach? Using instances instead of classes is something I hadn't considered. I could add one line after each class to instantiate it. I'll have to play with this a bit, and see if I can come up with a *simple* program to do the same thing as Animals_2, but using instances. I don't yet have the code written for my circuit-design platform, but I can give you a spec that describes some of the needs I see. 1) We need to represent a hierarchy of cells, typically 5 to 10 levels deep. 2) Each cell has data associated with it. Some of this data is a cummulative total of similar data from all subcells -- total currents, total chip area, etc. 3) The data for each cell is unique, and it must be displayed in a format unique to that cell. 4) We need a simple function, show() that can be called for any cell or no cell at all (just knowing the cell type). This function should show the cell data and the data from all cells above it. In case no cells of a particular type have been added to the design, the cummulative data should just show a default value, like zero. In addition to these functional requirements, we need to make the program structure as simple as possible, to use as an introduction to OOP for design engineers who have no CIS background, but have learned Python up to the point where OOP is introduced. Robustness and generality are not prime requirements at this point, although introducing something like _private variables is OK, because it won't distract from the introduction. >> I'm sure there are other examples from other specialties. In >> accounting, I can imagine a hierarchy of accounts, with a total for >> each account including all of its subaccounts. Don't just assume that >> the problem isn't real because you haven't encountered it in your >> work. > >Sorry, but that's not how you would do an accountancy package in OO. >Again each account would be an instance, not a class, otherwise adding >a new account would require either code modification or metaclass >hacking. Instances scope down, and having a count of the sub-accounts >stored in an object would be OK in my book. Though you wouldn't need >to, since the container for the instances would do it for you. Seems like this is very much like the Animals example. We create an instance for each asset, but there is one Asset class which is not an instance. You can't transfer funds to the Asset class, only one of its accounts. The Asset class, like the Mammal class, keeps data that is representative of all instances of the class. >But even this isn't how you would organize an accountancy program. >You'd use a database. That would not work as an example introducing OOP. It would be like saying to the students -- You can't understand OOP, so we're not even going to try. Just learn this database program, and use it to solve whatever problems you may encounter. >> >> >> >> >If you can't take it below 70 pages and you only have 4 hours... maybe >> >it's not such a great idea to try this? I can't see your students >> >benefiting from what you're proposing to do, if you have so little >> >time. >> >> I think I could do it in 30 pages and 4 hours total ( lecture, lab, >> and homework ), but not if I need to cover the topics that both Mark >> Lutz and I consider important to basic OOP in the current version of >> Python. The 30 pages assumes the unification of methods and functions >> that I have proposed. >> > >70 -> 30 because of this? Really? I would also cut way back on the "motivational" parts, and a number of other things that fit well in the current presentation, but are not necessary in the presentation I have in mind. My 30 page estimate is based not on crossing out topics in Learning Python, but on looking at the 7 pages I have now, and guessing what more I need to add. One of the best books I've ever read on a complex subject is Introduction to Quantum Theory by David Park. The book is split into two parts: the theory, which is presented in a brief, straightforward, but unrushed manner; and the examples, which amplify and re-iterate what is in the theory section. The first time through, you need to spend a lot of time reading the examples along with the theory. Years later, you can quickly read just the theory section, and it is a real pleasure. I think I can present the "theory" of OOP in 7 pages, at a sensible pace, including everything I think will be needed to write most programs ( bound and unbound methods, lambdas, static methods, etc. ). http://ece.arizona.edu/~edatools/Python/Prototypes.doc Adding examples and exercisise may take another 25 pages. Adding supplementary topics ( multiple inheritance, method resolution order, some of the techniques you are showing to make classes more versatile and robust, etc. ) may take another 30 pages. >Anyway, I guess you know what you have time to do, it being your >course 'n all. :) > >> >> >> >> >> >> What data are we talking about? numMammals is specific to Mammal. >> >> genus is specific to Feline, but *inherited* by instances of a >> >> subclass like Cat. >> > >> >The numAnimals etc... data, which is stored in Animals but gets >> >arbitrarily altered by the actions of subclasses of Animal, and >> >therefore is not specific to animal; it doesn't represent the state of >> >the Animal class or of Animal objects, but of a whole bunch of >> >subclasses of Animal. >> >> The total current to an IC is the sum of the currents to all of its >> subcircuits. That current is a single number, for example, 35 >> microamps. It has a name "Iss". Iss is a characteristic of the IC >> which appears in data sheets, etc. It is a variable representing the >> state of the entire IC. It does not represent the state of any >> subcircuit in the IC, even though it gets "altered" whenever one of >> those subcircuit currents changes. > >So the IC is an instance which stores or accesses data about the >instances which it contains, i.e. circuit elements; not a class which >you sub-class to get subcircuit elements. I'm discussing classes and >class heirarchies, not instance heirarchies. I was also assuming a class hierarchy. The idea of a hierarchy of instances is new to me. I guess I'll need an example to know what you are talking about. >> Looks like this whole argument comes down to what we mean by the word >> "specific". Let's drop it and focus on the more interesting topics in >> this thread. > >From here, it looks like the problem is the difference between an >instance and a class? ??? >> >> >> >> These are normal programming errors that can occur in any program, no >> >> matter how well structured. I don't see how the specific structure of >> >> Animals.py encourages these errors. >> > >> >Imagine if your structure had been implemented as one of the basic >> >structures of, say, Java. That is, some static data in the Object >> >class stores state for all the subclasses of Object. Now, someone >> >coming along and innocently creating a class can break Object - >> >meaning that may break anything with a dependency on Object, which is >> >the entire system. So I write a nice GUI widget and bang! by some >> >bizzare twist it breaks my program somewhere else because of an error >> >in, say, the StringBuffer class. This is analagous to what you are >> >implementing here. >> >> I'll need an example to see how these general worries can affect the >> Animals_2 hierarchy. What I see is quite robust. I added a Feline >> class between Mammal and Cat, and I had to change only two lines in >> the Cat class. ( And I could avoid even that if I had used a "super" >> call instead of a direct call to the Mammal functions.) > >And if someone unfamiliar with the code neglects to call the >superclass initializer when they create a new animal, then the code >will break in unpredictable places. Not calling the superclass is a >common problem - but easily fixable, *providing* the effects show up >in the subclass, and not at some other random place in the heirarchy. Adding a call to a superclass __init__ is a common pattern in the examples I've seen. See the section "Calling Superclass Constructors" starting on page 321 in Learning Python, 2nd ed. We need to make a distinction between users and programmers in our expectations of what kind of errors they will make. Users only need to *read* a class definition and understand what it does. Programmers are the group that needs to remember to add a call to the superclass when they write a new class. I am a user of the Qt Toolkit, but I would not attempt to add a class to their existing hierarchy. Nor would I expect Trolltech to provide me with some kind of robust class-generating function that was guaranteed to generate an error-free class at any point in their hierarchy I might chose to insert it. >> >While errors are always going to happen, OOP calls on some conventions >> >to minimize them. The most absolutely vital of these is that it's >> >clear what can break what. Generally I should never be able to break >> >a subsystem by breaking it's wrapper; definitely I should never be >> >able to break a superclass by breaking it's subclass; and I >> >*certainly* shouldn't be able to break a part of the system by >> >changing something unconnected to it. The whole of OOP derives, more >> >or less directly, from these principles. Expressions like 'A is a >> >part/type of B' derive from this philosophy, not the other way around. >> >> Sounds good. >> >> >Your program breaks with this concept. It allows an event in Cat to >> >affect data in Mammal and in Animal, which also has knock-on effects >> >for every other subclass of these. Therefore it is bad object >> >oriented programming. >> >> We are modeling the real world here. When you add a lion to a zoo, >> you add one to the count of all animals. > >When you add a lion to a zoo, you add one entry in the lion table of >your database. When you want to know the number of animals in the >zoo, the database query counts the number of entries in all of the >animal tables. *Real* databases are built that way because of >experience; repetition of data invariably causes out-of-synch >problems. I think the database problem is different than our Animals example. With a database, you typically have many users directly changing the data over a long period of time when errors can accumulate. Maybe some user runs a "transaction" script to debit one account and credit another, but his line goes down before the second part completes. So it makes sense in this case to store only the primitive data, and accept the overhead of recalculating everything else from that data whenever it is needed. >I worked on a project a couple of years ago to port a legacy database >into MySQL, and it was made damned close to impossible by this sort of >thinking; how the heck do you port a database which has had it's >shortcomings patched over to the point where it depends on the >inconsistent results for it's output? :-\ > >> When you add 2 microamps to >> the core currents in a bandgap voltage reference, you add that same 2 >> microamps to the total supply current. >> > >Again, I'd be inclined to handle this problem at the instance level, >not the class level. > >> I'm no expert in OOP, but what I have seen so far is not near as clear >> in structure as the origninal Animals_2 example. >> > >When you have to troll through a 20K line program where the >functionality for a single subsystem is scattered through multiple >classes in a heirarchy, it puts a really different perspective on what >'clear structure' is. Likewise, when everything is modularized >explicitly and you can alter a complex system which you barely >understand to include completely new core functionality in an hour or >two of work. I would expect a Python programmer seeing the Animals_2 example for the first time, could add a class between Feline and Mammal by the end of an hour, and be quite confident that nothing was broken. I studied your example for two hours, and I still don't understand it well enough to make some basic changes. >> >It takes us back to the days before even structured programming, when >> >no-one ever had any idea what the effects of altering or adding a >> >piece of code would be. >> > >> >It is therefore not a good teaching example. :) >> >> I'll need to see something better before I abandon the curent example. >> The problem may be our expectations of OOP. I see classes as modeling >> the real world, including variables that are altered by changes in >> subclasses. You seem to have some computer science notion of what a >> class should be. I'm not saying its wrong, but unless it helps me >> solve my real-world problems, in a better way than what I am doing >> now, I won't use it. > >You're right, I don't give a damn whether classes model the real >world; what matters, in general order of preference, is: > >- Robustness >- Maintainability >- Programmer time >- Efficiency This is a good set of priorities for a production program. For teaching OOP, I would say clarity is the over-riding concern. >I will sell any theoretical principle to the salt mines for those. >'Classes-model-the-real-world' is an abstract theory, an evolutionary >holdover from when OO was the Next Big Thing in AI. If it leads you >to design a non-robust, hard to maintain system then, in my book, it >gets dropped. > >> I'm reminded of the criticism Linus Torvalds got when he first >> published Linux. The academic community thought it was the worst, >> most fundamentally flawed design they had ever seen. It did not fit >> some expectation they had that a "microkernel" architecture was the >> proper way to design an OS. Luckily, Mr. Torvalds was not dependent >> on their approval, and had the confidence to move ahead. > >I've been trying to explain why the pattern in your example will cause >bugs; you've been justifying it in terms of OOP metaphors. *shrug* The >comparison is clear enough to me... :) I find the "piece of machinery" metaphor to be helpful, but no big deal. Mostly, it re-inforces the idea of encapsulation, keeping the dirty details of how an alternator works inside the component, and presenting to the outside world, a simple interface: if you want more current at that output, put more voltage on this input. I'm not using metaphors to justify bad programming. I am just having trouble seeing how one program, side-by-side with another, is supposedly bad. >> >> >> I'm not sure what you mean by "side effects" here. The show() >> >> >> function at each level is completely independent of the show() >> >> >> function at another level. > >> >> > >> >> >But the inventory data isn't independent. It's affected by classes >> >> >somewhere else in the heirarchy. Worse, it's done implicitly. >> >> >> >> The "inventory data" actually consists of independent pieces of data >> >> from each class. ( numCats is a piece of inventory data from the Cat >> >> class.) I'm sorry I just can't follow this. >> >> >> > >> >numMammals OTOH is not just a piece of data from one class - it's a >> >piece of data stored in one class, but which stores data about events >> >in many different classes, all of which are outside it's scope. >> >> Exactly as we see in objects in the real world. > >Objects perhaps, but not classes. This seems to be the distinction >which is driving this whole problem; you are regarding extending a >class as if it were adding a member to an instance. ??? >> >That's the way it has to be, if you want to write it like that. >> >However there is nothing to say that a given problem must use a >> >certain class structure. If you come up with a solution like this >> >then it's near-guaranteed that there was something badly wrong with >> >the way you modelled the domain. Either the program shouldn't need to >> >know the number of instances which ever existed of subclasses of >> >mammal or else your class structure is wrong. >> >> Trust me, the need is real. We just need to find the optimum example >> to show how Python solves the problem. > >Mail me some code where you need to do this in a real system, and I'll >show you how to refactor it. :) Let's see if we can get the Animals_2 example right, based on the requirements I stated above. It will be a few months before I have my design platform ready, and it will be far more difficult to discuss basic ideas in the context of a big system. I think Animals_2.py has one of everything I will be using. >> In my work as a software product engineer, I've learned to deal with >> two very common criticisms. 1) The user doesn't need to do that. 2) >> The user is an idiot for not understanding our wonderful methodology. >> These are generally irrefutable arguments that can only be trumped by >> a customer with a big checkbook. >> >> I generally don't engage in these >> arguments, but on one occasion, I couldn't resist. I was trying to >> show an expert how a complicated feature could be done much more >> easily with simpler functions we already had in our program. >> >> His argument was basically -- every expert in this company disagrees >> with you, and you're an idiot for not understanding how our new >> feature works. I replied that I was the one who wrote the User Guide >> on that feature. He started to say something, but it was only a >> fragment of a word, and it kind of fell on the table and died. There >> was a few seconds of silence, while he tried to figure out if he could >> call me a liar. I just looked right at him without blinking. >> >> Forget what you have learned in books. Think of a real zoo. Think >> how you would write the simplest possible program to do what Animals_2 >> does -- keep track of all the different classes of animals, and >> display the characteristics of any animal or class, including >> characteristics that are shared by all animals in a larger grouping. > >What you're asking is how would I implement something simply, >providing that I have to implement it with method X. Give me a >functional spec - what the system needs to do from the user point of >view - and I'll tell you how I would do it. See above for functional spec. >In the case of a real zoo, I can pretty much guarantee that it would >begin > >>>>import PySQLdb Don't forget. My basic purpose with the Animals_2 example is to teach OOP, not the use of a particular database. >> >And, as general rule, you should think carefully before using classes >> >to store data; that's typically what objects are for. I used static >> >data in programs quite a lot before I realised that it too-often bit >> >me later on. >> >> Classes *are* objects. > >In Python, classes are 'first class objects' - you can pass them >around as references, alter them and so on. That's in the same way as >functions are 'first class objects'. That's a different and older >piece of terminology than the term 'object' in OOP, which unhappily >coincides with it. > >Wherever I can, I'll convert the discussion over to use the term >instance if you're more comfortable with the terminology, but in the >canonical definition a class is not an object. Objects get created >from classes, and the term is equivalent to instance for practical >purposes (though you get into occasional pieces of terminology like >'object instance' where it's just convenient to not have to say >'object object', and 'object variable' would get kinda confusing too.) > Check any basic text on OOP for confirmation, say >http://java.sun.com/docs/books/tutorial/java/concepts/ I agree the terminology is confusing, and I try to use "object" only in the most generic sense. "Class" and "instance", as Python uses them are OK with me. The question, as I understand it, is whether classes should hold just methods, or both methods and data. Again, the examples I have seen show plenty of data being stored as attributes of classes. See Learning Python, 2nd ed. p. 317. The general form of the class statement according to Mark Lutz is: class (superclass, ...): # Assign to name. data = value # Shared class data def method(self, ...): # Methods self.member = value # Per-instance data Methods are more prevalent in the examples than data, but as far as I know, there is no warning to the effect: This is possible, but not good practice. >> I think you mean instances. I make a >> distinction between class variables and instance variables, depending >> on whether the variable is different from one instance to another. >> Every instance has a different cat.name, but all cats share the genus >> "feline". In fact, they share that genus with all other members of >> the Feline class. That is why I moved it from Cat to Feline as soon >> as our example was big enough to include a Feline class. >> >> > >> >OK: start with the basics. We need iterative counting data about the >> >individual elements of the heirarchy. >> > >> >The first thing is that we need to factor out the print statements. >> >Your back-end data manipulation modules should never have UI elements >> >in them. So, whatever form the data manipulation comes in, it should >> >be abstract. >> >> You are adding requirements to what I already have. OK if it doesn't >> slow the introductory presentation too much. >> >> >Secondly, we want to keep the data stored in each class local to that >> >class. So, Mammal can store the number of Mammals, if that turns out >> >to be a good solution, but not the number of it's subclasses. OTOH we >> >could remove the data from the classes altogether. >> >> Think of a real zoo. If you ask the zookeeper how many animals he >> has, will he tell you only the number that are animals, but are not >> also lions or tigers or any other species? That number would be zero. >> > >In a real zoo, it would not require brain-surgery on the zookeeper to >introduce a new type of animal. :) Adding the Feline class to the existing hierarchy was very easy. >Also, as I say, in a real zoo you would use a database for this task. >Any good database design person would balk at the idea of even storing >the number of a particular animal as an explicit variable in the >database. Think about that. Just so we can move on, I will accept your assertion that a truly bulletproof zoo program would use a database. We still need an example that doesn't use a database, or anything other than Python's basic functionality, to teach students about OOP. >> I really do want numMammals to display the total number of all >> mammals, whether or not they are a member of some other class in >> addition to Mammal. >> >> If I were to guess at your objection to this, I would assume you are >> worried that the different counters will get "out-of-sync", if for >> example, someone directly changes one of these variables, rather than >> calling the appropriate functions to make a synchronized change. >> >> My answer to that is to make the counter variables private. I've >> added a leading underscore to those names. numMammals is now >> _numMammals. >> > >OOS due to an explicit variable alteration is pretty much the >worst-case scenario, yes. It would require quite an incompetent coder >to do it, but it could still easily happen. The more likely problem >is the failure to call the superclass constructor - which may even be >harder to debug, since at least in the other case you can run through >the program in a debugger and find where the variable is being >changed, or just grep numMammals. > >Your faith in private variables is touching. :) The Python policy on private variables, which I agree with, is that we don't need to prevent deliberate action, just make sure the user understands a variable is private, not to be altered except by the provided functions. >> >Thirdly, it would probably be nice if we had the ability to implement >> >the whole thing in multiple independant systems. Currently the design >> >only allows one of "whatever-we're-doing" at a time, which is almost >> >certainly bad. >> >> ??? > >Supposing I want to store data for two zoos. If the data on the >number of animals is stored at class-level, then I literally can't do >that without closing down the program and opening up a different data >set. Munging the code to have numMammals_at_zoo_1 isn't a good >solution either. :) OK, now I understand. Let's make "Multi_Zoo.py" an example later in the chapter, not part of the introduction. >> >After a bit of brainstorming this is what I came up with. It's not a >> >specific solution to your problem; instead it's a general one. The >> >following class may be sub-classed and an entire class-heirarchy can >> >be placed inside it. It will then generate automatically the code to >> >keep a track of and count the elements of the class heirarchy, >> >returning the data you want at a method call. >> > >> >This is done with a standard OO tool, the Decorator pattern, but >> >ramped up with the awesome power of the Python class system. :) >> >> My non-CIS students are not familiar with the Decorator pattern. I >> fear that will make this example incomprehesible to them. >> >> > >> >The above code is 51 lines with about 10 lines of comments. For a >> >project of any size, this is a heck of an investment; I believe it >> >would take a fairly determined idiot to break the system, and *most >> >importantly*, they would be able to trace back the cause from the >> >effect fairly easily. >> >> This is an impressive bit of coding, but I can assure you, as an >> introduction to OOP, it will blow away any non-CIS student. It may >> also be difficult to modify, for example, if we want to do what >> Animals_2 does, and provide a custom display of characteristics for >> each class. >> > >Hmm, do you mean the talk method or the formatting of the inventory >data? Because of the rather convoluted scoping rules you have to call >say animal_farm..talk(self) to access the superclass >from within the talk method, which is a minor annoyance I guess. > >To format the show method differently for each class would be a little >more awkward, though you're not doing that at the moment. I am intending to do exactly that. Because the example is short, you are tempted to say I really don't need different show functions for each class. I can add more unique items to each class if I must, making it look more like a "real program", or you can accept the requirement that the small differences in the example display are important. How about something like this: We put all data and formatting unique to each class within that class, but we don't use the trick of each class calling its parent to generate a complete display. The sequencing of displays could then be done by some generic function, calling in sequence the unique display functions from each class. >> One possibility is to make this an Animals_3 example. Animals_1 was a >> simple two-class structure. It served to introduce instance >> variables, and some basic concepts like inheritance. When we moved to >> Animals_2, we pointed out the limitations of Animals_1, like not >> having enough classes to put variables like 'genus' where they really >> belong. >> >> Maybe we should go one more step, and make this a third example. We >> can point out the limitations of Animals_2 in the introduction to >> Animals_3. I can see the benefit of moving the print statements to >> the top level. This is needed if we ever want to make the classes in >> Animals_2 work in some kind of framework with other classes. The >> show() functions in Animals_2 could be modified to return a list of >> strings instead of printing directly to the console. >> >> I've posted your program as Solution 3 to the exercise at >> http://ece.arizona.edu/~edatools/Python/Exercises/ Could you give us >> a brief description of the advantages and disadvantages compared to >> the original. I'm not able to do that, because I'm having difficulty >> restating what you have said above in terms that students will >> understand. I cannot, for example, explain why your solution is more >> robust. >> > >Advantages: > Robustness; no requirement for a programmer to keep a count of > instances or update the count of the super class by calling it's > initializer. This minimises the chance of programmer error. > Avoids replication of data, eliminating OOS errors. > > Maintainability; all of the code for counting is contained in a > single module, so modifications will not require changes to >multiple > similar pieces of code throughout the class structure. > > Agility; we can maintain more than one zoo in a program by >creating > new instances of of the animal_farm class. Class level data would > limit us to data on a single zoo system. > > Generality; the Collection class can be used for any problem of > this type. This is excellent. I will add it to my web-page. >> >Admittedly the solution is on the complicated side, though perhaps >> >someone with more experience than me could simplify things. >> >Unfortunately, a certain amount of complexity is just a reflection of >> >the fact that your demands strain the OO paradigm right to it's limit. >> > You could possibly implement the same thing in Java with a Factory >> >pattern, and perhaps the reflection API. >> >> Your vast experience may be blinding you to the problems non-CIS >> students will have with these more complex solutions. I may be >> pushing a paradigm to some limit, but these are real-world problems >> that should be easily solved with a good OOP language. > >This isn't something I'd show a programming beginner either! I'd >choose a different way of demonstrating a class heirarchy, myself. OK, I'm convinced we need a third example. Animals_2 will remain part of the introduction, and our next example Animals_3 will be our bullet-proof, production-quality, what-you-better-do-if-someone-is-paying-you, final solution. I would still like to see some simplification of Animals_JM.py Although clarity is not specifically on your list of requirements, I think it does impact maintainability and programmer time. Meanwhile, I'll try doing something with your "instances instead of classes" suggestion. -- Dave From simoninusa2001 at yahoo.co.uk Sun May 9 20:20:22 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 9 May 2004 17:20:22 -0700 Subject: Python documentation in Qt Assistant? References: Message-ID: <30260531.0405091620.2016ed5@posting.google.com> Jarek Zgoda wrote in message news:... > Has anyone tried to integrate Python documentation with Qt Assistant? I > know I can view Python documentation with Eric3 help viewer, but I would > like to use Assistant's full-text searching capability. The Kompany's BlackAdder comes with a "pythonised" QtAssistant. From mcfletch at rogers.com Wed May 19 13:11:38 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 19 May 2004 13:11:38 -0400 Subject: what does this mean? In-Reply-To: References: Message-ID: <40AB954A.50509@rogers.com> mr. ice wrote: >I am new to python, The following statement is in the beginning of >class definition in a python scripts, what does it mean? Help? >class %(class_)s_W : public XMsg_W >{ > > You will likely notice that there are "" or '' marks around the text you're reading there. It looks a lot like a string template that someone is using to create C++ code. A string like this "Hello %(name)s_xyz" gets expanded in Python like so: name = 'this' value = "Hello %(name)s_xyz" % locals() yielding: value == "Hello this_xyz" So whoever coded the module is likely trying to auto-generate some C++ code using Python string substitution. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From bfchen at ust.hk Thu May 6 00:21:02 2004 From: bfchen at ust.hk (CHEN Benfeng) Date: Thu, 6 May 2004 12:21:02 +0800 Subject: Is IronPython open source or not ? Message-ID: I am interested in IronPython and want to have a study on the source code. But I cannot find any download link in the homepage of IronPython. -- Best Regards From usenet_spam at janc.invalid Sun May 23 14:36:52 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 23 May 2004 18:36:52 GMT Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> Message-ID: Manlio Perillo schreef: > I'm using the Cookie module (on the client side). Do you know the ClientCookie module? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From andrew-pythonlist at puzzling.org Wed May 5 22:31:15 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 6 May 2004 12:31:15 +1000 Subject: Python documentation: How about structured documentation? Looking for comments/suggestions In-Reply-To: References: Message-ID: <20040506023115.GB24284@frobozz> On Thu, May 06, 2004 at 02:12:26AM +0000, Kenneth McDonald wrote: > This seems to tie in with a few other things that have been posted > recently... > > One of the things I'm currently working on is something I call pk, > a layer on top of Tkinter which gives a much more object-oriented > inteface to Tk. This is relatively complex, and one of the things > I'm missing is the lack of good doctools support in Python. > Something like Javadoc would be nice. Something like d'oxygen > would be even nicer. Have you seen epydoc ? -Andrew. From tjreedy at udel.edu Wed May 19 18:54:24 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 May 2004 18:54:24 -0400 Subject: Help with large data set and fatal python error (pysqlite) References: Message-ID: "Vineet Jain" wrote in message news:KPENJIMKHJPNKOLFIHBNKEPNCJAA.vineet at eswap.com... > I've been able to recreate the problem with the following code segment. It > seems that the problem comes when you have multple db files open at the same > time. In my application I have many database files open at the same time. > I'm not using threads so all access to the db files are done sequenetially. > > At the end of the program I get the following error: > > Fatal Python error: deallocating None > > This application has requested the Runtime to terminate it in an unusual > way. > Please contact the application's support team for more information. Have you done so? In this case, the 'application' is, it would seem, sqlite. > If I change the numInnerLoop to 5, 10, 20, or 30 it works however anything > over 35 gives the above error. In my actual application, when run for a > larger set, the error can come in the middle of the program and is causing > me a lot of grief. Do the docs for sqlite specify max open connections? If not, maybe send them your example. If so, ask if limit can be raised. In the meanwhile, stay under it. Terry J. Reedy From acrobert-at-ucalgary-dot-ca at ucalgary.ca Sat May 1 12:22:07 2004 From: acrobert-at-ucalgary-dot-ca at ucalgary.ca (Anthony Roberts) Date: Sat, 01 May 2004 16:22:07 GMT Subject: quotes at the edges of a triple quote string... In-Reply-To: <5eednTy2_ZjVUA7dRVn-uw@powergate.ca> References: <5eednTy2_ZjVUA7dRVn-uw@powergate.ca> Message-ID: > Can't you still use a triple-quoted string, but escape the > last quote? > > >>> """test\"""" > 'test"' Yes... yes I can. I can also use the other quotetation marks. I realized this just after I posted. >>> '''test"''' 'test"' Either way works. Thank you for the quick response. :) From godoy at ieee.org Thu May 13 15:38:01 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 13 May 2004 16:38:01 -0300 Subject: Help with Distutils References: Message-ID: On Qui 13 Mai 2004 15:39, Johan Svedberg wrote: > Well, the reason is that I've told setup.py to install a bunch of > templates in /share/myapp/templates/ and I want to make sure > that myapp can find these no matter what is. I see somebody suggested that you use __file__, from the module. Another option --- I'm using it --- is to have a config file and have distutils to call a postinstall script (requires Python 2.3+) to update the directory in such a config file. You can parse it with ConfigParser in your application. It also adds an interesting way of putting things in different places and still having them to work as expected :-) -- Godoy. From juha.haataja at csc.no-spam.fi Tue May 25 02:05:53 2004 From: juha.haataja at csc.no-spam.fi (Juha Haataja) Date: Tue, 25 May 2004 09:05:53 +0300 Subject: Solving the Einstein's Riddle in Python References: Message-ID: In article , Christos "TZOTZIOY" Georgiou wrote: >> Perhaps you would like to take a look at my take on that at > http://www.sil-tec.gr/~tzot/python/ (check for the logic_puzzle.py). It > seems that it's slower than your version, but it's generic (ie you can > describe similar combinatorial puzzles with an easy custom language). I > have a couple of links in that page for the text files... Thanks for this pointer. I did try googling for Python code for solving this problem, but for some reason missed your site. Your solution is really nice, a general way of coding the problem in Python. - JuHa PS. I added some documentation and little tweaks to my Python code at http://www.csc.fi/oppaat/f95/python/talot_oo.py From dmq at gain.com Sun May 9 19:18:53 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 09 May 2004 16:18:53 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> Message-ID: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:<4a9o90pbu122npgf4m2hrgg04g2j0ic6ka at 4ax.com>... >> On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: >> Also, if you are calling >> a function that has an instance variable ( .length ) and no instance >> has been set by a prior binding, you would need to set __self__ >> manually. >> __self__ = foo; print FooLen() > >???!!!??? > >This is what I was talking about in my first post, global variables >which change depending on where you are in the code... as I understand >what you're saying, __self__ will have to be set, then reset when a >method is called from within a method and the exits. And __self__ >could presumably be changed halfway through a method, too. I'm sorry, >I don't see this as being more explicit or simpler. The setting of __self__ happens automatically, just like the setting of the first argument in a call from an instance. The user doesn't have to worry about it. In fact, I can't think of a circumstance where the user would need to explicitly set __self__. Maybe some diagnostic code, in which case having available a system variable like __self__ is a plus. You can, without any loss of functionality in a normal program, never mention __self__ in an introductory course. The user doesn't need to know what it is called. My preference is to give it a name and highlight it with double underscores. To me that makes the discussion more concrete and explicit, and builds on concepts already understood. Don't forget, the students already understand global variables at this point in the course. The "magic" of setting a particular global variable to an instance is about the same as the magic of inserting that instance as a first argument in a function call. The problem in either syntax is not the magic of setting 'self' or '__self__'. >> >A method in a class in Python is just like a global function; for a >> >global function to operate on an object, it must take it as an >> >argument. The prototype syntax would appear to break the above >> >example. >> >> Global functions have no instance variables, so there is no need for a >> special first argument. A Python method requires a special first >> argument (even if it is not used). > >But the first argument isn't terribly 'special'; it tells the method >what it's working on, just like any other argument. It's only >'special' characteristic is that there's some syntactic sugar to >convert foo.getLength() into Foo.getLength(foo). The specialness of the first argument isn't much, I agree, but it is enough to make the calling sequence different from a normal function or a static method. It is these differences that the new syntax gets rid of, thereby enabling the unification of all methods and functions, and simplifying the presentation of OOP. Methods in the new syntax are identical to functions (which the students already understand), except for the presence of instance variables. Instance variables are the one fundamental difference between functions and methods, and one that we wish to focus our entire attention on in the presentation. Any new and unnecessary syntactic clutter is a distraction, particularly if the new syntax is used in some cases (normal methods) but not others (static methods). >> >> The difference in the proposed syntax is that it doesn't need the >> >> staticmethod wrapper to tell the interpreter -- don't expect a special >> >> first argument. In the new syntax all functions/methods will have the >> >> same calling sequence. >> > >> >If a method doesn't operate on the data from an object then as a rule >> >it should be global. There are exceptions, but they generally don't >> >occur in Python so much as a in 'true oo' language like Java. >> >> The placement of a function at the module level or in a class should >> be determined by the nature of the function, not any syntax problems. >> If the function has characteristics unique to a class, it ought to be >> included with that class. The Mammal.show() function, for example, >> provides a display of characteristics unique to mammals, so we put it >> in class Mammal. We could have written a general-purpose Inventory() >> function to recursively walk an arbitrary class hierarchy and print >> the number of instances of each class. That general function would be >> best placed at the global level, outside of any one class. >> > >Mammal.show() shows characteristics to do with Mammals, *but not >specifically Mammal*. There really is a difference between a class >and it's subclasses. The Mammal.show() function *is* specific to Mammal. I think what you are saying is that calling Mammal.show() results in a display of characteristics of both Mammal and its ancestor Animal. That is a requirement of the problem we are solving, not a result of bad programming. We want to see *all* the characteristics of Mammal, including those it inherited from Animal. Leave out the call to Animal.show() if you don't want to also see the ancestor's data. >The general-purpose inventory solution would be a better solution. It >doesn't require repetition, it's hard (impossible?) to break and it's >generic, allowing it to be used beyond this single class heirarchy. > >If the inventory function would be best placed outside a class, why do >you think it's a good idea to put something with exactly the same >functionality inside your classes? The proposed Inventory() function is a general function that *would* be appropriate outside a class. The exising class-specific functions like Mammal.show() are unique to each class. I tried to make that clear in a short example by giving each data item a different text label. I've now added some unique data to the example just so we can get past this stumbling block. A real program would have a multi-line display for each class, and there would be *no way* you could come up with some general function to produce that display for any class. >> Learning Python, 2nd ed. by Mark Lutz and David Ascher is generally >> considered the best introductory text on Python. 96 pages on OOP. >> > >Books are always kind of strange, because a book must have a certain >number of pages and cover a certain range of content at a certain >technical level. For the level and range of the ORA Learning books, >that is going to mean a bit of padding for a simple language like >Python. If I see Learning Python in a bookshop then I'll take a look, >though. > >Regardless, I stand by what I said before - students generally will >not read 70 pages on a single topic, especially when it's a relatively >minor part of the course. Learning Python, 2nd ed. would be appropriate for a one-semester course. My problem is that I have only a fraction of a semester in a circuit-design course. So I don't cover OOP at all. I would include OOP if I could do it with four more hours. Currently Python is a little over the top. I don't think it is a problem with Lutz's book. He covers what he needs to, and at an appropriate pace. >> >Learning to program is about 5% how to do something, and 95% when and >> >why you should do it. You seem to be focusing almost exclusively on >> >how, which I suspect is why we're all so upset :) you get that way >> >when you have to fix the code which eventually results. >> >> The OOP presentations I've seen that focus as much as 50% on *why* >> generally leave me bored and frustrated. I feel like screaming -- >> Stop talking about car parts and show me some nice code examples. If >> it's useful, I'm motivated. Good style is a separate issue, also best >> taught with good examples (and some bad for contrast). >> > >I'm not talking about car parts. I'm talking about explaining >modularity, complexity, side-effects, classes as data structures etc. These are concepts that design engineers understand very well. I wouldn't spend any time teaching them about modularity, but I would point out how different program structures facilitate modular design, and how syntax can sometimes restrict your ability to modularize as you see fit. Case in point: The need for static methods to put the show() functions where we want them. >(It's hilarious to see what happens when people get taught by car-part >style metaphors; they take them completely literally. I've seen >someone writing the classic vending machine example write a 'Can' >class, subclass it to get 'CokeCan', 'PepsiCan'... and then create ten >of each to represent the machines' stock. That was after three years >of university, too...) Oh ... don't get me started on academia. :>) >> >OK: "The whole idea of having these structures in any program is >> >wrong." >> > >> >Firstly, the program uses a class hierarchy as a data structure. That >> >isn't what class heirarchies are designed for, and not how they should >> >be used IMO. But it's what any bright student will pick up from the >> >example. >> >> The classes contain both data and functions. The data is specific to >> each class. I even show an example of where the two-class first >> example forced us to put some data at an inappropriate level, but with >> a four class hierarchy, we can put each data item right where it >> belongs. >> > >The data is not specific to the class. It's specific to the class and >it's subclasses. Subclasses should be dependent on the superclass, >and generally not the other way around. What data are we talking about? numMammals is specific to Mammal. genus is specific to Feline, but *inherited* by instances of a subclass like Cat. >> Nothing in the Bovine class can affect anything in a Cat. Feline and >> Bovine are independent branches below Mammal. Adding a Mouse class >> anywhere other than in the chain Cat - Feline - Mammal - Animal cannot >> affect Cat. Could you give a specific example? >> > >Say someone adds a mouse class but doesn't call the constructor for >Mammal. The data produced by mammal and therefore cat is now >incorrect, as instances of mouse are not included in your count. In a >real example, anything might be hanging on that variable - so e.g. >someone adds some mouse instances and the program crashes with an >array index out of bounds (or whatever the Pythonic equivalent is :) ) >, or maybe we just get bad user output. This type of behaviour is >damn-near impossible to debug in a complex program, because you didn't >change anything which could have caused it. It's caused by what you >didn't do. These are normal programming errors that can occur in any program, no matter how well structured. I don't see how the specific structure of Animals.py encourages these errors. >> I'm not sure what you mean by "side effects" here. The show() >> function at each level is completely independent of the show() >> function at another level. > > >But the inventory data isn't independent. It's affected by classes >somewhere else in the heirarchy. Worse, it's done implicitly. The "inventory data" actually consists of independent pieces of data from each class. ( numCats is a piece of inventory data from the Cat class.) I'm sorry I just can't follow this. >> Chaining them together results in a >> sequence of calls, and a sequence of outputs that is exactly what we >> want. The nice thing about separating the total "show" functionality >> into parts specific to each class is that when we add a class in the >> middle, as I did with Feline, inserted between Mammal and Cat, it is >> real easy to change the Cat class to accomodate the insertion. >> >> Python has a 'super' function to facilitate this kind of chaining. >> Michele Simionato's 'prototype.py' module makes 'super' even easier to >> use. Instead of having Cat.show() call Mammal.show() I can now just >> say super.show() and it will automatically call the show() function >> from whatever class is the current parent. Then when I add a Feline >> class between Mammal and Cat, I don't even need to change the >> internals of Cat. > >That's fine - providing you're not using a class heirarchy to store >data. It's not the act of calling a method in a super-class which is >a bad idea, it's the way you are making *the numbers outputted* from >cat dependent of actions taken *or not taken* in another class >*completely outside cat's scope*. Seems like this is the way it has to be if you want to increment the counts for Cat and all its ancestors whenever you create a new instance of Cat. Again, I'm not understanding the problem you are seeing. You seem to be saying there should be only methods, not data, stored in each class. >> >> What I'm looking for is not clever re-structuring, but just a >> >> straightforward translation, and some comments along the way -- oh >> >> yes, that is a little awkward having to use a staticmethod here. Wow, >> >> you mean staticmethods aren't fundamentally necessary, just a bandaid >> >> to make up for Python's deficiencies? That was my reaction when I >> >> first saw Prothon. >> > >> >Static methods are more like a band-aid to make up for the >> >deficiencies of OOP. Python isn't a pure OO language, and doesn't >> >suffer the need for them badly. >> >> In one syntax we need special "static methods" to handle calls where a >> specific instance is not available, or not appropriate. In another >> syntax we can do the same thing with one universal function form. To try and get to the bottom of this, I re-wrote the Animals.py example, following what I think are your recommendations on moving the static methods to module-level functions. I did not move the data out of the classes, because that makes no sense to me at all. Take a look at http://ece.arizona.edu/~edatools/Python/Exercises/ and let me know if Animals_2b.py is what you had in mind. If not, can you edit it to show me what you mean? -- Dave From eurleif at ecritters.biz Tue May 18 01:21:45 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 18 May 2004 05:21:45 GMT Subject: "Extracting" a dictionary In-Reply-To: References: Message-ID: Heiko Wundram wrote: > Am Montag, 17. Mai 2004 21:34 schrieb Leif K-Brooks: > >> >>> locals().update(vars) > > From the documentation: > > """ > locals() > > Update and return a dictionary representing the current local symbol table. > Warning: The contents of this dictionary should not be modified; changes may > not affect the values of local variables used by the interpreter. > """ Thanks for pointing that out, I was a bit lazy with TFM. Please ignore my advice. From theller at python.net Wed May 5 12:20:35 2004 From: theller at python.net (Thomas Heller) Date: Wed, 05 May 2004 18:20:35 +0200 Subject: py2exe excluding a module, and import it during runtime, how? References: <39d94318.0405050750.633872eb@posting.google.com> Message-ID: <3c6ej164.fsf@python.net> satya at ttck.keio.ac.jp (Satya Nanda Vel Arjunan) writes: > Hi, I think there must be a simple solution for this problem, but I > couldn't find any example of this problem when I searched for it. I am > using py2exe-0.5.0. I would like to make a simple script, test.py into > an exe file, test.exe. In test.py I import a custom module called emc: [...] > I would like to exclude the emc module when creating the exe file. To > do this I used the following setup.py: [...] > When I run the test.exe I get the following error: > ImportError: No module named emc > > I have tried putting the module emc.py in the same directory as > test.exe and but it could not load it. So far I have only been > successful if I include emc.py inside the library.zip file, which I do > not want to do. How do we import a module only during runtime if we > exclude it when creating the exe file? I need this feature because > some modules are not readily available during the creation of the exe > file. Thank you for any pointers. This can be done, and I do it regularly. You need to add the directory where your emc.py module is to sys.path, by default the py2exe'd executables only have the ziparchive on their sys.path. See the 'simple' sample to experiment with this, and to get some ideas. Also see this entry in the wiki: Thomas From mwh at python.net Mon May 17 15:32:54 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 17 May 2004 19:32:54 GMT Subject: This program makes Python segfault - no other does References: Message-ID: Juho Saarikko writes: > On Mon, 17 May 2004 17:54:32 +0000, Michael Hudson wrote: > > > Juho Saarikko writes: > >> #0 0x400c4c1b in free () from /lib/libc.so.6 > >> #1 0x400c4aa3 in free () from /lib/libc.so.6 > >> #2 0x0807ff2e in PyObject_Free (p=0x81d7240) at Objects/obmalloc.c:774 > >> #3 0x0807f5a6 in PyMem_Free (p=0x81d7240) at Objects/object.c:2111 > >> #4 0x4023a2d4 in unQuoteBytea (sin=0x81dd2ec ">nemo wrote:") at libpqmodule.c:417 > > > > Oh look, this is clearly inside the libpq extension module! What > > evidence do you have for a bug in Python itself? > > The function unQuoteBytea allocates memory with PyMem_Malloc, and frees it > with PyMem_Free. The segfault happens at freeing the memory (as the > backtrace shows). It seems to me that if Python's memory management > routines fail to free an object they've allocated, it must be a bug in > Python. Um. Almost certainly PyMem_Malloc winds up just calling malloc(), and you can see above that PyMem_Free is winding up calling free(). Is this a debug build of Python? You might want to try one of them. > That or some other bug corrupts memory structures, in which case > it's almost impossible to track down. At this point I'm considering > either switching to a different database plugin, or to Java. > > I tried the new Python version (3.3.4c1) and got the exact same behaviour. > Aarrgghh. > > Here, I'll attach the unQuoteBytea function, it's a short one. Maybe you > can find some problem in it I couldn't: > > > PyObject *unQuoteBytea(char *sin) > { > int i, j, slen, byte; > char *sout; > PyObject *result; > > slen = strlen(sin); > sout = (char *)PyMem_Malloc(slen); > if (sout == (char *)NULL) > return PyErr_NoMemory(); > > for (i = j = 0; i < slen;) > { > switch (sin[i]) > { > case '\\': > i++; > if (sin[i] == '\\') > sout[j++] = sin[i++]; > else > { > if ((!isdigit(sin[i])) || > (!isdigit(sin[i+1])) || > (!isdigit(sin[i+2]))) > goto unquote_error; > > byte = VAL(sin[i++]); > byte = (byte << 3) + VAL(sin[i++]); > sout[j++] = (byte << 3) + VAL(sin[i++]); > } > break; > > default: > sout[j++] = sin[i++]; > } > } > > sout[j] = (char)0; I think j can equal slen at this point? Truth in advertising: I googled for libpqmodule.c, got (as I hoped) the CVS logs from SF, noticed that the most recent log entry said: 09NOV2003 bga Fixed a buffer overrun error in libPQquoteBytea based on a fix by James Matthew Farrow. [Bug #838317]. , that the date of the this log was after the most recent release of pypgsql and then looked at the diff. Maybe you should try building pypgsql from CVS... Cheers, mwh -- If you're talking "useful", I'm not your bot. -- Tim Peters, 08 Nov 2001 From heikowu at ceosg.de Wed May 5 15:53:13 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Wed, 5 May 2004 21:53:13 +0200 Subject: Improvement ? In-Reply-To: References: Message-ID: <200405052153.13581.heikowu@ceosg.de> Am Mittwoch, 5. Mai 2004 21:12 schrieb Jean-Marc Ranger: > But is this the expected behavior ? I personaly would prefer to see > this operation succeed - and don't like the idea of writing a > workaround :) What you could do is pass the final directory name to os.path.abspath before you create it. abspath will filter out the unneccesary reference to "." before returning the name. HTH! Heiko. From dmq at gain.com Tue May 25 06:50:08 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 03:50:08 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: On 25 May 2004 10:30:03 GMT, Antoon Pardon wrote: >Op 2004-05-25, David MacQuigg schreef : >> On 25 May 2004 07:39:49 GMT, Antoon Pardon >> wrote: >>> >>>Well one possible view is that methods are just functions. The >>>difference being that it is not exactly the function as it >>>is defined in the class but as related function. Now I don't >>>know if trying to explain methods from this point of view >>>would be easier for students to understand and it may cause >>>confusions of its own. But I think this approach deserves >>>more attention you seem willing to give it. >> >> I don't feel I can make much improvement on Learning Python, 2nd ed. >> I think this is the same approach that you are talking about - >> functions first, then methods, one variation at a time. > >I don't think so. The apprach I'm thinking of would >be about the following. > >1) functions >2) bare classes (no methods) >3) higher order functions >4) show how higher order functions > can result in method like beheviour >5) methods and show the connection with > higher order functions. I've started a section on my webpage at http://ece.arizona.edu/~edatools/Python/Examples for those that feel we need a completely different approach to introducing OOP. If you put together some examples of what you mean by the above, I'll add them to my webpage. -- Dave From marco.terzuoli at libero.it Wed May 19 15:06:59 2004 From: marco.terzuoli at libero.it (Marco Terzuoli) Date: Wed, 19 May 2004 19:06:59 GMT Subject: BANALE ma utile References: Message-ID: Armand Federico - INFO wrote: > Devo scoprire se un elemento esiste in una lista > > Se metto confini.index(nomeelemento) mi da errore nel caso non esista e mi > da l'indice nel caso esista > > Il mio problema ?: > se l'elemento non esiste, devo fare la stessa cosa con un altro elemento. > > Come posso evitare l'errore??? > > > *** > Avevo provato con > > if confini.index(nomeelemento): > return qualcosa > else: > continue > > *** > Oppure con > > if confini.index(nomeelemento)>-1: > return qualcosa > else: > continue > > Ma nel caso non venga trovato l'elemento da errore Prova a usare le eccezioni. Cio? fai try: return qualcosa except IndexError: continue Marco From coder5811 at yahoo.com Sat May 8 03:31:58 2004 From: coder5811 at yahoo.com (Coder Coder) Date: 8 May 2004 00:31:58 -0700 Subject: __import__ Message-ID: Hi, Can someone help me with how to overload the __import__ function, so that I can call the old __import__ function and if it cannot find the library to be able to do something else. - Thanks. From martin at v.loewis.de Thu May 27 13:30:40 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 May 2004 19:30:40 +0200 Subject: terminological obscurity In-Reply-To: References: <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: <40B625C0.3040605@v.loewis.de> >>Really makes no difference at all - not just insignificant, >>really _no_ difference. A truly heterogeneous sequence may >>be full of references to the _same_ object (e.g., (1, 1, 1)), >>and a truly homogeneous sequence may have objects as different >>as None and a module. It's not about properties of the objects, >>considered in isolation. > > > You fundamentally miss my point. > > What you are saying is clear enough. You are also saying that this is > what Guido meant, when he said something different. And leaving as > anomolous why Guido didn't say what he meant himself. What he did say is "Tuples are for heterogeneous data, list are for homogeneous data. Tuples are *not* read-only lists." He did not actually define the terms that he was using (just as he did not define the terms tuple, list, data, or read-only). It is very clear to my why he did not say what Donn said - because he thought that the notion of homogenous and heterogenous is obvious to anybody. He then *also* said something about how static typing might be introduced into Python - but that was about possible static typing, not about the terms "homogenous" and "heterogenous". Even with static typing, it might be possible to declare a list that is statically typed, contains homogenous data, and yet contains objects as different as None and a module. The type of this list might be "list of (NoneType union ModuleType)", better declared as "list of optional ModuleType". Regards, Martin From pathall at gmail.com Fri May 28 02:31:36 2004 From: pathall at gmail.com (Patrick Hall) Date: 27 May 2004 23:31:36 -0700 Subject: partial / wildcard string match in 'in' and 'list.index()' Message-ID: Hi, > For a given list: > fruits=["apples","oranges","mangoes","bananas"] > > Is it possible to do wildcard matches like shown below? > 1. "man*" in fruits > 2. fruits.index("man*") > 3. "*nanas*" in fruits > 4. fruits.index("*nanas") I'm not sure if this is what you had in mind, but you can use list comprehensions: fruits=["apples","oranges","mangoes","bananas"] import re 1. [fruit for fruit in fruits if re.match("man.*",fruit)] 2. [fruits.index(fruit) for fruit in fruits if re.match("man.*",fruit)] 3. [fruit for fruit in fruits if re.match(r".*an.*",fruit)] 4. [fruits.index(fruit) for fruit in fruits if re.match("man*",fruit)] Note also that I think you're looking for .* instead of just * in your regular expressions. > or is there any way to achieve an equivalent effect > short of doing a while loop? I personally am not so sure a while loop wouldn't be clearer in this case -- things like "fruit for fruit in fruits" are pretty unreadable to me. Cheers, Pat From Laura.McCord at doucet-austin.com Fri May 21 10:55:52 2004 From: Laura.McCord at doucet-austin.com (Laura McCord) Date: Fri, 21 May 2004 09:55:52 -0500 Subject: Deleting Directories Message-ID: <573C3D25471BAE4DB0CDA25B1FE6C3832E342B@aa16exc.int.doucetandassociates.com> This is probably a very basic question but I started learning python. I am almost done writing my delete directory script but I am at a stand still right now. I want to delete folders in my "/var/www/html/da" directory that are over 1 day old. But, when I find the folder a simple rmdir() command does not work because the directory is not empty. What else do I need to do to delete a directory that contains content? Here is the code: dir = "/var/www/html/da" currentTime = int(time.time()) print currentTime dirfiles = os.listdir(dir) print dirfiles for name in dirfiles: dirpath = os.path.join(dir, name) mod_time = os.path.getmtime(dirpath) timeDiff = currentTime - mod_time if timeDiff > maxOld: print dirpath Thanks, Laura From martin at v.loewis.de Fri May 28 02:52:10 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 May 2004 08:52:10 +0200 Subject: terminological obscurity In-Reply-To: <1085718479.27401@yasure> References: <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <1085718479.27401@yasure> Message-ID: <40b6e196$0$12458$9b622d9e@news.freenet.de> Donn Cave wrote: > Well, I'm not really sure what he has in mind there, so there > is some ambiguity for students of homogeneity such as ourselves. I was trying to point out (and try again), that uniform typing and homogeneity are *not* the same things, all the time. However, people often consider them to be the same thing, and for a good reason: In *most* applications, homogenous structures are uniformly typed, and uniformly typed collections are typically homogenous. Now, if someone brings up a collection which is homogenous, but where elements have different most-specific types, it may still be the case that the types share some common supertype. One way of obtaining such a common supertype is the introduction of a union type. However, this is about typing, not about homogeneity. Regards, Martin From mcfletch at rogers.com Tue May 18 11:47:51 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 18 May 2004 11:47:51 -0400 Subject: How to just wait 3 secs ? In-Reply-To: <40AA2AFD.1080804@attglobal.net> References: <40AA2AFD.1080804@attglobal.net> Message-ID: <40AA3027.50107@rogers.com> import time time.sleep( 3 ) HTH, Mike Marcello Pietrobon wrote: ... > I would like to make my script to wait 3 seconds ( so I can read the > output on the console ) > and then continue. > How do I do it ? ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From rmunn at pobox.com Mon May 10 13:03:41 2004 From: rmunn at pobox.com (Robin Munn) Date: Mon, 10 May 2004 17:03:41 GMT Subject: polymorphism w/out signatures? References: <314b29e9.0405070128.28de9ff6@posting.google.com> Message-ID: Simon Brunning wrote: > > def setText(window, text, append=False): > # Ensure that text is a list > try: > text + '' > text = [text] > except TypeError: > pass > > ... rest of funtion, which can assume that 'text' is a list That would be better with an "else:" clause: try: text + '' except TypeError: pass else: test = [text] -- Robin Munn rmunn at pobox.com From heikowu at ceosg.de Mon May 3 08:02:44 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Mon, 3 May 2004 14:02:44 +0200 Subject: Bug in PyCallable_Check In-Reply-To: References: Message-ID: <200405031402.44454.heikowu@ceosg.de> Am Montag, 3. Mai 2004 13:39 schrieb Arkon: > And then the PyCallable_Check won't *detect* that it's not a real > function(pointer) passed...then later when you intend to run that > function, you get an error. PyCallable_Check does as it is told, it checks whether the argument can be called. There are loads of callable things in Python, method references being just one of them. A class is callable (instantiation or overridden __metaclass__ or the like), an instance is callable (using the __call__ method of the class), and many other things too. What you're seeing (complaining about) is that types are nothing else than classes, and so they are callable too. If you really have to check that it is a function, you'll have to check the type of the reference for types.FunctionType. HTH! Heiko. From jdhunter at ace.bsd.uchicago.edu Tue May 11 08:33:28 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 11 May 2004 07:33:28 -0500 Subject: plot two data sets on gnuplot In-Reply-To: <4CBS9k$wiV@redbbs.cc.ntut.edu.tw> (casio.bbs@redbbs.cc.ntut.edu.tw's message of "10 May 2004 14:29:03 GMT") References: <4CBS9k$wiV@redbbs.cc.ntut.edu.tw> Message-ID: >>>>> "?}???F???" == ?}???F??? writes: > I'm trying to write a script to pass a file of stock > prices and volumes, and plot the results on a gnuplot > graph which is non-overlapped graph. > Fig. 1 ------------ Fig. 2 > Figure 1 is a graph of stock prices, and Figure 2 is a > graph of stock volumes, I'm trying to implement it as > following codes, I don't use gnuplot, but I just wanted to let you know that I recently added a finance module for matplotlib http://matplotlib.sourceforge.net that supports the kind of graph you are trying to make. It's fairly minimalist now, but will grow in the near future. Here is a screenshot of a financial chart I made to show off some of the finance features http://nitace.bsd.uchicago.edu:8080/files/share/finance_demo.png If you're interested, you can check out the finance_demo.py example in the matplotlib src distribution, and if you want to seem more example code than you find in that dir, email me and I'll send some your way. Good luck! John Hunter From __peter__ at web.de Fri May 14 12:14:23 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 May 2004 18:14:23 +0200 Subject: Loop and the list References: Message-ID: Krzysztof Szynter wrote: > def normowanie(TY,max): > "normalize the function" > for i in range(0,len(TY)-1): > TY[i] = TY[i]/float(TY[max]) > return TY While you iterate over TY, for i==max TY[max] suddenly changes to 1, and now all further items are divided by 1, i. e. remain unchanged. Remove the second argument altogether, remove your maxvalue() function and then put the following line at the beginning of your script: from __future__ import division # indicate that we want # 1/2 == 0.5 instead of 0 Now the revised normalization function (untested): def normowanie(TY): m = max(TY) return [v/m for v in TY] This creates a normalized copy of the original list. You can call it: normalizedTY = normowanie(TY) If you want to change TY in place, i. e. you need not keep the original list, here's that variant: def normowanie(TY): m = max(TY) TY[:] = [v/m for v in TY] As this follows the example of the mutating methods like list.append() and list.sort() and doesn't return the list, call it like so: normowanie(TY) All items in TY are now in the range 0 <= v <= 1 (assuming there were no negative values in the first place), but the original values are lost. Peter From eriksp at attbi.nospam.com Thu May 20 21:11:37 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 21 May 2004 01:11:37 GMT Subject: Confused about while statement Message-ID: In theory, the following code should ask for the user to enter a value for h until he/she enters hello or goodbye. h = "hi" while h != "hello" or "goodbye": h = raw_input("Value for h:") But the program keeps asking for a value no matter what I enter. Why doesn't it work? From mhuening at zedat.fu-berlin.de Fri May 28 08:39:06 2004 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 28 May 2004 12:39:06 GMT Subject: py2exe encoding References: Message-ID: Yermat wrote in news:c978v6$chl$1 at arcturus.ciril.fr: > It was in the FAQ and now in the wiki: > http://starship.python.net/crew/theller/moin.cgi/EncodingsAgain > Thanks a lot. That solved my problem. Matthias From antonmuhin at rambler.ru Fri May 14 10:32:08 2004 From: antonmuhin at rambler.ru (anton muhin) Date: Fri, 14 May 2004 18:32:08 +0400 Subject: Loop and the list In-Reply-To: References: Message-ID: <2gk3eeF3gha1U1@uni-berlin.de> Krzysztof Szynter wrote: > Hi all > > Have got a big problem. This is my code: > > [snipped] If I understand you correctly, you just need to find maximum. If it's so, there is better way: built-in max function: >> max([1, 2, 3]) 3 regards, anton. From steve at ferg.org Thu May 20 08:40:49 2004 From: steve at ferg.org (Stephen Ferg) Date: 20 May 2004 05:40:49 -0700 Subject: Who is maintaining the "Python eggs" page? Message-ID: There are a couple of broken links on the Python Eggs site: http://www.python-eggs.org/links.html I'd like to reach the maintainer and report them, but there's no information about the maintainer on the page. Does anyone know who the maintainer is, and how to reach him/her? From __peter__ at web.de Wed May 26 05:54:05 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 11:54:05 +0200 Subject: Cleaner idiom for text processing? References: Message-ID: Duncan Booth wrote: > Peter Otten <__peter__ at web.de> wrote in news:c91got$vpi$00$1 at news.t- > online.com: > >> Yet another way to create the dictionary: >> >>>>> import itertools >>>>> nv = iter("foo 1 bar 2 baz 3\n".split()) >>>>> dict(itertools.izip(nv, nv)) >> {'baz': '3', 'foo': '1', 'bar': '2'} >>>>> > > You can also do that without using itertools: > >>>> nv = iter("foo 1 bar 2 baz 3\n".split()) >>>> dict(zip(nv,nv)) > {'baz': '3', 'foo': '1', 'bar': '2'} >>>> The advantage of my solution is that it omits the intermediate list. > However, I'm not sure I trust either of these solutions. I know that > intuitively it would seem that both zip and izip should act in this way, > but is the order of consuming the inputs actually guaranteed anywhere? I think an optimization that changes the order assumed above would be *really* weird. When passing around an iterator, you could never be sure whether the previous consumer just read 10 items ahead for efficiency reasons. Allowing such optimizations would in effect limit iterators to for loops. Moreover, the calling function has no way of knowing whether that would really be efficient as the first iterator might take a looong time to yield the next value while the second could just throw a StopIteration. If a way around this is ever found, checking izip()'s arguments for identity is only a minor complication. But if that lets you sleep better at night, change Peter Hansen's suggestion to use islice(): >>> from itertools import * >>> nv = "foo 1 bar 2 baz 3\n".split() >>> dict(izip(islice(nv, 0, None, 2), islice(nv, 1, None, 2))) {'baz': '3', 'foo': '1', 'bar': '2'} >>> However, this is less readable (probably slower too) than the original with normal slices and therefore not worth the effort for small lists like (I guess) those in the OP's problem. Peter From __peter__ at web.de Mon May 10 13:27:14 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 May 2004 19:27:14 +0200 Subject: Watch That Post References: <0rOnc.20115$7n5.16403@pathologist.blueyonder.net> Message-ID: Steven wrote: > Premshree Pillai wrote: > >> Hello, >> >> I recently posted a simple Python script--Watch That >> Post--that lets you watch a URL for any changes. >> >> I wrote it to watch posts on LiveJournal, but it can >> watch any URL. >> >> It's at http://premshree.seacrow.com/code/python/watch > > > I tried running it. It works fine until it tries to run the watch function > a second time, then it does this: > > Traceback (most recent call last): > File "watch.py", line 76, in ? > watch() > File "watch.py", line 58, in watch > size2 = len(urllib.urlopen(url).readlines()) > File "/usr/lib/python2.3/urllib.py", line 76, in urlopen > return opener.open(url) > File "/usr/lib/python2.3/urllib.py", line 181, in open > return getattr(self, name)(url) > File "/usr/lib/python2.3/urllib.py", line 410, in open_file > return self.open_local_file(url) > File "/usr/lib/python2.3/urllib.py", line 420, in open_local_file > raise IOError(e.errno, e.strerror, e.filename) > IOError: [Errno 2] No such file or directory: 'www.kde-apps.org' > > I really like the idea, > > Steven Try to provide the protocol: >>> import urllib >>> urllib.urlopen("www.kde-apps.org") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/urllib.py", line 76, in urlopen return opener.open(url) File "/usr/local/lib/python2.3/urllib.py", line 181, in open return getattr(self, name)(url) File "/usr/local/lib/python2.3/urllib.py", line 410, in open_file return self.open_local_file(url) File "/usr/local/lib/python2.3/urllib.py", line 420, in open_local_file raise IOError(e.errno, e.strerror, e.filename) IOError: [Errno 2] No such file or directory: 'www.kde-apps.org' >>> urllib.urlopen("http://www.kde-apps.org") > >>> (Just a guess) Peter From martin at v.loewis.de Thu May 13 14:20:01 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 13 May 2004 20:20:01 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> References: <40a39511$0$560$e4fe514c@news.xs4all.nl> <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> Message-ID: <40A3BC51.3040605@v.loewis.de> Irmen de Jong wrote: > P.S. I don't really see why you mentioned python-dev, are you saying > that bugs and patches have more chance of being included in a new > Python version if the submitter is subscribed to python-dev and also > announces the bugs/patches there? Patches have a larger chance to get included if they are reviewed. For the last few years, we have been short of reviewers, so patches have little chance to get included, period. People submitting patches might consider helping the process beyond submitting patches, e.g. by reviewing patches of other people. E.g. review 10 or so patches, put your comments into them, and then suggest approval or rejection on python-dev. Then, somebody (perhaps yours truly) might check bulk-close patches if he agrees with the review. If any submitter of a patch would review 10 other patches, there would be no backlog. Regards, Martin From fs111 at linuxmail.org Fri May 14 11:49:58 2004 From: fs111 at linuxmail.org (=?ISO-8859-15?Q?Andr=E9?= Kelpe) Date: Fri, 14 May 2004 17:49:58 +0200 Subject: is it a daemon? how to create such a thing... References: Message-ID: <2gk856F3ug7fU1@uni-berlin.de> Valia wrote: > hello all, Hi! > so i wonder if i could have some kind of process/script which would > load this list once and then wait for the smaller scripts theirs > queries about replacements pairs and answer them. i imagine this have > to do with daemon programming but i'm brand new to it, and also i just > need the simpler piece of code to do that (it is for a quick > experiment, my aim is not to create an apache server framework :) ) Take a look at Pyro (Python Remote Objects) at http://pyro.sf.net. This should easily solve all your problems. HTH Andr? From guettli at thomas-guettler.de Wed May 5 11:32:13 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 05 May 2004 17:32:13 +0200 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: Am Wed, 05 May 2004 06:16:06 -0700 schrieb Stephen Ferg: >> Is submitting a bug or patch to sourceforge really that much of a barrier? > > Yes, it is a significant barrier. It requires knowledge of both Latex > and a certain way of using diff. Hi Stephen, You don't need to submit a patch to the latex source. You can send plain text as a "feature request". I already send some feature request which were added to the docs (deadlock problem, if not using popen4) If you are unsure if it should be in the docs, you can ask here before sending it to the bug tracking system. Thomas From amireallyfat at yahoo.com.au Mon May 24 18:10:51 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Tue, 25 May 2004 08:10:51 +1000 Subject: why i Message-ID: <40b2e204$1_1@news.iprimus.com.au> i never got this its always in my tutial bookfor i in range(...) From lesstif-admin at lesstif.org Mon May 17 03:06:18 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Mon, 17 May 2004 07:06:18 -0000 Subject: Request to mailing list Lesstif rejected Message-ID: Your request to the Lesstif mailing list Posting of your message titled "my advice...." has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From peter at engcorp.com Wed May 26 09:40:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 09:40:01 -0400 Subject: sys.stdout linebuffered In-Reply-To: References: Message-ID: Thomas Guettler wrote: > I start a long running script like this (unix): > > nohup foo.py > foo.log & [snip] > The "-u" switch is not an option. That statement is suspect, and like Benjamin I wonder whether it really is true. Nevertheless, in the unlikely case that you absolutely cannot use the -u switch, look at the description of that option in the output of "python -h" and use the environment variable mentioned there instead. -Peter From steve at ferg.org Thu May 20 14:10:02 2004 From: steve at ferg.org (Stephen Ferg) Date: 20 May 2004 11:10:02 -0700 Subject: Who is maintaining the "Python eggs" page? References: Message-ID: I bet you're right! :-) Thanks! From peter at engcorp.com Tue May 4 08:37:45 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 May 2004 08:37:45 -0400 Subject: is it possble to run a script from the python shell? In-Reply-To: References: Message-ID: Darren Dale wrote: > If so, how is it done? This is probably a stupid question. But when I > os.chdir into a directory that I know contains a python file, when I try > to call it > >>>>color_demo.py As Aahz said, use execfile(). I wanted to note, however, that calling the Python interactive interpreter prompt a "shell" is probably a poor idea, and a possible source of confusion for you. I believe "shells" will generally pass unrecognized commands on to another layer for further processing (and thus the name). Python's prompt is not a shell in that sense, as it recognizes only Python syntax and will give an error for any other commands. Typing just the name of a file, while it may work at your command line or Linux shell, is not valid Python syntax, so it doesn't work. There are some (or at least one) real shells for Python, in the sense of the word I think you're using. Look at http://ipython.scipy.org/ for further info about one such package. -Peter From apardon at forel.vub.ac.be Thu May 13 03:40:45 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 07:40:45 GMT Subject: Scope rule pecularities References: <2g8ag2F4re0lU1@uni-berlin.de> Message-ID: Op 2004-05-12, Donn Cave schreef : > In article , > Antoon Pardon wrote: > >> Op 2004-05-12, Duncan Booth schreef : >> > Antoon Pardon wrote in >> > news:slrnca428q.1i9.apardon at trout.vub.ac.be: >> > >> >> IMO lacking an assignment that copies the value >> >> of one object into another was a mistake and >> >> which creats IMO a lot of difficulties. >> >> >> >> If I have a function with an object as a paramter. >> >> and this object is mutable. Now within this function >> >> I find a second object with the value I want the >> >> argument to have. Now I can't simply copy the >> >> second object over the argument but I have to >> >> copy attribute by attribute from the second object >> >> into the argument. >> > >> > Why wouldn't you just return the second value (or a copy of it) as a result >> > from the function? That is usually a more flexible choice since it gives >> > the caller the option of either replacing the original value or using the >> > modified value somewhere different. >> >> Well because the object could be bound with more than one name. >> >> > Anyway, if you really need to do this then the mutable object should have >> > some sort of updateState method which takes the second object as a >> > parameter. That way the original object can have control over which >> > attributes get overwritten and which don't. >> >> And I think it is a pain in the butt to always have to write such an >> UpdateState method whenever you want one object to be copied in place >> from an other. > > I really think this is a cases where you will write better > programs if you let yourself be guided by what you can do > in idiomatic Python. I don't know. My attitude is that I don't program in a language. I program by outlining structurers, functionality, algorithm, etc which are then translated into a language. I judge languages by how much I have to fight them in getting this translation. Of course the knowledge of languages has an influence in how I outline these things, but I don't do the outline with a particular language in mind. > In modern programming, now that we have pretty much adopted > the "structured" programming model, one of the main remaining > burdens on the programmer is "mutable state". You need to > be able to account for possible changes in values, if you > want to be able to reason about your program. Python isn't > any kind of extreme solution to this problem, it isn't a > "pure" functional language, but it does have some helpful > constraints and this is one of them - you know a function > can't rebind names that you supply as its parameters. The > inability to do this is a feature. But I don't ask for rebinding, I ask for easy in place copying. Lets name a new operator "@=" Now given variables A and C of the same class I would like to see the following: >>> B = A >>> A @= C >>> A is B True >>> A is C False >>> A == C True And maybe if D is of an other class >>> D @= C TypError -- Antoon Pardon From irmen at -nospam-remove-this-xs4all.nl Sat May 15 09:36:22 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 15 May 2004 15:36:22 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: References: <40a39511$0$560$e4fe514c@news.xs4all.nl> <40a60334$0$65124$e4fe514c@news.xs4all.nl> Message-ID: <40a61cd6$0$563$e4fe514c@news.xs4all.nl> Aahz wrote: > 2.4 has plenty of time for patches to get accepted. There will be at > least a month after the first published alpha before a release candidate > gets created. I'm confused now because this thread has been about > 2.3.4, which is a relatively low-effort bugfix release. You're right ofcourse. I mixed things up -- please ignore what I said about 2.4. I'll think twice before posting about this again :-) -Irmen From donn at u.washington.edu Tue May 18 17:28:15 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 18 May 2004 14:28:15 -0700 Subject: Popen3-style os.execl? References: Message-ID: In article , Chris Green wrote: > Hey folks, > > I'm whipping up a quick CGI to wrap a command line app and I was a bit > suprised to not find a execl-like Popen3 style object. I don't want > to bother with the shell interpreting metacharaters by constructing a > command line. > > Basically, I want something that acts just like Popen3 but allows me > to specify cmd as a path + args. Does something like this exist in > the standard library? If not, it sounds like a good candidate... Did you try it? I think of Popen3 as something that acts just like you describe, but also accepts a command line. Not the best API, maybe. Donn Cave, donn at u.washington.edu From sbard at lexpert-auto.com Wed May 19 08:07:20 2004 From: sbard at lexpert-auto.com ( image-sig@python.org) Date: Wed, 19 May 2004 14:07:20 +0200 Subject: wmf question Message-ID: hi I try to use PIL and wmf image - PIL-1.1.5a1 - python 2.3 source = Image.open( r"A0174.WMF", 'r') image = apply( wxEmptyImage, source.size ) image.SetData( source.convert( "RGB").tostring() ) return image.ConvertToBitmap() but when i resize my picture fonts don't resize is it possible to resize wmf fonts ? I try to look to WmfImagePlugin.py Thank's for help -> a french python who love zope,wxpython & pil From agriff at tin.it Sun May 16 04:57:17 2004 From: agriff at tin.it (Andrea Griffini) Date: Sun, 16 May 2004 08:57:17 GMT Subject: Guess My Number Game References: Message-ID: <90aea0p1sn3ehbca0tds5uuhj5brrbbdj9@4ax.com> On Sat, 15 May 2004 15:58:22 +0200, Heiko Wundram wrote: Not really python related, but... >On average, the shortest possible runtime (and also a deterministic runtime of >O(log2(high-low))) will be achieved if you use interval walking. > >Thus: > >number = 64 >low = 1 >high = 100 >while low <> high: > med = (low+high)//2 > tries += 1 > if med == number: > print "I guessed your number:", med > elif med < number: > if med == low: > print "I guessed your number:", med+1 > low = med+1 > else: > low = med > else: > high = med >print "I needed", tries, "tries." This bisection algorithm is bad. On average it will require about 0.5 more steps than necessary. A better one is... def dico2(low,high,guess): while low < high: t = (low + high)//2 g = guess(t) if g == 0: return t elif g == -1: low = t+1 else: high = t-1 return low supposing that guess(x) returns -1, 0 or 1 depending if the number is too low, correct or too high. If you find yourself handling special cases in a bisection algorithm (e.g. your test "if med==low") then you can be quite sure there's a better way. HTH Andrea From jbors at mail.ru Tue May 25 15:33:00 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Tue, 25 May 2004 23:33:00 +0400 Subject: programming video manipulation In-Reply-To: Message-ID: -----Original Message----- From: Olivia Robinson > > I have been investigating Python as an alternative to using > MAX/MSP/Jitter to program the collection of information from the > sensors and the resulting video manipulation. I have not been able to > find information about manipulating video with Python, or collecting > information from a microcontroller. I have heard that I may need a > library of commands already written in C or C++. Does anyone have any > information about using Python with microcontrollers or manipulating > video? Ideas? Hi Olivia, Not sure which interface your microcontrollers are using, if it is USB, then you might look at PyUSB which seems should work. Otherwise you may need some standard C/C++ libs. For video manupulation you may try pymedia( http://pymedia.sourceforge.org ). At the time PyMedia supports avi( mpeg4, divx, xvid ), asf, mov, mpeg( encoding/decoding ). It will include more a/v formats in 2 months. Hope this helps, Dmitry/ From cliechti at gmx.net Sun May 23 16:56:46 2004 From: cliechti at gmx.net (Chris Liechti) Date: Sun, 23 May 2004 20:56:46 +0000 (UTC) Subject: Problem concerning pyparallel References: Message-ID: Harald Schreiber wrote in news:c8qqp4$u1$01$1 at news.t-online.com: > Hi, > When trying to install the pyparallel-software under Windows98SE I got an > errormessage about a missing cl.exe. > Can someone there out give me some explanations? in case your talking about my extension with that name, it requires to build a .pyd extenstion. either you download the binary distribution from pyserial.sf.net or compile it on your own. you dont seem to have the M$ compiler, but youc an also use cygwin (i do) or mingw. in both cases run python setup.py build --compiler=mingw32 install chris -- Chris From pit.grinja at gmx.de Wed May 19 01:57:41 2004 From: pit.grinja at gmx.de (Piet) Date: 18 May 2004 22:57:41 -0700 Subject: Making items visible in wxPython wxListCtrl References: <39cbe663.0405181208.1065933d@posting.google.com> Message-ID: <39cbe663.0405182157.5725185d@posting.google.com> Shame on me.... Looks like as if wanted to populate a non-existing column with data. Anyway, now evrything is working properly. Many, many thanks! That helped me a lot. Piet From loic at fejoz.net Thu May 6 06:29:38 2004 From: loic at fejoz.net (Yermat) Date: Thu, 06 May 2004 12:29:38 +0200 Subject: classes vs dicts In-Reply-To: References: Message-ID: Charlie wrote: > Greetings, > > I am pretty new to Python and like it very much, but there is one > thing I can't figure out and I couldn't really find anything in the > docs that addresses this. > > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? > I guess using dictionaries is fastest and easiest, but is this > recommended? > > Thanx for any help. create a class ! You're wrong when you're saying that dictionaries is fastest because class use dictionaries to find attributes so that the same ! But class is nicer to read and manage... -- Yermat From andrew-pythonlist at puzzling.org Mon May 10 02:51:58 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 10 May 2004 16:51:58 +1000 Subject: Passing objects to a function In-Reply-To: References: Message-ID: <20040510065158.GD14313@frobozz> On Sun, May 09, 2004 at 04:36:53PM -0700, Robert Brewer wrote: > > Barring that, however, the right way to document a function is: the > documentation string, of course! > [...] > > ...following the example for the 'str' builtin, you might write: > > def BlackJackValue(hand): > """BlackJackValue(Hand_instance) -> int\n\nReturn an integer, which > is the value of the Hand according to the rules of BlackJack.""" > pass Except I hope you'd use real newlines, rather than \n, for the sake of people trying to read the source. If you used epydoc , you could specify types like this: def BlackJackValue(hand): """Return the value of the hand, according to the rules of Blackjack. @arg hand: The hand to calculate the value of. @type hand: Hand @returns: The value of the hand @rtype: int """ It's reasonably readable, if somewhat verbose. And then epydoc can make reasonably nice HTML API docs for you, if you're into that sort of thing :) -Andrew. From hilda at array.ca Mon May 31 14:47:30 2004 From: hilda at array.ca (Hilda Faraji) Date: Mon, 31 May 2004 14:47:30 -0400 Subject: pymat for python 2.3? Message-ID: <000001c4473f$ba835f20$1cf8c5c0@purple> Hello there I was wondering how I can find a version of Pymat, which can be compatible with Python 2.3. I appreciate if some one can help. Thanks Hilda -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at gazeta.usun.pl Sun May 9 02:25:29 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 9 May 2004 06:25:29 +0000 (UTC) Subject: What I don't like about wxPython References: Message-ID: OKB (not okblacke) pisze: >> Ultimately, none of these ui api's are as 'pythonic' as I want them >> to be, and wxPython in particular seems like a carbon copy of the C >> api, which makes it lose points in my book. > > I agree with this; that API seems completely incongruous in a > Python program. It has been told and written many times. If you look something "more pythonic" yet still such powerful, you can use some wrapper on wxPython. Wax first comes to my mind, look for it in PyPi. -- Jarek Zgoda http://jpa.berlios.de/ From fumanchu at amor.org Fri May 7 11:50:02 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 May 2004 08:50:02 -0700 Subject: polymorphism w/out signatures? Message-ID: Peter Otten wrote: > Larry Bates wrote: > > > I use type() quite a lot. I poked around and couldn't > > find where it was being deprecated. I did see that > > types module is slated for deprecation. Maybe I > > overlooked it? > > > > I use: > > > > class foo: > > _stringtype=type('') > > _tupletype=type(()) > > _listtype=type([]) > > > > def __init__(self, variable): > > if type(variable) == _stringtype: > > self.variable=variable # check for string type > > if type(variable) in (_listtype, tupletype): > > self.variable=str(variable) # check for list/tuple > > I would change that to > > def __init__(self, v): > self.variable = str(v) If only that worked for datetime types ;) >>> d = datetime.date(2004, 1, 1) >>> d2 = datetime.date(d) Traceback (most recent call last): File "", line 1, in ? TypeError: function takes exactly 3 arguments (1 given) D'oh! One of these days, I'm going to file a bug for that. Robert Brewer MIS Amor Ministries fumanchu at amor.org From klachemin at home.com Thu May 27 09:06:52 2004 From: klachemin at home.com (Kamilche) Date: 27 May 2004 06:06:52 -0700 Subject: How to list all functions in an imported module? Message-ID: <889cbba0.0405270506.3cd91d26@posting.google.com> I can't figure out how to list all functions from an imported module. I searched Google, but all the answers I found didn't work. Did something change in Python 2.2, perhaps there's a new method of doing it? From jepler at unpythonic.net Thu May 27 22:41:46 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 27 May 2004 21:41:46 -0500 Subject: Terminating program run from thread (not just the thread) In-Reply-To: References: Message-ID: <20040528024146.GA9914@unpythonic.net> The class-based interface to popen3(), popen2.Popen3, stores the pid in an attribute called "pid". Jeff From jfabiani at yolo.com Mon May 17 19:03:22 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 17 May 2004 23:03:22 GMT Subject: module for working with the result set In-Reply-To: References: Message-ID: <_wbqc.68175$eT6.35900@newssvr25.news.prodigy.com> Diez B. Roggisch wrote: >>mydata=cursor.fetchmany(10) >>for field in mydata[0]: >> print mydata[0][field] >> >>Traceback (most recent call last): >> File "C:\Python23\Lib\site-packages\sm\scriptutils.py", line 49, in run >> exec codeObject in mainDict >> File "", line 10, in ? >> File "C:\Python23\Lib\site-packages\pyPgSQL\PgSQL.py", line 2063, in >>__getitem__ >> key = self._xlatkey[key.lower()] >>KeyError: '5992 ' >>Exception raised while running script >> >>But ;( >>print mydata[0][0], mydata[0][1] >>the above works perfectly - prints what I want. > > > it seems that the value of field is 5992, and that isn't a key to the row - > which is quite likely, as 5992 as column-name is most probably forbidden, > and as index a little bit high - can't imagine what a table with ~6000 > columns should hold.... > > Now what about showing us the result of this: > > mydata=cursor.fetchmany(10) > print mydata[0] > > Then one can tell how to access the fields. Thats a general advice: when > such things occur, print out the values in question short before the > problem, then you can see if and more important why what you expect and > what you get differ. > See this does not make sense to me. mydata[0] ['5992 ', 'A', '5346 ', ' ', 'XX ', 'Kathy Stromme ', 'RICHMOND AMERICAN HOMES ', '7250 WEST PEAK, ST # 212 ', ' ', 'LAS VEGAS ', 'NEVADA ', '89128 ', ' ', '702-240-5600 ', ' ', 'RICHMOND AMERICAN HOMES ', '7250 WEST PEAK, ST # 212 ', ' ', 'LAS VEGAS ', 'NEVADA ', '89128 ', ' ', '702-240-5600 ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0/0/30 ', 'FIRST ', ' ', ' ', ' ', ' ', ' ', 'USD', ' ', , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , '', '', '64 ', ' ', '4-PPPP-34 ', 'COURTYARD @ LONE MT. TERRACE ', ' ', 'RACL ', ' ', 'R1', ' ', 'ALVJU', 'MONJO', , , , , , , , None, None, None, , None, , , 'JUAN ALVAREZ ', 'JOSE MONTALVO ', ' ', '5992 ', ' ', None, None, , , None, None, ' ', ' ', None, None, None, None, , ' ', , ' ', None, None, None, ' ', None, ] From sbard at lexpert-auto.com Wed May 19 08:09:37 2004 From: sbard at lexpert-auto.com (sbard at lexpert-auto.com) Date: Wed, 19 May 2004 14:09:37 +0200 Subject: wmf question Message-ID: hi I try to use PIL and wmf image - PIL-1.1.5a1 - python 2.3 source = Image.open( r"A0174.WMF", 'r') image = apply( wxEmptyImage, source.size ) image.SetData( source.convert( "RGB").tostring() ) return image.ConvertToBitmap() but when i resize my picture fonts don't resize is it possible to resize wmf fonts ? I try to look to WmfImagePlugin.py Thank's for help -> a french python who love zope,wxpython & pil (sorry for mistake in my email adress) From just at xs4all.nl Wed May 12 03:17:50 2004 From: just at xs4all.nl (Just) Date: Wed, 12 May 2004 09:17:50 +0200 Subject: OT: Idea for Python T-shirt References: Message-ID: In article , "Simon Wittber" wrote: > A python T-Shirt? > > Funnily enough, I was thinking on this last night. Something eloquent, > something slightly obscure, which only other Pythonistae would recognize: > > "import this" "import this" pretty much started its' life on a t-shirt. Best picture I could find on line: http://twistedmatrix.com/users/glyph/ipc10/photos/Large/TeamTwisted.jpeg The "this" module was an easter egg for IPC10/Python 2.2, the shirt was a hint. Just From j_mckitrick at bigfoot.com Fri May 21 15:33:04 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 21 May 2004 12:33:04 -0700 Subject: Using pygtk and glade2 References: <40AC9EAE.4020905@draigBrady.com> <40ADE246.9050502@draigBrady.com> Message-ID: > Hang on, gtk.Bin isn't even in the combo hierarchy? > http://www.pygtk.org/pygtk2reference/class-gtkcombo.html > Are you sure you've got the correct widget? > > P?draig. I clicked on it in Glade2, and the property window said 'combobox1'. Then I added the signal and built the app. This is the same thing I did with 'comboentrybox'. jonathon From kirk at eyegor.jobsluder.net Wed May 12 12:43:29 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Wed, 12 May 2004 16:43:29 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: On 2004-05-12, Ville Vainio wrote: >>>>>> "Kirk" == Kirk Job-Sluder writes: > > Kirk> And here is the fundamental question. Why should I spend my > Kirk> time writing a module in python to emulate another tool, > Kirk> when I can simply use that other tool? Why should I, as a > > Perhaps you won't; but someone who isn't already proficient with the > tool may rest assured that learning the tool really isn't worth his > time. awk and sed fall into this category. Actually, I'm not convinced of the learning time argument. It takes about 30 minutes training time to learn enough awk or sed to handle 90% of the cases where it is the better tool for the job. A good understanding of regular expressions will do most of your work for you no matter which langugage you use. > Kirk> resarcher who must process large quantities of data, spend > Kirk> my time and my employer's money reinventing the wheel? > > You are not reinventing the wheel, you are refactoring it :). I don't > think your employer minds you spending 15 extra minutes creating some > tool infrastructure, if it allows you to drop awk/sed dependency that > your co-workers then won't need to learn. In which my case, the perl version is more likely to win out on the basis of standardization. IME, the time involved to create good infrastructure that does not come back to bite you in the ass is considerably more than 15 minutes. Think also that for every minute you spend designing something to share, you need to spend between 5-20 documenting and training in the organization (and this is not including maintenance and distribution.) The great thing is that the tool infrastructure already exists. Not only does the tool infrastructure exist, but the training materials already exist. Really, how hard is "perl -pi -e 's/foo/bar/'" to understand? How hard is "sed -e 's/foo/bar/' < infile > outfile" to understand? How hard is a shell script to understand? > I find writing pythonic tools a relaxing deversion from my everyday > work (cranking out C++), so I don't really mind. As long as the time > spent is within 5 minutes - 1 hour range. Well, there is another big difference. I'm a big fan of instant gratification so the off-the-shelf tool that does the job in 10 seconds is better than 5 minutes to 1 hour writing a pythonic tool. I have re-written shell scripts in python just for kicks, but I don't have any illusions that refactoring everything into python should be a perogative. From uche at ogbuji.net Mon May 10 12:16:36 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 10 May 2004 09:16:36 -0700 Subject: Processing Python and xml PyXml - References: Message-ID: chuck amadi wrote in message news:... > Hi all Im new to Python but regularly write xml articles for my > Organisation and a past Java Sys Programmer. > > I can write basic Python but seem to have trouble excuting the > xml/python examples . > > Installed PyXml and have Python 2.1,2,2 and 2.3 running . > > I have used SAX and ANT for building html pages from xml but im missing > something here. > > Please can someone point me in the right direction as I usally use vi > > chmod the py file and run ./file.py > > Please help as I need to get to grips with PyXml and xml /python > processing for a project coming in soon! > > I have the PyXml doc's You don't give any useful details about the problems you're having, so I'm not sure how anyone would be able to help you. FWIW: http://www.xml.com/pub/at/24 http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/pyxml-akara --Uche From andymac at bullseye.apana.org.au Fri May 21 19:48:34 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 22 May 2004 09:48:34 +1000 (EST) Subject: Python compilers? In-Reply-To: References: <30260531.0405180848.42e2919d@posting.google.com> <8089854e.0405210201.2a9b6de@posting.google.com> Message-ID: <20040522094717.R98726@bullseye.apana.org.au> On Fri, 21 May 2004, Svein Ove Aas wrote: > Peter Hansen wrote: > > > Actually, there are compilers that produce native machine code from > > Java for several CPUs available, and they are used at least in the > > embedded world. > > There is also GCJ as part of the GCC, which can compile both .class > and .java files. Its libraries aren't complete yet, but I'm sure it's > only a matter of time. Hmmm... anyone tried GCJ on Jython? -- 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 dmq at gain.com Thu May 6 07:50:39 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 06 May 2004 04:50:39 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> Message-ID: On Thu, 06 May 2004 18:12:18 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> Explanation of Instance Variables in Python >> ------------------------------------------- >> """ Some of the variables inside the functions in a class have a >> self. prefix. This is to distinguish local variables in the function >> from "instance variables". These instance variables will be found >> when the function is called... > >Just because a particular writer uses more waffle than >necessary to explain something about Python doesn't mean >the thing being explained is complicated enough to require >that many words. We disagree on what is "waffle" and what are beneficial extra words. Your explanation, to me, seems more like a "man page" than a textbook explanation. For a more complete discussion of this topic, with some alternative paragraphs, see the thread "Explanation of Instance Variables in Python", 4/28/04. -- Dave From http Tue May 11 16:09:28 2004 From: http (Paul Rubin) Date: 11 May 2004 13:09:28 -0700 Subject: Performance of cPickle module References: Message-ID: <7xpt9an2tj.fsf@ruckus.brouhaha.com> sh at defuze.org writes: > If I had to use a database, the database would keep track of my users and I > would only need to do a SQL statement. Would the cPickle more efficient in my > case than a database ? Not if you had more than a few users. Why don't you look at the dbm or shelve modules. The dbm module lets you store strings (including pickles) in a disk file that works like a hash table (much less hassle than messing with an SQL server). The shelve module uses dbm and handles the pickling automatically. Note that all these approaches have a terrible pitfall, which is what happens if the web page needs to update the database, say you want to let people automatically create their own user accounts through the site? If two people try to update the dbm file (or an xml file) simultaneously, things can get completely screwed up unless you're careful. The idea of a real database is to take care of those issues for you. Another thing you could do is put the session state in a browser cookie. Be careful when you do that though, since a malicious user could concoct a cookie that lets him seize some other user's session, or even takes over your server if you unpickle the cookie. The best way to handle that is encrypt the cookies. See http://www.nightsong.com/phr/crypto/p3.py for a simple encryption function that should be sufficient for this purpose. From jimmy at retzlaff.com Tue May 25 23:58:39 2004 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 25 May 2004 20:58:39 -0700 Subject: ANN: X10 FireCracker Module for Python version 1.0 Message-ID: The X10 FireCracker Module for Python is available at: http://www.averdevelopment.com/python/ This is a module for sending X10 commands via a FireCracker Computer Interface (CM17a). It can be called from Python code or used directly from the command line. Prerequisites: Any platform with Python 2.3 and pySerial 2.0. It has been tested on Windows XP, Windows Server 2003, and Mandrake 10. License: MIT This is the initial public release of this module. Jimmy From elainejackson7355 at home.com Thu May 13 19:21:19 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Thu, 13 May 2004 23:21:19 GMT Subject: images in tkinter Message-ID: Hi! I'm working on a script that displays images on Tkinter buttons, and I'd like to be able to do the following things: 1) Ensure that a button, whose 'image' attribute changes during execution of the script, stays the same size, but does not crop images that are larger than a predefined 'height' and 'width'. 2) Get the respective names and file-types of all of the image files in a given directory. (What I'm doing provisionally is reading the names out of a text file written specifically for that purpose, and so far they're all gif's, but I'd like to have more flexibility than that.) Any help will be greatly appreciated. Peace From __peter__ at web.de Thu May 20 12:17:47 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 May 2004 18:17:47 +0200 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: Skip Montanaro wrote: > Try > > u"".join(r) > > instead. I think the join operation is trying to convert the Unicode bits > in your list of strings to strings by encoding using the default codec, > which appears to be ASCII. This is bound to fail when the first non-ascii str occurs: >>> u"".join(["a", "b"]) u'ab' >>> u"".join(["a", chr(174)]) Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position 0: ordinal not in range(128) >>> Apart from that, Python automatically switches to unicode if the list contains unicode items: >>> "".join(["a", u"o"]) u'ao' Peter From ods at strana.ru Tue May 11 09:07:26 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 11 May 2004 17:07:26 +0400 (MSD) Subject: mx.DateTime bug? Message-ID: DateTime objects always compare equal to instances of user-defined classes: Python 2.3.2 (#1, Nov 27 2003, 18:07:14) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from mx import DateTime >>> DateTime.__version__ '2.0.3' >>> class c: pass ... >>> DateTime.now()==c() True Documentations states that "DateTime and DateTimeDelta instances can be compared and hashed, making them compatible to the dictionary implementation Python uses (they can be used as keys)", but there is at least race condition when instance of user defined class has the same hash value. Moreover, making DateTime objects to be always equal to instances with unknown nature is a bad idea. -- Denis S. Otkidach http://www.python.ru/ [ru] From pit.grinja at gmx.de Wed May 19 03:50:38 2004 From: pit.grinja at gmx.de (Piet) Date: 19 May 2004 00:50:38 -0700 Subject: GUI frontend for MySQL in wxPython References: Message-ID: <39cbe663.0405182350.7c25556f@posting.google.com> Paul McNett

wrote in message news:... > David Stockwell writes: > > I'm very new to python as well, but if you are looking to see > > what someone did as an example, take a look at > > http://www.tyomych-proj.narod.ru/readme.usage.htm > > PMFJI, but after reading that page I just had to mention Dabo > again in an act of shameless self-promotion, as it has > something that does what this Java program apparently does, yet > persists the output to a GUI application that you can run over > and over on the database, and customize to your needs. Admittedly, I didn?t yet have a closer look at dabo, but I had visited that page before. But for my purpose, dabo is probably "too much". What I wanted to develop originally was not mainly an app for graphical browsing of databases, but I mainly wanted to use python?s OO to create classes and functions that could be used by others for their own apps as well. For example, my program comprises five main classes (DatabaseServer, DatabaseQuery, Database, DatabaseTable and DatabaseTableRow) which IMHO make it a little easier to handle the functions provided by MySQLdb. I checked for such a bundle which is a little higher level than the MySQL driver, but haven?t found any. Does anybody know whether such a package exists? Best regards Piet From newsREMOVE at THISfb.wwd.ca Thu May 27 00:22:01 2004 From: newsREMOVE at THISfb.wwd.ca (=?ISO-8859-1?Q?Fran=E7ois_Bouffard?=) Date: Thu, 27 May 2004 00:22:01 -0400 Subject: Loggers and reloads In-Reply-To: References: <68fe96e8.0405261101.dd3cd14@posting.google.com> Message-ID: <1085631721.848347@www.vif.com> > I bet it > would also be possible to check if for a given logger already a handler is > registered, and refuse to add another one. You're completely right, thank you. There's always only one logger object in my code, however, each time the module is reloaded, a new handler is added. Therefore, something like: for h in logger.handlers: logger.removeHandler(h) indeed does the trick if I put it before the logger.addHandler() call. Thanks again. From russblau at hotmail.com Tue May 18 17:18:29 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 18 May 2004 17:18:29 -0400 Subject: alternatives to making blocks like { } or other ?? References: Message-ID: <2gvct4F7dsu9U1@uni-berlin.de> "Timo Virkkala" wrote in message news:Z1vqc.592$Xe5.151 at read3.inet.fi... > CYBER wrote: > > Is there any other way under python to create blocks ?? > > instead of > > def sth(x): > > return x > > could i use something else like > > def sth(x): > > { > > return x > > } > > Not without changing the language a lot. But just try the normal way for a > couple of days, you'll get used to it in no time. Or you could try this, which works almost exactly as well: def sth(x): # return x # -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From fumanchu at amor.org Wed May 19 10:48:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 May 2004 07:48:03 -0700 Subject: unique number generator Message-ID: Joe Wong wrote: > There is a constraint that the number can be at most 8 digits, ie: > > 00000000 ~ 99999999 > > No hex decimal is allowed... > > And I am on Linux platform.. > > Any other suggestion? :-) If you need to write your own, the core of it can just be a generator: def _unique(seed): i = 99999999 while i: yield seed % i i -= 1 id_gen() = _unique("") id_gen.next() id_gen.next() id_gen.next() ...then you have several mechanisms to share those numbers with consumer code, whether shared mem, lockfiles, sockets, whatever. You just need to ensure that the generator continues to run, because if you restart that process, you repeat numbers. For some apps, that might be OK. If it's not OK, modify the generator to save state somehow (shelve comes to mind) and pick up where it left off on restart. Robert Brewer MIS Amor Ministries fumanchu at amor.org From tezt at email.si Tue May 18 16:39:04 2004 From: tezt at email.si (Mitja) Date: Tue, 18 May 2004 22:39:04 +0200 Subject: Python compilers? References: <1mklty031ke5a.dlg@thorstenkampe.de> Message-ID: Thorsten Kampe (news:1mklty031ke5a.dlg at thorstenkampe.de) wrote: > * Tor Iver Wilhelmsen (2004-05-18 17:26 +0100) >> Grant Edwards writes: >> >>> Dude, didn't you take high-school math? 1/3 _is_ 0.33333... >> >> No, because at some point you will stop writing 3's, either out of >> boredom, exhaustion or because you need to pee. At that instant, you >> introduce a rounding error, making 3 * 1/3 = 0.99999999999... instead >> of 1.0 > > Must have been a long time since you went to school... 1/3 is > /exactly/ 0.3...: http://mathworld.wolfram.com/RepeatingDecimal.html > Even worse.... 0.999999999999999999999... is exactly 1 :) > Thorsten From kirk at eyegor.jobsluder.net Thu May 13 08:16:37 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Thu, 13 May 2004 12:16:37 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: On 2004-05-13, Andrew Dalke wrote: >> > Kirk Job-Sluder wrote: >> >> Write me a two-line script in python that reads a character delimited >> >> file, and printf pretty-prints all of the records in a different order. > > Carl Banks wrote one, convoluted so it can be on the command line. > Kirk Job-Sluder replied >> This looks like using the proverbial hammer to drive the screw. > > But you asked use to use the hammer to drive in the screw. In real > life I have more tools to use. For this case I would use Perl or awk. Bing, exactly the point. > My solution was to use the interactive Python shell. Something > like (untested) Certainly, python is the best solution for many problems. > > Trying doing that sanely with any programming language expressed > all on the command-line. No credit if you can't handle the '&' and space. Missing the point. The point was not that everything should be done using awk, sed or perl one-liners. The point was that there awk, sed, or perl one-liners are useful for a subset of tasks where the explicitness of python gets in the way. > > Andrew > dalke at dalkescientific.com > > From jjl at pobox.com Wed May 12 16:22:26 2004 From: jjl at pobox.com (John J. Lee) Date: 12 May 2004 21:22:26 +0100 Subject: Dabo 3-tier desktop framework for data-aware apps References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> Message-ID: <87pt99tmyl.fsf@pobox.com> john fabiani writes: [...] > I also have not discovered the way to print reports or any routines > that will generate the detail bands etc... But I have faith that they > are out there. I really hope that I don't have to hand code reports. 'Report' is a fairly broad concept. It sounds like 'report' means something quite specific to a VFP-er, though. If so, what would that be? John From davidf at sjsoft.com Mon May 17 06:55:08 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 17 May 2004 12:55:08 +0200 Subject: OPC Server in Python In-Reply-To: References: Message-ID: F. GEIGER wrote: > Hi all, > > I consider writing a control application in Python (realtime stuff would run > on hw, i.e. a PCI card). If I decide to do so, I'd like to provide access to > the control app's data for OPC clients. This means writing an OPC Server > (OPC DA). > > Could I do this in Python too? At the core an OPC Server is a COM server, > isn't it? Did anyone in this group do anything like that already? And if so, > are you willing to share your experience? I've tried to write an OPC server in Python, just for testing, I had a few bugs that I struggled to iron out but in the end I didn't need it so I never finished it, but it's definitely doable. The nice thing is you could then write an OPC client in Python to test it as well... > > Right now I'm trying to get more info about OPC, i.e. there are some > additional issues like OPC Groups and OPC Items and Browsing etc. > > Any books you would recommend? Other stuff to get me started quickly? I would recommend looking at Lab43's LightOPC which is a C implementation of OPC code available under LGPL, you can use it as examples... Start with a simple server, look at the OPC groups/items/browsing later... > > Any hint welcome! > > Kind regards > Franz GEIGER > Would be good to hear how you progress... David From dai4happy at yahoo.com Sat May 8 21:39:49 2004 From: dai4happy at yahoo.com (angel) Date: Sun, 9 May 2004 09:39:49 +0800 Subject: How python ActiveX to access DHTML document? References: Message-ID: Thanx, but you mistook my meanings. (1)I wrote ActiveX. (2)The ActiveX will be embed in a html page. (3)The ActiveX want to know the container html document's IDispatch pointer. Your solution can only create a new document, and then control it. Thanx again angel "Waldemar Osuch" ??????:c5b3dbee.0405081507.75d2125b at posting.google.com... > "angel" wrote in message news:... > > Hi > > > > I want to write an ActiveX by using python. And I know how do, but I don't > > know how python to access DHTML Document.If using cpp, it can be done by > > following source. > > /****/ > > CComPtr spContainer; > > m_spClientSite->GetContainer(&spContainer); > > CComQIPtr spDoc(spContainer); > > if (spDoc) > > spDoc->put_bgColor(CComBSTR(_T("pink"))); > > /****/ > > Who can tell me how to do the same in python? Thanx > > > > ps. I use win32com package. > > > > Thanx again > > angel > > Assuming you want to have HTML Document within IE following should > work from the command line. > > >>> from win32com.client import Dispatch > >>> ie = Dispatch("InternetExplorer.Application") > >>> ie.Visible = True > >>> ie.Navigate('about:blank') > >>> doc = ie.Document > >>> doc.bgColor = "pink" > > I would also recommend running Tools->COM Makepy utility from Pythowin > on Microsoft Internet Controls (for Internet Explorer) > and Microsoft HTML Object Library (for DHTML Document) > > waldek From iv at an.voras.fer.hr Wed May 12 14:11:15 2004 From: iv at an.voras.fer.hr (Ivan Voras) Date: Wed, 12 May 2004 20:11:15 +0200 Subject: if Request("something") == None: doesn't work In-Reply-To: References: Message-ID: Sam Sungshik Kong wrote: > if str(Request("something")) == "None": > works! > > Also, > if len(Request("something")) == 0: > works! > Try Response.Write(repr(Request("something"))) to see if you are really getting a None. From python-url at phaseit.net Wed May 26 16:36:44 2004 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 26 May 2004 20:36:44 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 26) Message-ID: <10b9vus8q0kne61@corp.supernews.com> QOTW: "This wouldn't be the first place where my fondness for things that work has gotten me into trouble ..." -- Nick Vargish, on Python "Typing is cheap. Thinking is expensive." Roy Smith Computer Associates International Inc. ... well, it's not clear *what* it's doing, apart from publicity, but one possible outcome is that thoroughly Pythonic Plone will suddenly become welcome in The Enterprise http://www.eweek.com/article2/0,1759,1599309,00.asp http://plone.org/foundation/announcement http://biz.yahoo.com/prnews/040524/nym203_1.html IBM now employs distinguished Pythoneer Mark Pilgrim http://diveintomark.org/archives/2004/03/01/blue Fernando Perez writes penetratingly on Python as a substitute for, say, bash for daily work http://www.scipy.net/pipermail/ipython-user/2004-April/000275.html Jacek Generowicz not only asks for agreement that "compiling dynamics languages ... can give significant speedups", but presents evidence for the proposition http://groups.google.com/groups?frame=left&th=d2348b3083caf371 "There Ain't No Such Thing As Plain Text" engages the passion of Paul Prescod, Roger Binns, and other experienced Pythoneers http://groups.google.com/groups?frame=left&th=161304412c3dd9a8 Riverbank Computing announces PyQt v3.12 http://www.riverbankcomputing.co.uk/pyqt/index.php The next General Assembly of the Python Business Forum will be on 9 June 2004 in Goteborg, at the end of EuroPython 2004 http://www.python-in-business.org http://www.europython.org/conferences/epc2004/pressreleases/update20040519 Kent Johsnon illustrates why Python's callbacks are better than Java inner classes http://www.pycs.net/users/0000323/weblog/2004/05/19.html#P46 Greg Wilson gives his vision of extensibility http://www.third-bit.com/~gvwilson/xmlprog.html ======================================================================== 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 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 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. *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 tjreedy at udel.edu Thu May 13 10:16:11 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 May 2004 10:16:11 -0400 Subject: Google and Python usage References: Message-ID: "Peter Hansen" wrote in message news:t62dndgNZ6u3bT_dRVn-hA at powergate.ca... > David M. Cooke wrote: > > > Everybody says Google uses Python, but I've never seen it... until I > > came across this, for the Google AdWords support page: > > > > https://adwords.google.com/support/bin/topic.py?topic=102 > > > > Is that a .py I spy? > > I guess so, but in any case the usual use of Python attributed > to Google is not something you *would* see, as it's always been > said to be on the back end, collecting and indexing the sites > in the first place, not on the front end. Nice to see their > use of it is growing even beyond that... I think it reasonable to suppose that they also use Python to prototype and test new features and algorithms that later get either discarded or recoded in C or whatever for speed. They rerun at least some programs enough times that recoding can pay off in reduced hardware costs. But their continued success depends on staying nimbly ahead of the competition. Terry J. Reedy From buzzard at urubu.freeserve.co.uk Sat May 29 11:22:00 2004 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 29 May 2004 16:22:00 +0100 Subject: UK Social research job to suit Excel programmer (not necessarily VBA) References: <40B8991F.4010207@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:40B8991F.4010207 at engcorp.com... > Duncan Smith wrote: > > > http://www.man.ac.uk/news/vacancies/research.html#581 > > Sorry, but what's the connection to Python? There is (I am told) a significant amount of work automating Excel. Unfortunately this isn't clear from the job description (I didn't write it). I know from experience that this can be achieved admirably using Python (and Mark Hammond's extensions). Personally I would like to see the work done in Python, but that depends on who applies and whether those who make the decisions can be convinced that it's an appropriate language (well, moreso than VBA). It's certainly not a full-time programming job (due to the social science / modelling component), but it does need someone who can write good maintainable code. Duncan From sarah.tanembaum at yahoo.com Wed May 5 19:19:52 2004 From: sarah.tanembaum at yahoo.com (Sarah Tanembaum) Date: Wed, 5 May 2004 19:19:52 -0400 Subject: Web programming ... References: <40990fd8$0$567$e4fe514c@news.xs4all.nl> Message-ID: I'm refering to HTML/XML Web application traditionally written with scripting language such as ASP, JSP, PHP, and Perl. Thanks "Chris Herborth" wrote in message news:nQ9mc.40413$ZJ5.1300352 at news20.bellglobal.com... > Irmen de Jong wrote: > > > Sarah Tanembaum wrote: > > > >> Is python good for creating Web application? > > > > Short answer: yes. > > Long answer: http://www.python.org/cgi-bin/moinmoin/WebProgramming > > I guess it depends on what you mean by "web application"... I've never been > able to find decent SOAP support, or something that can grok a WSDL file, > for example. > > -- > Chris Herborth chrish at cryptocard.com > Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ > Never send a monster to do the work of an evil scientist. From olli at secnetix.de Thu May 13 10:19:04 2004 From: olli at secnetix.de (Oliver Fromme) Date: 13 May 2004 14:19:04 GMT Subject: if Request("something") == None: doesn't work References: <10a57riii39q7d0@news.supernews.com> Message-ID: <2gheeoF2qf3pU1@uni-berlin.de> John Roth wrote: > "Sam Sungshik Kong" wrote: > > > > if Request("something") == None: > > Response.Write("") > > else: > > Response.Write(Request("something")) > > [...] > 2. However, the even easier way to do it is not to do > a check at all, but simply rely on the fact that both None > and the null string act like False in an if statement. In > other words, just remove the "== None" and see what > happens. Furthermore, in Python the result of a boolean operator is the value of the operand that has been evaluated last. So, the above if...else construct could be reduced to this simple (and very readable) line: Response.Write(Request("something") or "") Of course that assumes that the Request() really returns None, not a string with content "None". Best regards Oliver -- "To this day, many C programmers believe that 'strong typing' just means pounding extra hard on the keyboard." -- Peter van der Linden From stevenbee at removethis.part.att.net Tue May 4 16:41:56 2004 From: stevenbee at removethis.part.att.net (Steven Brent) Date: Tue, 04 May 2004 16:41:56 -0400 Subject: iter jitters Message-ID: Hi folks, In the snippet below, I'm trying to overload the __iter__ list method: def __iter__(self): print "using custom iter" counter = 0 end = len(self.data) - 1 while counter <= end: print self.data[counter] counter += 1 It pretty much works, except that the output is ugly when the while loop falls off the end of the list: >>> L3 = [1,2,3,'x','y',z'] >>> for item in L3: print item, using custom iter 1 2 3 x y z Traceback (most recent call last): File "mylist.py", line 38, in ? for item in L3:print item, TypeError: iter() returned non-iterator of type 'NoneType' Oh, yeah, plus it's adding a newline at the end of each item even though I've got the comma there. I'm gonna keep plugging away to see if I can figure this out, but stuff like this makes me frustrated... Thanks a million. From shalabh at cafepy.com Thu May 20 20:26:12 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Thu, 20 May 2004 17:26:12 -0700 Subject: Freeze and Resume execution References: <20040520125509.GS2112@zoran.com> Message-ID: Miki Tebeka wrote: > Hello All, > > I'm looking for a way to "yield" an exception. > > Background: I'm writing a hardware simulator. I have an output buffer > and need to freeze when it's full and then when called again to resume > execution from the point where it stopped. > > Currently all I can think of is to use a class and save the state when > throwing an exception. However this required manual book keeping of the > current state (and it is complicated). > > I'd like to use generators but can't see any "nice" way of doing it. > What I'd like it to throw an exception when the buffer is full and then > next time the generator is called to continue execution as after a > "yield". > > Is this possible? > Can you recommend a good way of doing this? Any state machine? Python generators yield to only one level up in the stack frame - i.e. the calling function. Exceptions, however, are thrown up the stack any number of levels, but there is no way to resume after that. What you could try is to yield and then call the generator again. If you want to pass information back and forth you can yield a mutable (like []), put values into it from the caller, and then call the generator again. If you want to yield multiple levels up the stack frame and later resume where you left off, you *might* want to look at stackless. It may or may not do what you want. > > Thanks. > Bye. -- Shalabh From phil at riverbankcomputing.co.uk Thu May 6 02:52:36 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 6 May 2004 07:52:36 +0100 Subject: PyQT developement for Windows In-Reply-To: <30260531.0405051915.48c7f478@posting.google.com> References: <30260531.0405051915.48c7f478@posting.google.com> Message-ID: <200405060752.36142.phil@riverbankcomputing.co.uk> On Thursday 06 May 2004 4:15 am, simo wrote: > Phil Thompson wrote: > > It's up to you how you license your own application so there is no > > problem with dual licensing it - the GPL and one that is compatible with > > a Windows version of Qt and PyQt. > > > > The problem is how do your users get a copy of Qt and PyQt? Depending on > > your circumstances, and those of your users, you have the choice of the > > non-commercial version (free but Qt v2 only), the educational version > > (free if you are an educational institution), or the commercial version > > (not free but you can redistribute Qt and PyQt to anybody with your > > application). > > Way too cryptic. To summarise: > > 1. To distribute *under any licensing terms* on Windows, you have to > buy commercial PyQt and Qt. > > 2. To distribute under GPL for Linux/Mac only *not Windows*, you can > use the GPL Qt/PyQt. > > 3. To distribute *commercially* for any platform, you have to buy a > commercial license. > > I'm pretty sure there is no currently available non-commercial v2 or > educational combination of PyQt/Qt that works anyway (like > non-commercial Qt 3.2.1 doesn't have a matching PyQt, only 2.x) The non-commercial v2 combatible version of PyQt will be restored with the next release of PyQt (sometime next week). The educational combination of PyQt/Qt is available and works fine. At Trolltech's request there will not be a version of PyQt released for the non-commercial release of Qt 3.2.1 (the "book" version). As of the next release there will be an evaluation version of PyQt that works with the evaluation version of Qt. Phil From brian at sweetapp.com Wed May 12 13:50:58 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 12 May 2004 19:50:58 +0200 Subject: ANN: Vancouver Python Workshop Message-ID: <40A26402.2030902@sweetapp.com> Vancouver Python Workshop ========================= The Vancouver Python and Zope User Group is pleased to announce the Vancouver Python Workshop. The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Paper proposals accepted: May 17th to June 15th Attendee registration: June 1st to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From rogerb at rogerbinns.com Mon May 3 21:46:39 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 3 May 2004 18:46:39 -0700 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com><246a4e07.0405012334.5e5474db@posting.google.com> Message-ID: > > ps What does B&D mean? > > Bondage and Discipline And the origin and definition of the term: http://www.catb.org/~esr/jargon/html/B/bondage-and-discipline-language.html Roger From rho at see.signature.invalid Tue May 11 03:32:04 2004 From: rho at see.signature.invalid (Nigel Rowe) Date: Tue, 11 May 2004 17:32:04 +1000 Subject: How to call a function from a shared library ? References: Message-ID: <40a07f32$0$2303$61ce578d@news.syd.swiftdsl.com.au> Tom Van Acker wrote: > Hello, > > I'm getting overwhelmed by information if I google this question. But > it is not clear to me. I have a shared library (.so file), created by > some other company we work with. Now I have to call a certain function > from this shared library. The declaration looks like this; > > int TransformPoints(void * vel_g, void* vel_i, void* vpoints, int nb) > ; > > Untill now, I was using the ctypes module to access this function. The > first two parameters are arrays[0..23] of type double and the third > parameter is an array[0..2] of type double. Using the ctypes module, > this works allright. > > But now I have to port this application to other platforms, and I > cannot use the ctypes module anymore (due to libffi incompatibility). > Is there another way to do this? > > Any help would be greatly appreciated. > > Tom Maybe Pyrex (http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/). -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From mogmios at mlug.missouri.edu Sat May 8 08:46:39 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 08 May 2004 05:46:39 -0700 Subject: Preferences Files In-Reply-To: References: Message-ID: <409CD6AF.3040403@mlug.missouri.edu> >Is there a good preferences modules for Python? I know that the Mac >version has one, but I need something cross-platform. > I'm not a Java person so possibly I'm misunderstanding you. I usually store preferences as Python and just load them into my program either with import or exec. From tor.iver.wilhelmsen at broadpark.no Sun May 2 06:55:57 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 02 May 2004 12:55:57 +0200 Subject: Looking at the next element in a for loop References: Message-ID: madsurfer2000 at hotmail.com (-) writes: > Is there a way I can get the next element in the loop? Something like this: > > for a in b: > if a == 1: > print No, not as long as you use an iterator. If you use an index instead, it's easy of course. for i in xrange(len(b)): if b[i] is 1: print b[i+1] From lbates at swamisoft.com Thu May 27 13:44:57 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 27 May 2004 12:44:57 -0500 Subject: How to I print without newline ? References: Message-ID: wrote in message news:mailman.364.1085670411.6949.python-list at python.org... > Hi ! > > I want to print, but without newline. I want to create a progress for > ftp, but the print is drop a newline for every percent. > I want like this: > > 0% 25% 50% 75% 100% > > But this happening: > 0% > 25% > 50% > 75% > 100% > > How to I prevent the newlines ? > > Thanx for help: > FT > > From temp1111 at hotmail.com Tue May 18 11:41:59 2004 From: temp1111 at hotmail.com (temp1111) Date: 18 May 2004 08:41:59 -0700 Subject: memory overflow, overlap PyMarshal_ReadObjectFromString Message-ID: Hi We are using embedded python in a C++ application We are seeing memory corruption with a number of OVL, OVF errors in mpatrol with PyMarshal_ReadObjectFromString on the stack Each stack trace has the following final 5 functions: 0xFDEA7008 __big_float_times_power+2268 0xFDEA8E34 __decimal_to_binary_fraction+156 0xFDEA9160 __decimal_to_unpacked+460 0xFDEAA5F0 decimal_to_double+572 0xFDEB4FC8 strtod+136 A sample full stack trace is given below. Any suggestions as to how to fix appreciated. We are using python 2.2.1 swig 1.1 Regards MEMCOPY: memcpy (0xFB3EDAF2, 0xFB3EDAEE, 16 bytes, 0x00) [11|-|-|-] 116 0xFDEA7008 __big_float_times_power+2268 117 0xFDEA8E34 __decimal_to_binary_fraction+156 118 0xFDEA9160 __decimal_to_unpacked+460 119 0xFDEAA5F0 decimal_to_double+572 120 0xFDEB4FC8 strtod+136 121 0xFE8FBD30 r_object+772 122 0xFE8FC164 r_object+1848 123 0xFE8FC600 r_object+3028 124 0xFE8FC164 r_object+1848 125 0xFE8FC600 r_object+3028 126 0xFE8FC164 r_object+1848 127 0xFE8FC600 r_object+3028 128 0xFE8FD1C4 PyMarshal_ReadObjectFromString+64 129 0xFE8FCC80 PyMarshal_ReadLastObjectFromFile+276 130 0xFE8EA3D4 load_source_module+388 131 0xFE8EAE44 load_module+148 132 0xFE8EBF68 import_submodule+364 133 0xFE8EB9D4 load_next+236 134 0xFE8EB548 import_module_ex+92 135 0xFE8ED2AC PyImport_ImportModuleEx+44 136 0xFE8ACE90 builtin___import__+92 137 0xFE8FD4D4 PyCFunction_Call+372 138 0xFE8A7C5C PyObject_Call+52 139 0xFE8B4914 PyEval_CallObjectWithKeywords+284 140 0xFE8B1E88 eval_frame+12796 141 0xFE8B3C14 PyEval_EvalCodeEx+2472 142 0xFE8B6688 PyEval_EvalCode+48 143 0xFE8E9EE0 PyImport_ExecCodeModuleEx+332 144 0xFE8EA544 load_source_module+756 145 0xFE8EAE44 load_module+148 146 0xFE8EBF68 import_submodule+364 147 0xFE8EB9D4 load_next+236 148 0xFE8EB548 import_module_ex+92 149 0xFE8ED2AC PyImport_ImportModuleEx+44 150 0xFE8ACE90 builtin___import__+92 151 0xFE8FD4D4 PyCFunction_Call+372 152 0xFE8A7C5C PyObject_Call+52 153 0xFE8B4914 PyEval_CallObjectWithKeywords+284 154 0xFE8B1E88 eval_frame+12796 155 0xFE8B3C14 PyEval_EvalCodeEx+2472 156 0xFE8B6688 PyEval_EvalCode+48 157 0xFE8E9EE0 PyImport_ExecCodeModuleEx+332 158 0xFE8EA544 load_source_module+756 159 0xFE8EAE44 load_module+148 160 0xFE8EBF68 import_submodule+364 161 0xFE8EB9D4 load_next+236 162 0xFE8EB548 import_module_ex+92 163 0xFE8ED2AC PyImport_ImportModuleEx+44 164 0xFE8ACE90 builtin___import__+92 165 0xFE8FD4D4 PyCFunction_Call+372 166 0xFE8A7C5C PyObject_Call+52 167 0xFE8B4914 PyEval_CallObjectWithKeywords+284 168 0xFE8B1E88 eval_frame+12796 169 0xFE8B3C14 PyEval_EvalCodeEx+2472 170 0xFE8B6688 PyEval_EvalCode+48 171 0xFE8E9EE0 PyImport_ExecCodeModuleEx+332 172 0xFE8EA544 load_source_module+756 173 0xFE8EAE44 load_module+148 174 0xFE8EBF68 import_submodule+364 175 0xFE8EB9D4 load_next+236 176 0xFE8EB548 import_module_ex+92 177 0xFE8ED2AC PyImport_ImportModuleEx+44 178 0xFE8ACE90 builtin___import__+92 179 0xFE8FD4D4 PyCFunction_Call+372 180 0xFE8A7C5C PyObject_Call+52 181 0xFE8B4914 PyEval_CallObjectWithKeywords+284 182 0xFE8A6F80 PyObject_CallFunction+280 183 0xFE8EC4CC PyImport_Import+648 184 0xFEA85F24 run__13PythonContextPcPPcT1T1+2692 185 0xFEA84B64 run__13PythonContextRCQ42ie3iel6engine7MessageRQ42ie3 iel6engine7MessagePcT3+372 186 0xFEA7F574 run__9IelPythonGQ42ie3iel6engine7MessageRQ42ie3iel6en gine7MessagePcT3+708 187 0xF9354D5C ??? 188 0xFEA9735C sendMsg__Q42ie3iel6engine6RouterRQ42ie3iel6engine7Mes sageT1RCQ24_STLt12basic_string3ZwZQ24_STLt11char_traits1ZwZQ24_STLt9allocator1Zw N23GQ42ie3iel6engine24TransporterInterface_var+14132 189 0xFEADA4AC send__21TransporterInterfaceIRCQ42ie3iel6engine15IelU nicodeChars+12060 190 0xFEAD5DCC send_skel__Q46POA_ie3iel6engine20TransporterInterface R17TAO_ServerRequestPvT2R17CORBA_Environment+328 191 0xFF230834 synchronous_upcall_dispatch__15TAO_ServantBaseR17TAO_ ServerRequestPvT2R17CORBA_Environment+336 192 0xFEAD7158 _dispatch__Q46POA_ie3iel6engine20TransporterInterface R17TAO_ServerRequestPvR17CORBA_Environment+48 193 0xFF23DF10 dispatch__30TAO_Default_Servant_DispatcherRQ218TAO_Ob ject_Adapter14Servant_UpcallR17TAO_ServerRequestR17CORBA_Environment+44 194 0xFF225C08 dispatch__18TAO_Object_AdapterR13TAO_ObjectKeyR17TAO_ ServerRequestG16CORBA_Object_outR17CORBA_Environment+316 195 0xFEE89384 dispatch__20TAO_Adapter_RegistryR13TAO_ObjectKeyR17TA O_ServerRequestG16CORBA_Object_outR17CORBA_Environment+92 196 0xFEEBABC4 process_request__21TAO_GIOP_Message_BaseP13TAO_Transp ortR12TAO_InputCDRR13TAO_OutputCDR+304 197 0xFEEBA53C process_request_message__21TAO_GIOP_Message_BaseP13TA O_TransportP15TAO_Queued_Data+428 198 0xFEDA4C38 process_parsed_messages__13TAO_TransportP15TAO_Queued _DataR17TAO_Resume_Handle+228 199 0xFEDA3E84 handle_input_i__13TAO_TransportR17TAO_Resume_HandleP1 4ACE_Time_Valuei+1284 200 0xFEDB9D18 handle_input__27TAO_IIOP_Connection_Handleri+336 201 0xFE1E6E84 dispatch_socket_event__14ACE_TP_ReactorR20ACE_EH_Disp atch_Info+132 202 0xFE1E6240 handle_socket_events__14ACE_TP_ReactorRiR18ACE_TP_Tok en_Guard+176 203 0xFE1E6D10 dispatch_i__14ACE_TP_ReactorP14ACE_Time_ValueR18ACE_T P_Token_Guard+160 204 0xFE1E5A20 handle_events__14ACE_TP_ReactorP14ACE_Time_Value+572 205 0xFE265854 handle_events__11ACE_ReactorP14ACE_Time_Value+48 206 0xFEE50D5C run__12TAO_ORB_CoreP14ACE_Time_ValueiR17CORBA_Environ ment+504 207 0xFEDFA4E4 run__9CORBA_ORBP14ACE_Time_ValueR17CORBA_Environment+ 36 208 0xFEDFA49C run__9CORBA_ORBR17CORBA_Environment+20 209 0xFEAE9F60 svc__10ThreadPool+408 210 0xFE21A220 svc_run__13ACE_Task_BasePv+224 211 0xFE1D7A74 invoke_i__18ACE_Thread_Adapter+100 212 0xFE1D79D0 invoke__18ACE_Thread_Adapter+108 213 0xFE1A5F98 ace_thread_adapter+24 214 0xFEBE57BC _lwp_start+8 From mkc at stowers-institute.org Mon May 10 17:30:18 2004 From: mkc at stowers-institute.org (Michael Coleman) Date: Mon, 10 May 2004 16:30:18 -0500 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> Message-ID: <85sme8ug0l.fsf@stowers-institute.org> Olivier Scalbert writes: > Jarek Zgoda wrote: >>Olivier Scalbert pisze: >> >>>What is the python way of doing this : >>>perl -pi -e 's/string1/string2/' file >> >>Use sed. >> > yes, but in python ? Jarek's answer is the correct one, for almost any real situation. For the purposes of exposition, though, a pythonic equivalent would be: import fileinput for l in fileinput.input(): print l.replace('string1', 'string2') If you want regular expression substitution and not just constant strings, use re.sub instead. Mike -- Mike Coleman, Scientific Programmer, +1 816 926 4419 Stowers Institute for Biomedical Research 1000 E. 50th St., Kansas City, MO 64110 From dygimailNo at SPAMpoczta.fm Fri May 14 14:23:48 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 14 May 2004 18:23:48 GMT Subject: Loop and the list References: <2gk3eeF3gha1U1@uni-berlin.de> Message-ID: Peter Otten <__peter__ at web.de> wrote in news:c82rsa$fie$03$1 at news.t-online.com: > There is no conceptual difference between functions and objects. You > can both bind them ad libitum: Understand. Thank a lot. > I'm a callable integer. Weird, n'est-ce pas? La vie est mysterieuse. ps Thanks for patience. -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From apardon at forel.vub.ac.be Thu May 6 07:16:15 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 May 2004 11:16:15 GMT Subject: A more flexible formatting proposal Message-ID: It is my impression that the python developpers haven't taken advantage of the Object Oriented nature of python when it comes to formatting: So I have the following proposal. Allow classes to have a special method __format__, that will be called when the object has to be represented in a specific format. A little example of how it could be used follows. Maybe instead of __format__ we could use the __str__ method for this. But then somekind of additional checking should be done to see if the __str__ method allows for an addition form argument or not. class fstring (str): def __mod__(self , args): strng = ' ' + self + 'a' result = '' si = 0 ai = 0 i = strng.find('%' , si) while i >= 0: if strng[i + 1] == '%': si = i + 2 result = result + '%' else: result = result + strng[si:i] for ti in range(i + 1 , len(strng)): if strng[ti].isalpha(): break if ti < len(strng) - 1: frm = strng[i : ti + 1] si = ti + 1 if hasattr(args[ai] , '__format__'): result = result + args[ai].__format__(frm) else: result = result + frm % (args[ai],) ai = ai + 1 else: si = ti i = strng.find('%' , si) result = result + strng[si:] return result[1:-1] return str.__mod__(self , args) class Int (int): def __format__(self, frm): nr = abs(self) if frm[-1] == 'b': res='' while nr > 0: res = `nr % 2` + res nr = nr / 2 return res else: return frm % (self,) Nr = Int(26) print '%f + %f = %f' % (3.2 , 1.4 , 4.6) print fstring('%f + %f = %f') % (3.2 , 1.4 , 4.6) print fstring('%b %o %x %d') % (Nr, Nr, Nr, Nr) From cookedm+news at physics.mcmaster.ca Tue May 4 14:58:17 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 04 May 2004 14:58:17 -0400 Subject: curses and python (linux, debian) References: <4jQlc.95615$YC1.6104179@phobos.telenet-ops.be> Message-ID: At some point, Guido wrote: > David M. Cooke wrote: > >> At some point, Guido wrote: >> >>>Hello >>> >>>I'm new to python and i'm trying to write a script that shows a menu. >>> >>>Now, I have some troubles with curses.setsyx() >>> >>>I do: >>> >>>import curses >>> >>>curses.setsyx(2, 20) >>>curses.putp("TEST TITLE") >>>curses.setsyx(25, 35) >>>curses.putp("TEST CENTER") >>>curses.setsyx(12, 35) >>>curses.putp("TEST CENTER") >>> >>>but it just prints all the string after each other at the first >>>lines.. >> Er, that's really the wrong way to do it. For one thing, curses.putp >> doesn't do what you think you want it to do. Have a look at "Curses >> Programming with Python": >> http://www.amk.ca/python/howto/curses/ >> Something like this: >> import curses >> def main(stdscr): >> stdscr.addstr(2, 20, "TEST TITLE") >> stdscr.addstr(25,35, "TEST CENTER") >> stdscr.addstr(12,35, "TEST CENTER") >> while 1: >> c = stdscr.getch() >> if c == ord('q'): >> return >> curses.wrapper(main) >> > > thx very much > > very handy tutorial! > > Now, i'm using DrPython, it looks fine, but i can't debug my curses > program > > It gives an error with this message: curses.wrapper returned ERR on > curses.cbreak I'm not familiar with DrPython, but it looks like a IDE. The console widget it uses for the Python shell probably doesn't support enough to be a 'real' terminal, so curses likely doesn't work in it. You'll have to run it in a terminal program like xterm. > if i run it with python, it works! >From the command line, right? There you go :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From chuck.amadi at ntlworld.com Mon May 31 11:34:18 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Mon, 31 May 2004 16:34:18 +0100 Subject: a python script which will parse an email message In-Reply-To: <40BB4E33.9030402@ntlworld.com> References: <40BB4E33.9030402@ntlworld.com> Message-ID: <40BB507A.5020900@ntlworld.com> chuck amadi wrote: > (Please include python-list/comp.lang.python on your mails. You'll > get more > useful feedback.) > > chuck> Hi Skip used your snippet - the above returns a > > chuck> Returned mail: see transcript for details > chuck> Returned mail: see transcript for details > > Assuming those are the subjects of the messages in > /var/spool/mail/chucka, > that looks fine. > > chuck> The second snippet - returns > chuck> Returned > mail: see chuck> transcript for details > chuck> Returned > mail: see chuck> transcript for details > chuck> When i less /tmp/subjects theres no data. > > What version of Python are you using? Maybe it's so old it doesn't > support > the > print >> openfile, ... > > construct, though if not, I'd expect a SyntaxError. Did you forget the > ">>"? > > Skip Yes I did but ran two versions . My version of python ruiing python -V is python 2.3 I will obviously check the version Im running on the mounted file server as opposed to my local machine which is also python 2.3 Cheers for your help by the way I have been reading Python Standard Library , Programming Python and Learning Python by O'Reilly So I will get the hang of this. off for a bath with Learning Python as my partner . Cheers all. > > > > From godoy at ieee.org Thu May 13 15:32:39 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 13 May 2004 16:32:39 -0300 Subject: Can I use dist-utils to install a sub-package? References: <40A3BCAA.3000905@noaa.gov> Message-ID: On Qui 13 Mai 2004 15:21, Christopher Barker wrote: > HI all, > > I'd like to be able to use distutils to install a package within the > wxPython package: > > wx.lib.MyPackage > > I want to be able to do this so folks can upgrade a package of mine that > is in the wxPython library, without changing it's location. > > In looking through the distutils docs, it looks like I cannot specify a > sub-package location for my package, It will only put it in > site-packages, not site-packages.wx.lib > > Is there a way to do this? Chris, Look at my previous post about distutils and RPM. I'm doing something like that, only that I'm copying files because they are not python scripts but images. And the other difference is that they are on my own package... You can try using the following construction: setup( name="name", version="0.1", (...) packages=['wx.lib.YourPackage'], package_dir = {'wx.lib.YourPackage': '.'}, (...) Here you tell that your package has the 'wx.lib.YourPackage' name and is located in the same directory as the setup script. You can put it somewhere else. I hope this helps. Be seeing you, -- Godoy. From rxv at hotmail.com Sun May 23 19:42:10 2004 From: rxv at hotmail.com (Ike) Date: Sun, 23 May 2004 23:42:10 GMT Subject: Jython direction please Message-ID: Can someone please point me to a good link for learning Jython. I have everything installed...I just cant even find how to simply open, list out, and save a source file. Thanks, Ike From bdecker at flowcom.com.au Mon May 3 22:54:07 2004 From: bdecker at flowcom.com.au (bdecker at flowcom.com.au) Date: Tue, 4 May 2004 02:54:07 +0000 (UTC) Subject: list as a base class in Python 2.1 Message-ID: <20040504125913.GC15311@flowcom.com.au> Hello, With python2.2 I am able to define a class based on the 'list' type as follows: class sample(list): ... But this doesn't work under python 2.1. Is there still a way to simply use the list type as a base class under python 2.1? Ben From aahz at pythoncraft.com Tue May 4 00:05:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 4 May 2004 00:05:26 -0400 Subject: is it possble to run a script from the python shell? References: Message-ID: In article , Darren Dale wrote: > >If so, how is it done? This is probably a stupid question. But when I >os.chdir into a directory that I know contains a python file, when I try >to call it > >>>>color_demo.py > >I get > >NameError: name color_demo is not defined Try >>> execfile('color_demo.py') -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From mcfletch at rogers.com Wed May 19 11:05:59 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 19 May 2004 11:05:59 -0400 Subject: How to just wait 3 secs ? In-Reply-To: <10amnvdih3rlud4@corp.supernews.com> References: <40AA2AFD.1080804@attglobal.net> <10amnvdih3rlud4@corp.supernews.com> Message-ID: <40AB77D7.8090709@rogers.com> Cameron Laird wrote: ... >>>I would like to make my script to wait 3 seconds ( so I can read the >>>output on the console ) >>>and then continue. >>>How do I do it ? >>> >>> ... >While time.sleep() certainly is correct at that level, >I'm concerned about whether it's the best advice we can >give. > ... I *try* to climb out of the muck and into the promised land ( ;) ) of XP and Cameron just pulls me back into the mire! Certainly, if you need a timeout on reading a file (i.e. stdin) then you're going to need more code, but he was explicitly looking for a pause to *read* what's on the console. Explaining the use of non-blocking IO and polling loops is rather too involved if someone just wants a 3-second pause :) ... or at least it's too involved for the amount of time I have to spend on it this week :) . I suppose I could have mentioned the use of raw_input as a first step toward interactivity, but then I'd have to do the timeout dance anyway, and I'm a fundamentally lazy person when I'm short on time (i.e. always) :) . Cameron, however, will be happy to right this wrong with a solid tutorial on the proper path to enlightenment :) ;) . Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From davidf at sjsoft.com Thu May 13 11:48:30 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 13 May 2004 17:48:30 +0200 Subject: ANN: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: References: Message-ID: Paul McNett wrote: > Hello Pythonistas, > > Ed Leafe and I have been collaborating on a new 3-tier framework > for creating cross-platform data-aware applications. While it > is still quite alpha, we decided to go ahead and announce it to > get a feel for what level of interest it would gather. > > The product's name is Dabo, and it will let you create > data-aware desktop apps for distribution to Mac, Linux, Unix, > and Windows computers. It is written in Python and wraps > the wxPython widgets, which is why we are announcing it here. > > Attached is the text of the complete announcement, but it is > kind of long. Please visit us at: > > http://dabodev.com My gzip doesn't like your dabo unix source tar.gz files ... are they OK? David From adeleinandjeremy at yahoo.com Sun May 2 21:01:46 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Sun, 2 May 2004 18:01:46 -0700 (PDT) Subject: Newbe-books Message-ID: <20040503010146.30900.qmail@web50308.mail.yahoo.com> I am no expert, but I would say that if you are new to Python and not new to programming, then what you really need is a straight-forward tour through each of Python's features, possibly in comparison to some other language(s). What you do not need (if my thinking is correct) is a book about programming using Python. Unfortunately, I doubt that such a book exists for the reason that a book geared towards presentation of language-specific features, and nothing more, would never make it on a list of good-sellers; the content exists in muliple places (most notably the standard Python documentation), and that content appeals mainly to people capable of, willing to, and preferring to turn to those alternative sources. With this in mind, I can suggest that there are two books that you definitely do not want to buy: _Python_How_To_Program_ by Dietel et al, and _Practical_Python_ by Hetland. Both of these cover programming in general - the former in a formal manner to introduce computing science, and the latter in a much lighter vein, with more Python-specificity. _Learning_Python_ is exceptionally good at covering many of the Python specifics, but I can't imagine that one could say that the book's presentation is optimal or even acceptable for someone who knows programming already - it just covers too many simple concepts. I can't imagine that the material presented needs to take more than 50 pages for an experienced programmer. So I would say don't buy this one either - except that it is better than _Programming_Python_ for presenting Python's language-specific features. I am unfamiliar with _Core_Python_, and I won't even claim to have gotten a good idea about it from my quick skim in a bookstore, but it did appear to be more about Python than about programming, and many others on this list have recommended it in the same category as _Learning_Python_. Also _Python_In_A_Nutshell_ sounds to be a good choice for your purposes, but again I am not very familiar with it. As I am not knowledgeable of either of these, I have to say that _Learning_Python_ is, of the books I know, the one I'd recommend - with the caveat that you will find yourself skimming over many sections and missing truly important points because they were buried among simple, basic concepts - but of course that is as it should be; it's meant for beginners. I have not suggested online documentation or Guido's tutorial (which are really the best resources for your situation), because I believe that as an experienced programmer you would for sure know about these already, and simply prefer hardcopy for those unfortunate circumstances when a computer is unavailable. HTH, - Jeremy __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From htx1 at gmx.de Fri May 14 05:55:21 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Fri, 14 May 2004 11:55:21 +0200 Subject: appending to dict In-Reply-To: <95f72778.0405140140.662d63fc@posting.google.com> References: <95f72778.0405140140.662d63fc@posting.google.com> Message-ID: bucket79 wrote: > why a.keys().append(3) makes 'None' ? Because .append modifies the list in place. It does not return a new list. > and is there anyway appending to dictionary? key/value pairs in a dictionary are not ordered. There is no "last pair". So you can't append to a dictionary. But you can update it with another dictionary. Use something like: adict.update (anotherdict) keys () returns a list of keys in the dictionary. The order of the elements in this list is arbitrary (or somehow ordered afterwards). But there is no real list of keys in the dictionary itself. Greetings, Holger From vincent at visualtrans.de Thu May 6 07:06:53 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 06 May 2004 13:06:53 +0200 Subject: prefix for installed scripts In-Reply-To: <8Vemc.384062$oR5.32412@pd7tw3no> References: <8Vemc.384062$oR5.32412@pd7tw3no> Message-ID: Kim Kulak wrote: > Hello, > > I've run into a small problem with my first python program. > > I'm writing this program on Debian Linux so python is installed in /usr > and sys.prefix is '/usr'. I've written a setup.py script and installed > my program and it's configuration data with prefix = '/usr/local'. It > installs exactly where I want it, but when I run my program 'sys.prefix' > is '/usr' (where python is installed) and not '/usr/local' (where my > program is installed. > > My question is: how do I find where _my_ program was installed? > > TIA, > Kim > > P.S. > Is anybody working on: "python setup.py uninstall" ? > How about os.path.split(sys.argv[0])[0]? HTH, Vincent Wehren From mva at sysfault.org Thu May 13 00:55:39 2004 From: mva at sysfault.org (Marcus von Appen) Date: Thu, 13 May 2004 06:55:39 +0200 Subject: __slots__ vs __dict__ References: <120520041314481389%JBrouwers@ProphICy.com> <86hdul2tad.fsf@sysfault.org> Message-ID: <86d659ylh0.fsf@sysfault.org> Andrew Bennetts writes: [...] >> # start >> class Foo (object): >> __slots__ = "_test" >> >> def __init__ (self): >> self._test = None >> >> if __name__ == "__main__": >> f = Foo () >> f.testvar = "test" >> return >> # end > > This code is a syntax error for me -- the final return isn't in a function. Sorry for that messy code - the return is absolutely wrong (no idea, why I put it there after typing the example in). >> Rebinding __slots__ in __setattr__ fails with a bus error on my system (it >> should not be possible anyways, because __slots__ is a tuple): >> >> # start >> class Foo (object): >> __slots__ = "_test", "_test2" >> >> def __init__ (self): >> self._test = 1 >> self._test2 = 2 >> >> def __setattr__ (self, name, value): >> # just test a simple rebinding >> self.__slots__ = self.__slots__ >> return >> >> if __name__ == "__main__": >> f = Foo () >> f.testvar = "test" >> return >> # end > > Also a syntax error. I also don't get a bus error, just infinite recursion > (because assigning to self.__slots__ calls __setattr__, but __slots__ isn't > an attribute of the instance). What version of Python, and what platform? Typed in a wrong line again here. Change it to something appropriate like def __setattr__ (self, name, value): # just test a simple rebinding self.__slots__.__add__ (tuple (name)) return > I'm guessing you're on something like FreeBSD where Python has had trouble > coping gracefully with infinite recursion. Right, but this was caused by typing in wrong code. Sorry for that. Regards Marcus -- We don't understand the software, and sometimes we don't understand the hardware, but we can *see* the blinking lights! From apardon at forel.vub.ac.be Tue May 25 06:30:03 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 May 2004 10:30:03 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: Op 2004-05-25, David MacQuigg schreef : > On 25 May 2004 07:39:49 GMT, Antoon Pardon > wrote: >> >>Well one possible view is that methods are just functions. The >>difference being that it is not exactly the function as it >>is defined in the class but as related function. Now I don't >>know if trying to explain methods from this point of view >>would be easier for students to understand and it may cause >>confusions of its own. But I think this approach deserves >>more attention you seem willing to give it. > > I don't feel I can make much improvement on Learning Python, 2nd ed. > I think this is the same approach that you are talking about - > functions first, then methods, one variation at a time. I don't think so. The apprach I'm thinking of would be about the following. 1) functions 2) bare classes (no methods) 3) higher order functions 4) show how higher order functions can result in method like beheviour 5) methods and show the connection with higher order functions. -- Antoon Pardon From nospam at here.com Sun May 16 04:14:33 2004 From: nospam at here.com (Richard Townsend) Date: Sun, 16 May 2004 09:14:33 +0100 Subject: Test error with Python 2.3.4c1 References: Message-ID: > self.getLineNumber() is None if I check using pdb, but what > disconcerts me is the > > File "/usr/local/lib/python2.3/site-packages/_xmlplus/sax/_exceptions.py", line 94, in __str__ > > line. Why is sax taken from the installed version instead of the > 2.3.4c1 version. I raised a bug report (864379) back in December or a similar problem with 2.3.3 on HP-UX - except there it caused a core dump. I too was surprised that it was accessing code in the current installation. The last response to the bug report suggested an incompatibility with PyXML-0.8.3, but since then there have been no further responses. From grante at visi.com Thu May 13 17:28:37 2004 From: grante at visi.com (Grant Edwards) Date: 13 May 2004 21:28:37 GMT Subject: struct doesn't handle NaN values? References: <10a7m0aj181spc5@news.supernews.com> Message-ID: On 2004-05-13, John Roth wrote: >> Perhaps I'm doing something wrong: the struct module docs say >> it's IEE 754, but I can't figure out how to get it to handle >> NaN values correctly (either packing or unpacking). > I believe that struct uses the c library as is, That's not what the docs say. The struct docs says it converts between native Python values and IEEE 754. If that's not the case and it converts between Python float format and "native C library" format, then the docs need to be changed [and I'll need to write something that converts to/from IEEE 754 format.] > like the float support in general. Unfortunately, that leaves > everyone at the mercy of the rather inconsistent and > ideosyncratic implementations of corner cases in existing c > libraries. But, my c library seems to handle it correctly: 1) 0xffffffff is treated correctly as a NaN. 2) NaN's are detected and converted to strings as 'nan'. Which part of the C library is broken? -- Grant Edwards grante Yow! AIEEEEE! I am having at an UNDULATING EXPERIENCE! visi.com From pit.grinja at gmx.de Tue May 18 16:08:46 2004 From: pit.grinja at gmx.de (Piet) Date: 18 May 2004 13:08:46 -0700 Subject: Making items visible in wxPython wxListCtrl Message-ID: <39cbe663.0405181208.1065933d@posting.google.com> Hi there. I am trying to display tabular data in a wxListCtrl. What I get from the script below are only the headers, not the items themselves. The documentation didn?t help me much; instead I was lost in ListItemId?s and different possibilities of inserting items and strings. I am sure the solution is only one step away, but I need somebody to point in the direction. Heres the script: from wxPython.wx import * class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,-1, title, style=wxDEFAULT_FRAME_STYLE) self.panel = wxPanel(self,-1) self.Lctrl = wxListCtrl(self.panel,-1,size=(200,200),style = wxLC_REPORT) for i in range(2): self.Lctrl.InsertColumn(i,"Column"+str(i),format=wxLIST_FORMAT_LEFT,width=100) self.Lctrl.SetStringItem(i,1,"Hi") self.Lctrl.SetStringItem(i,2,"there") self.Lctrl.SetItemData(i,1) app = wxPySimpleApp() frame = MainWindow(None, -1, "List Control Test") frame.Show(1) app.MainLoop() Best regards Peter From fumanchu at amor.org Tue May 4 00:16:13 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 3 May 2004 21:16:13 -0700 Subject: fixedpoint cmp conundrum Message-ID: I described a problem about list.index() and fixedpoint: > > >>> import fixedpoint > > >>> a = fixedpoint.FixedPoint(3, 2) > > >>> bunch = [None, 12, a] > > ... > > > >>> bunch.index(a) > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python23\Lib\fixedpoint.py", line 316, in __cmp__ > > xn, yn, p = _norm(self, other, FixedPoint=type(self)) > > File "C:\Python23\Lib\fixedpoint.py", line 482, in _norm > > y = FixedPoint(y, x.p) > > File "C:\Python23\Lib\fixedpoint.py", line 255, in __init__ > > raise TypeError("can't convert to FixedPoint: " + `value`) > > TypeError: can't convert to FixedPoint: None > > > > > > Mmrph! I could fix this by: > > > > 1. Iterating through "bunch" by hand and trapping TypeError, > > 2. Overriding or hacking the __cmp__ function in fixedpoint, or > > 3. Overriding or hacking the _norm function in fixedpoint > > > > The question is: given that there are multiple places to "fix" this, > > where should I do so? and Tim himself replied: > 4. Define an __eq__ method, which returns False if its arguments > are non-comparable. ...to which I can only say: Thanks! :) Nailed it. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ajsiegel at optonline.com Fri May 28 01:29:49 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 05:29:49 GMT Subject: terminological obscurity References: <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <1085718479.27401@yasure> Message-ID: <4sidb0lmlsscpg7j1ahm3459dkosoge3so@4ax.com> On Fri, 28 May 2004 04:28:00 -0000, "Donn Cave" wrote: >| Yet you insist, with a fresh start on all this, on using the >| terminology "homogenous data". > >Oh, well. You knew what he meant, though, didn't you? Not really. In fact to someone like myself who has a decent practical and intuitive sense of the use of lists in Python, the employment of this terminology seems almost like purposeful mystification. If he simply said "list" I would know what he was talking about. Better. And that was just as true when this thread started. As interesting - in some sense - as the discussion has been, and as wrapped up in it as I got, I realize I haven't learned anything actually useful. Did I take a detour. This is my impression more of how Lisp people like to spend their time :) Art From mail at hellmutweber.de Thu May 6 14:35:07 2004 From: mail at hellmutweber.de (Hellmut Weber privat) Date: Thu, 06 May 2004 18:35:07 +0000 Subject: Privacy In-Reply-To: References: Message-ID: <409A855B.40809@hellmutweber.de> Hi python list, the message I got had a file attached 'document.pif'. since I'm mailing with firefox under linux it did not do any harm. Maybe there is a possibility to prevent messages of this kind... Greetings from Munich Hellmut python-list at python.org wrote: > Still? -- Dr. Hellmut Weber Degenfeldstra?e 2, D - 80803 M?nchen-Schwabing tel (+49 89) 3081172, mobil (+49 172) 8450321 mail at hellmutweber.de ---------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: mail.vcf Type: text/x-vcard Size: 393 bytes Desc: not available URL: From curzio.basso at unibas.ch Wed May 12 03:52:23 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Wed, 12 May 2004 09:52:23 +0200 Subject: [numarray] mean vector of 2d matrix In-Reply-To: <3064b51d.0405110553.7ee2468a@posting.google.com> References: <409f9edd$1@maser.urz.unibas.ch> <3064b51d.0405110553.7ee2468a@posting.google.com> Message-ID: <40a1d7b7$1@maser.urz.unibas.ch> beliavsky at aol.com wrote: > With Numeric, one can use the 'average' function to compute the average along > an axis, or the average of all elements when the axis argument is set to None. > See p317 of Martelli's "Python in a Nutshell" book. For example, the code However, it looks like in numarray no average() is provided. Now I found out there is an average() function provided by the MA (Masked Arrays) module, but I do not really understand why there is an average() function for a masked array and not for a generic array... Anyway, thanks for the tip! From SeeBelow at SeeBelow.Nut Sun May 9 18:48:25 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sun, 09 May 2004 22:48:25 GMT Subject: What's the difference? Message-ID: <409EB546.B8367374@shaw.ca> between this: name = "C" and this: name = StringVar() name.set("C") I hope someone can explain that to me. Thanks, Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From dave at pythonapocrypha.com Sat May 22 14:10:51 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 22 May 2004 12:10:51 -0600 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> Message-ID: <05b801c44028$1e2dbd00$6500a8c0@YODA> David MacQuigg wrote: > If Python were consistent, and *always* used a special first argument, > there wouldn't be a problem. The magic first argument would be no > more difficult than magically setting a global variable. The problem > is that some methods require a magic first argument, and others > require that it *not* be there. In one case you call cat1.talk() and > in another it is Cat.talk(cat1). But the above explanation misses one very important point: one is used 99.9% of the time, the other 0.1% of the time, if that. Mentioning them side by side like you do implies that they are both equially common, which is not remotely the case. > I know this is not terribly > difficult to understand -- one is a bound method, the other unbound. > Still it is a problem for beginners, and it leads to unecessary > complexities like static methods. I don't see how this is at all related to static methods. A method is some piece of functionality that is specific to a particular class. If you have some function already lying around, why would you want it as a method, much less a static method? (I can think of a couple of rather contrived examples, but nothing compelling or common in a normal application - help me out here) > The recent discussion on "Method binding confusion" 5/2/04 shows that > even experts can get confused. Here is the example, reduced to its > simplest terms: [snip example that IMO doesn't reflect any sensical use case] > How would you explain this to non-CIS students in a class on circuit > design, where there is very little time to discuss programming? What kind of an instructor would bring this up in an introductory programming course? If you're short on time, there are oodles and oodles of more commonly used topics to cover. I find the current distinction between methods and functions as one that makes quite a bit of sense. It doesn't really cause problems, and I've yet to see a proposal that is cleaner while still making as much sense (IOW, perhaps it IS imperfect, but I can't think of anything better, and apparently nobody else can either). Most importantly, I've yet to see it cause any real or lasting problems for beginners - either (1) nobody cares unless you point it out and make an issue out of it, or (2) they ask, you take 30 seconds to explain it, and they say, "oh, ok" and move on. Occasionally someone particularly bright (and/or with experience in certain other languages) will really grasp the 'why' behind the difference, and you'll see the light go on as they begin to understand the power available to them. -Dave From ed at leafe.com Wed May 19 16:30:42 2004 From: ed at leafe.com (Ed Leafe) Date: Wed, 19 May 2004 16:30:42 -0400 Subject: n-tier application in Python In-Reply-To: <2h1hljF7u74vU1@uni-berlin.de> References: <2h1hljF7u74vU1@uni-berlin.de> Message-ID: <6648C0E4-A9D3-11D8-845A-003065B11E84@leafe.com> On May 19, 2004, at 12:50 PM, Kornl wrote: > Hello, does anyone has any experience in developing n-tier > applications in > python? If yes would you like to share your experience? What turn out > good > and bad?? I have taken my experience with n-tier application development and used it to develop a 3-tier framework for Python application development. The project is called Dabo, and is currently in early alpha release. There are several working examples available to download, so that you can get a feel for what apps written in Dabo might be like. Check it out at the second URL in my sig. We currently use wxPython for the UI, and MySQL for the backend, but plans are to support a wide range of UIs and databases, with the middle-tier logic remaining intact. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From sylphaleya at gmx.net Tue May 25 09:11:01 2004 From: sylphaleya at gmx.net (Manuel Huesser) Date: Tue, 25 May 2004 15:11:01 +0200 Subject: XML-RPC - instance Message-ID: Currently it's possible to register a single functions or a an instance in the standard XML-RPC library. Is there a possibility to refer to a different instance, like in a session. Should be possible with HTTP/1.1, but I haven't an idea. If not with XML-RPC, are there other ways. Thanks From tor.iver.wilhelmsen at broadpark.no Tue May 18 11:26:57 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 18 May 2004 17:26:57 +0200 Subject: Python compilers? References: Message-ID: Grant Edwards writes: > Dude, didn't you take high-school math? 1/3 _is_ 0.33333... No, because at some point you will stop writing 3's, either out of boredom, exhaustion or because you need to pee. At that instant, you introduce a rounding error, making 3 * 1/3 = 0.99999999999... instead of 1.0 From michele.simionato at poste.it Sat May 15 09:00:28 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 May 2004 06:00:28 -0700 Subject: Stackless python and microthreads References: <95aa1afa.0405140121.52a6d8e0@posting.google.com> <95aa1afa.0405142053.76ae0818@posting.google.com> Message-ID: <95aa1afa.0405150500.5fe3674b@posting.google.com> Andrew Bennetts wrote in message news:... > FWIW, Twisted will be using Zope 3's interfaces framework soon Aha! It seems clear that I have to find the time to start studying Zope interfaces then .... Michele From aahz at pythoncraft.com Thu May 6 00:09:24 2004 From: aahz at pythoncraft.com (Aahz) Date: 6 May 2004 00:09:24 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: In article , Andrew Bennetts wrote: > >I realise I'm sounding repetitive here, but: The only barrier is being able >to submit a bug to the bug tracker. It's not even a particularly large barrier; SF finally fixed things so that Lynx can be used to submit bugs. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From jcarlson at uci.edu Thu May 13 11:25:55 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 13 May 2004 08:25:55 -0700 Subject: Scope rule pecularities In-Reply-To: References: Message-ID: >>The real thing to remember is that Python isn't >you expect Python to behave like>, > > I think it is reasonable to expect a language to behave consistently. > > I would like to be able the understand what += does to > an object without the need of knowing it is mutable or > not. Well then, that is easy, += does whatever the object says it should do. The only builtin type that is actually modified in place (via +=) are lists. Everything else uses single name rebinding. Is that a simple enough rule, because had you done /any/ sort of critical investigation, you would have discovered it yourself. Your investigation would have turned up that immutables behave as they should, and a list's __iadd__ method is an alias for its extend method. >>>I now expect a and c still to be the same object. >> >>If 'a' is mutable, and 'a' has the proper __iadd__ operator, then 'a' >>and 'c' will be the same object when you are done. However, integers, >>strings, floats,... are immutable, so 'a' and 'c' won't be the same >>object in those cases (Python only rebinds objects that are specified, >>due to the whole "explicit is better than implicit" Zen). > > Python does more than enought things in an implicit way. And automatically rebinding /every/ name that references an object is more explicit? I don't think so. If all you can say is, "I don't like it, it should be more consistant", then I ask, "what would be more consistant?" Should we keep a list of every name that references an object so that functionally, everything is passed by reference and can be modified at will? Should we force everything to be mutable, only interning (and making immutable) objects used as keys in a dictionary? Honestly, I don't believe either option is a good idea. Let us look at an example and find out why. Hmmm, dictionaries. Dictionaries are hash tables that contain a key and value pair. In order to handle dynamic expansion of the hash table, we must keep the key (Python keeps a pointer to the key, it is much faster that way). Right now, only immutables are able to be keys. Why is this so? Let us imagine that we use a mutable string as a key in a dictionary. Everything is fine and dandy, until we modify the string. At that point, in order for the dictionary to stay consistant, we must make a copy of that string to keep it as a key. No big deal, right? Wrong. What if that string were 500k? 500M? It becomes a big deal. Similarly, rebinding all names that point to an immutable, when that immutable is modified via += is a fool's errand, /especially/ when we can use l = 1000000*[0]. According to the rebinding method, all million pointers would need to be rebound to the new object, which would be the same as making an integer mutable, which has the problem described in the previous paragraph. I think you'll find Python's handling of all immutable values to coincide with how C handles single integers (except for the pass-by-reference in function calls). >>and your expectations are not what >>actually happens. What you think /should/ happen is not what /does/ >>happen, and I am quite sure it is not what /Guido thinks should happen/. > > So? Is what Guido thinks should happen above criticism. I think > that if what Guido thinks should happen makes the language > behave inconsistenly then No, Guido is not above criticism. The mistakes he believes he has made will be fixed in the 3.0 release. If you can't wait for it, then perhaps you should write the interpreter/compiler for the language you want to use. It seems to be in vogue these days. - Josiah From michele.simionato at poste.it Wed May 5 00:19:23 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 4 May 2004 21:19:23 -0700 Subject: Unification of Methods and Functions References: <4n4d905eflq6ekrutjmrg3t6llk2b8lab7@4ax.com> Message-ID: <95aa1afa.0405042019.5a94e0ed@posting.google.com> Greg Chapman wrote in message news:... > On Mon, 03 May 2004 11:44:06 -0700, David MacQuigg wrote: > > >It seems to work in Michele Simionato's 'prototype' module. > >{ comp.lang.python, 4/28/04, "Prototypes in Python"} It is global > >only to the called function, but the key requirement is met -- no > >alteration of the standard function calling sequence. > > > >Why can't it be a true global? > > If I understand correctly, one drawback of his approach is that methods cannot > rebind globals. A STORE_GLOBAL opcode will store its value into the globs > dictionary created when the method was fetched; this dictionary is not the same > as the module's dictionary, so the changed global will only be visible within > that method (and within that method call: the next time the method is fetched, a > new globs will be created). > > --- > Greg Chapman I believe you are right (haven't checked yet) but I guess I can always change the globals from inside the method with something like currentmodule=sys.modules["__name__"] currentmodule.myglobal="something" Not that changing globals from a method is good style. BTW, I do agree that my hack is an evil hack, the interesting thing about it (for me) was the fact that inside the method I could use "super.method(*args)" instead of the ugly "super(cls,self).method(*args)" syntax. I didn't think that was possible at all. I just wonder if it would be technically possible to implement something like that in C with a decent performance (maybe caching the method access). What do you think? Michele Simionato From ddenholm at theworld.com Sun May 9 15:24:12 2004 From: ddenholm at theworld.com (D Denholm) Date: 9 May 2004 12:24:12 -0700 Subject: problem with PYTHONPATH on WinXP Message-ID: I recently installed Python 2.2 on my WinXP box. I am having problems figuring out how to create the PYTHONPATH correctly. I went to the WinXP SystemProperties > Advanced > Environment Variables and created a System Variable called PYTHONPATH with the value: G:\Python22\lib\site-packages\Pythonwin; G:\Python22\lib\site-packages\win32; G:\Python22\lib\site-packages\win32\lib; G:\Python22\lib\site-packages; G:\Python22\DLLs; G:\Python22\lib; G:\Python22\lib\lib-tk; G:\Python22; G:\Python22\lib\site-packages\Numeric; G:\cvslocal; G:\cvslocal\sim\cmd But when I run Python from the DOS Command Line, import sys, and then print the sys.path variable, the path does not contain the last directory entry: G:\MySim42>python Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 >>> import sys >>> sys.path ['', 'G:\\Python22\\lib\\site-packages\\Pythonwin', 'G:\\Python22\\lib\\site-pac kages\\win32', 'G:\\Python22\\lib\\site-packages\\win32\\lib', 'G:\\Python22\\li b\\site-packages', 'G:\\Python22\\DLLs', 'G:\\Python22\\lib', 'G:\\Python22\\lib \\lib-tk', 'G:\\Python22', 'G:\\Python22\\lib\\site-packages\\Numeric', 'G:\\cvs local'] >>> Note that the sys.path contents are the same (taking into account the differing syntax) as the PYTHONPATH value EXCEPT for the last directory: "G:\cvslocal\sim\cmd" I have tried several times but the last entry never shows up... Also, I have tried deleting the PYTHONPATH enviroment variable completely but the sys.path does not change. Any suggestions or explanations would be appreciated. --Doug From klappnase at web.de Thu May 20 17:30:37 2004 From: klappnase at web.de (klappnase) Date: 20 May 2004 14:30:37 -0700 Subject: Unknown Tkinter bug References: Message-ID: Krzysztof Szynter wrote in message news:... > > After i close graphcial window, shell gives this error message: > > ---BEGIN > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Program Files\Python232\lib\lib-tk\Tkinter.py", > line 1345, in __call__ > return self.func(*args) > File "C:\Program Files\Python232\lib\idlelib\ScriptBinding.py", > line 157, in run_module_event > interp.runcode(code) > File "C:\Program Files\Python232\lib\idlelib\PyShell.py", > line 658, in runcode > self.interp.restart_subprocess() > AttributeError: ModifiedInterpreter instance has no attribute 'interp' > ---END > > Where should i look for a mistake? Here's what I get when I run your example: Traceback (most recent call last): File "/usr/local/share/test.py", line 19, in ? while x<450 or y<450 : NameError: name 'x' is not defined you actually use a couple of other variables that are not defined, too, so I think this is maybe not the complete code ? Maybe you should have a look at the rest of the code if you have problems. BTW, the traceback you posted seems to look like an IDLE problem rather than a Tkinter bug I think (at least PyShell.py is the main file that runs IDLE's Shell window). Regards Michael From eurleif at ecritters.biz Sat May 15 11:19:00 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 15 May 2004 15:19:00 GMT Subject: Input Types In-Reply-To: References: Message-ID: EAS wrote: > How do you make a loop where the program keeps asking for > an integer or float until it gets one? (No letters or other input.) import sys # We need sys.stdin for input while True: # Infinite loop. We break out of it after getting a float. try: # For catching the exception of getting an invalid float. num = float(sys.stdin.readline().rstrip("\r\n")) # Try # parsing it as a float. break # If we reach this line, it's valid. Exit the loop except ValueError: # It's an invalid float. pass # Just let the loop run again. From jbors at mail.ru Thu May 27 17:55:08 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Fri, 28 May 2004 01:55:08 +0400 Subject: Stackless python and microthreads In-Reply-To: <40B66057.7040200@stackless.com> Message-ID: > This is true. For performance comparison reasons, and to make > Stackless "complete" in a way, I just developed real thread support > and measured context switch speed. Now it is not longer a claim, > but the truth (going to be Stackless 3.1): > > Stackless soft-switched channels are 10 times faster than > using real threads. > > Stackless tasklets are 10000 times smaller than threads on Windows. > Chris, I was interested in measuring performance with some apps I have around here. I think I should recompile pygame for it as it crashes. Did you try pygame with stackless ? Any clue if it works ? Thanks, Dmitry/ From phrogeeb at hotmail.com Sat May 22 15:02:09 2004 From: phrogeeb at hotmail.com (Uri) Date: 22 May 2004 12:02:09 -0700 Subject: Reading a file, sans whitespace Message-ID: <8a0bb987.0405221102.dc679ff@posting.google.com> I have a file that looks like this: (but longer, no wordwrap) Name: Date: Time: Company: Employee Number: Jim 2.03.04 12:00 JimEnt 4 Steve 3.04.32 03:00 SteveEnt 5 I want to load 'Jim' and '12:00' and those types of answers into variables in my program, the only delimiter in the file is whitespace. How do I do this? I can do it with string.split(" ",[0]) type line for a file that's only delimited by single spaces, but when I'm searching for white space, how do I do it? THanks! From premshree_python at yahoo.co.in Sun May 9 17:48:26 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Sun, 9 May 2004 22:48:26 +0100 (BST) Subject: Watch That Post Message-ID: <20040509214826.35453.qmail@web8308.mail.in.yahoo.com> Hello, I recently posted a simple Python script--Watch That Post--that lets you watch a URL for any changes. I wrote it to watch posts on LiveJournal, but it can watch any URL. It's at http://premshree.seacrow.com/code/python/watch -Premshree Pillai ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From jai_uw at yahoo.com Tue May 4 01:56:06 2004 From: jai_uw at yahoo.com (jai_uw) Date: Tue, 04 May 2004 05:56:06 -0000 Subject: python CGI scripting Message-ID: Hello, I am trying to do CGI scripting with Python, but I have a slight constraint. I do not have the CGI module installed on my machine. Is there anyway I can still do CGI scripting in Python without the CGI module installed? I don't have root access to the linux machine I am on, and so I won't be able to install the Python CGI module. All I need to do is access the text box fields of an html form in a Python script. The CGI module makes this really easy, as we can import CGI, but I was wondering if anyone knows a way to do this without using the CGI module. Any input would be greatly appreciated. Thanks, Jai Modi From hans at zephyrfalcon.org Sat May 22 13:10:38 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 22 May 2004 13:10:38 -0400 Subject: wxPython about event function In-Reply-To: References: Message-ID: <40AF898E.9080301@zephyrfalcon.org> RolleXu wrote: > class container(wxPanel): > self.compnt is a control > > the event func: > > EVT_LEFT_DOWN(self,self.OnLeftDown) > > when click container > self.OnLeftDown will be called > when click self.compnt > self.OnLeftDown won't be called > > please tell me > why? > and how to call the func, both case? Well, you attach the event to 'self', which is the container. You probably want: EVT_LEFT_DOWN(self.compnt, self.OnLeftDown) HTH, -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From miki.tebeka at zoran.com Wed May 5 10:38:34 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 5 May 2004 16:38:34 +0200 Subject: Several questions about embedding Python In-Reply-To: References: Message-ID: <20040505143834.GE1712@zoran.com> Hello Cameron, > I don't know how to debug, in this sort of embedding context > in particular; the reason you cite is a good example of why. Currently what I do is: from pdb import run ... def main(): ... if __name__ == "__main__": run("main())" If you have a .pdbrc in the current directory of the module you can set breakpoints to it and it'll be loaded at import time. When you hit a breakpoint the program will stop and you'll be in pdb prompt. > I sit and think a lot, so that I understand what my applica- > tions do. I don't use debuggers. I'm still undecided about > whether it's helpful for me to confess that. I agree. However there are times when a debugger is priceless, I found it help mainly with "stupid" bug (such as forgetting to declare "global", misspelling ...). > Yes, you can use pure SWIG wrappers. I'll be more precise: it > *sounds* as though you're saying SWIG is only for extending Py- > thon, and not embedding Python. This is false; SWIG can be used > to embed Python. Maybe there's a problem with use of SWIG in a > particular approach to embedding; just from what you've written, > though, I think it's reasonable to expect success with SWIG's > use. How? As I understand it SWIG will produce a DLL (sadly it's win2k). I need that this DLL will share some data with the main application, don't have a clue on how to do this. Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From tjreedy at udel.edu Tue May 18 12:04:22 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 May 2004 12:04:22 -0400 Subject: error converting list to tuple References: Message-ID: "Stefan Seefeld" wrote in message news:a3qqc.34397$325.832599 at news20.bellglobal.com... > (I call this code from within a C++ extension module), You should have said that in the beginning since that is a whole different ball game: extension modules in C are not Python. > so I'm wondering whether I could have messed up the > python runtime somehow or whether there are other > possible explanations for the exception. It is easy to mess up in C ;-). You are most likely to get an answer (from another C extension writer) if you post a short as possible code snippet that exhibits the error, and the actual and complete error message. tjr From skip at pobox.com Mon May 3 17:15:47 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 3 May 2004 16:15:47 -0500 Subject: Python CSV DictWriter Problems In-Reply-To: <409663B5.90102@mediapulse.com> References: <40966026.70600@mediapulse.com> <409663B5.90102@mediapulse.com> Message-ID: <16534.46723.35707.92255@montanaro.dyndns.org> Gabriel> Is there a known-bug in csv.DictWriter? It is ignoring my Gabriel> attempts to specify a Dialect. It doesn't even error if you Gabriel> give it anything invalid. I can send it the registered Gabriel> string-name of the dialect, a string of gibberish, a dialect Gabriel> object instance, a dialect class object... it accepts all and Gabriel> ignores all. Fixed in CVS I believe. I will check when I get a chance (there doesn't seem to be a test case for this), but you might try grabbing the DictWriter class from the csv.py that's in CVS. Skip From icemon999 at yahoo.com Tue May 18 14:50:44 2004 From: icemon999 at yahoo.com (mr. ice) Date: 18 May 2004 11:50:44 -0700 Subject: onverting c++ to phyton Message-ID: Hi Phyton guru out there, I am looking for a tools to translate some code written in c++ to phyton. I understand there may not be a perfect match but any suggestion is welcome. mr. Ice From Joseph.V.Laughlin at boeing.com Tue May 4 15:50:54 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Tue, 4 May 2004 12:50:54 -0700 Subject: Setting CPU Affinity Message-ID: <67B3A7DA6591BE439001F2736233351202876F7E@xch-nw-28.nw.nos.boeing.com> > From: Mark Hammond [mailto:mhammond at keypoint.com.au] > Sent: Tuesday, May 04, 2004 4:52 AM > To: python-list at python.org > Subject: Re: Setting CPU Affinity > > > Laughlin, Joseph V wrote: > > When I spawn a new process via spawnv(), how can I set the CPU > > affinity for the newly-spawned process with python? > > The pywin32 (win32all) extensions include the win32 functions > for this > in the win32process module. You should be able to: > * use spawmv to get the new process ID. > * use win32process.OpenProcess() to get a process handle. > * use win32process.SetProcessAffinityMask() to set the affinity. > > Mark. > -- > http://mail.python.org/mailman/listinfo/python-list > What about on a unix/linux platform? Thanks, Joe From paddy3118 at netscape.net Sun May 9 16:19:39 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sun, 09 May 2004 21:19:39 +0100 Subject: perl to python In-Reply-To: <409e8a04$0$22988$a0ced6e1@news.skynet.be> References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> Message-ID: <7nwnc.21730$4m5.19369@front-1.news.blueyonder.co.uk> Olivier Scalbert wrote: > Jarek Zgoda wrote: > >> Olivier Scalbert pisze: >> >> >> >>> What is the python way of doing this : >>> perl -pi -e 's/string1/string2/' file >>> >> >> >> Use sed. >> >> >> > yes, but in python ? I wonder what the motivation behind your question is? Do you have Python and not Perl or sed available? Is the request from part of a larger conversion task? Do you just want to compare the Perl to the Python solution? Pad. From sorry at but.no.spam Mon May 17 12:42:53 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Mon, 17 May 2004 19:42:53 +0300 Subject: This program makes Python segfault - no other does References: Message-ID: On Mon, 17 May 2004 10:57:55 -0400, Terry Reedy wrote: > Based on posts over several years, seq faults most often arise from > 1. buggy compilers, especially at 'higher' optimization settings Compiler is gcc 2.95.4, with the debug optimization ("make OPT=-g"). > 2. buggy compiled extensions There seems to be one potential segfault waiting there, if PostGreSQL gives suitably malformed Bytea string, but it has nothing to do with this. > 3. byte code fiddling > and only occasionally from > 4. Python interpreter bugs > which the developers consider high priority for squashing. Well, what do you think, should I report this ? Because I can't find anything wrong with the extension code - not that my C skills are that great, but still. >> Specifically, I'm wondering if my habit of reusing old variable names in > a >> function once they are no longer needed might be causing the trouble; >> maybe it causes confusion on the variable type ? > > Very dubious to me; at worst you should get an exception with traceback. Yup, wasn't that; there's something fishy happening at Python memory management code, apparently. >> So, here's the program. Does anyone know what's wrong with it ? > > Since you don't seem to be fiddling with internals, there is no way I know > to eyeball the code and tell which line is doing the 'impossible'. So I The conn.getvalue() -lines. Specifically, getvalue() on a Bytea field seems to be the cause of the problem, triggering the segfault on some lines. > think it up to you to determing the offending line by uncommenting print > statements and adding more as needed. Then see if you can reduce the > program and still get segfaults. I did, that's why the print lines are there. I'm sorry I didn't think to include the info from the start... Anyway, here's gdb stacktrace, if anyone's interested. The problem is not in unQuoteBytea, which works fine untill it tries to discard some temporary variables, at which point, kaboom. That would seem to indicate either line #2 or #3, but this is the first time I've used a debugger, so I might be quite wrong. #0 0x400c4c1b in free () from /lib/libc.so.6 #1 0x400c4aa3 in free () from /lib/libc.so.6 #2 0x0807ff2e in PyObject_Free (p=0x81d7240) at Objects/obmalloc.c:774 #3 0x0807f5a6 in PyMem_Free (p=0x81d7240) at Objects/object.c:2111 #4 0x4023a2d4 in unQuoteBytea (sin=0x81dd2ec ">nemo wrote:") at libpqmodule.c:417 #5 0x40243c2f in libPQgetvalue (self=0x401dfe00, args=0x401ea74c) at pgresult.c:630 #6 0x080fede0 in PyCFunction_Call (func=0x401eabcc, arg=0x401ea74c, kw=0x0) at Objects/methodobject.c:73 #7 0x080b7d4a in call_function (pp_stack=0xbffff2f8, oparg=2) at Python/ceval.c:3439 #8 0x080b50e0 in eval_frame (f=0x81dcbd4) at Python/ceval.c:2116 #9 0x080b7ff3 in fast_function (func=0x401ed294, pp_stack=0xbffff448, n=2, na=2, nk=0) at Python/ceval.c:3518 #10 0x080b7e2d in call_function (pp_stack=0xbffff448, oparg=2) at Python/ceval.c:3458 #11 0x080b50e0 in eval_frame (f=0x818d16c) at Python/ceval.c:2116 #12 0x080b669d in PyEval_EvalCodeEx (co=0x401bade0, globals=0x4018b79c, locals=0x4018b79c, args=0x0, argcount=0, kws=0x0, kwcount=0, defs=0x0, defcount=0, closure=0x0) at Python/ceval.c:2663 #13 0x080b16f0 in PyEval_EvalCode (co=0x401bade0, globals=0x4018b79c, locals=0x4018b79c) at Python/ceval.c:537 #14 0x080da8e4 in run_node (n=0x40174350, filename=0xbffff83b "decode_uu.py", globals=0x4018b79c, locals=0x4018b79c, flags=0xbffff670) at Python/pythonrun.c:1265 #15 0x080da880 in run_err_node (n=0x40174350, filename=0xbffff83b "decode_uu.py", globals=0x4018b79c, locals=0x4018b79c, flags=0xbffff670) at Python/pythonrun.c:1252 #16 0x080da843 in PyRun_FileExFlags (fp=0x8142908, filename=0xbffff83b "decode_uu.py", start=257, globals=0x4018b79c, locals=0x4018b79c, closeit=1, flags=0xbffff670) at Python/pythonrun.c:1243 #17 0x080d97c6 in PyRun_SimpleFileExFlags (fp=0x8142908, filename=0xbffff83b "decode_uu.py", closeit=1, flags=0xbffff670) at Python/pythonrun.c:862 #18 0x080d9065 in PyRun_AnyFileExFlags (fp=0x8142908, filename=0xbffff83b "decode_uu.py", closeit=1, flags=0xbffff670) at Python/pythonrun.c:659 #19 0x08055220 in Py_Main (argc=2, argv=0xbffff734) at Modules/main.c:415 #20 0x080549e6 in main (argc=2, argv=0xbffff734) at Modules/python.c:23 From mcfletch at rogers.com Tue May 18 06:08:25 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 18 May 2004 06:08:25 -0400 Subject: Timer events In-Reply-To: References: <93dqc.15615$gr.1409242@attbi_s52> Message-ID: <40A9E099.8060907@rogers.com> EAS wrote: >But how do you display the time while it is going? > > When asking a question, try to provide a little (okay, in this case, a *lot*) more context. Sure, there's a thread somewhere back in the bit-bucket that one could dredge out to figure out approximately what's being asked, but you're starting your mail out with "but", which suggests that you're discarding the rest of the thread's suggestions. I, for instance, often display the time while it is going by hanging a clock in my office, but that's not likely the solution you're looking for. Similarly, I can display time in my VR contexts by hooking up OpenGLContext's timer object to a Text node to display the current time in a manner that polls only at frame-refresh time. Again, I could use Tkinter's after method to update a clock on-screen. Or I could use a wxPython wx.Timer object, or a wx.lib.analogclock.AnalogClock for my wxPython projects. Or I could just format a datetime instance in a web-site. *Where* are you trying to display "the time"? (And what you do you mean by "the time", I assume you don't want to display relativity-corrected time, but there's no way to tell from the question) Do you want to display elapsed time within your program or calendar/clock time? Do you really mean time-of-day, or date+time? Do you want to display it as graphics or text? What GUI system if you want to display as graphics? What text environment if you want to display as text (console or web)? What are you trying to do? Asking the right question is most of the problem most of the time, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From acrobert-at-ucalgary-dot-ca at ucalgary.ca Sat May 1 12:09:42 2004 From: acrobert-at-ucalgary-dot-ca at ucalgary.ca (Anthony Roberts) Date: Sat, 01 May 2004 16:09:42 GMT Subject: quotes at the edges of a triple quote string... Message-ID: property = re.compile("""(?P[a-z0-9_\-]+)="(?P.*?)""""re.I) This doesn't work because the closing quote in my regex forms the first quote of a triple quote to end the string... property = re.compile("""(?P[a-z0-9_\-]+)=("(?P.*?)")""", re.I) This mucks up stuff I want to do later. I've thought about it for a while, and except for changing it to a single-quoted string with escaped quotes, is there any clean way to do this? TIA, Anthony From davidf at sjsoft.com Wed May 19 12:34:16 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 19 May 2004 18:34:16 +0200 Subject: better csv modules and where have object-craft gone? In-Reply-To: References: <40a98a20@news.highway1.com.au> Message-ID: Skip Montanaro wrote: > Tim> I have been using object crafts csv module for quite a few > Tim> projects, mainly because I found the csv in python in it's current > Tim> incarnation is funtionally inferior to object crafts. The object > Tim> craft module for instance allowed you build up csv gradually (ie > Tim> field at a time rather the python csv module where the writer does > Tim> the work a record at a time) which isn't always the way I would > Tim> like to work, also I have always had encoding problems (specifcally > Tim> it doesn't support unicode as per the docs) everytime I used the > Tim> python module where as the object craft one always worked out of > Tim> the box. > As for lack of Unicode support that's a known issue. I suppose it hasn't > been high enough on anyone's list of itches to have attracted any scratching > yet. Still, you might be able to get most of the way there with a subclass: > > class UnicodeWriter(csv.writer): > def __init__(self, *args, **kwds): > self.encoding = kwds.get('encoding', 'utf-8') > if 'encoding' in kwds: del kwds['encoding'] > csv.writer.__init__(self, *args, **kwds) > > def writerow(self, row): > for (i,f) in enumerate(row): > if isinstance(f, unicode): > row[i] = f.encode(self.encoding) > > I'm almost certain that reading data in multibyte encodings won't work > though, as the low-level reader is byte-oriented instead of > character-oriented. Patches are welcome to resolve that deficiency. Aha! so this is why my csv2po converter is getting strange encodings out... What I'd really like to write/have is a pure Python implementation of the csv module. Presumably this would 1) Make Unicode trivial 2) Be slower Anyhow it would be nice... David From heikowu at ceosg.de Tue May 11 10:10:08 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 11 May 2004 16:10:08 +0200 Subject: OT: Idea for Python T-shirt In-Reply-To: References: Message-ID: <200405111610.08244.heikowu@ceosg.de> Am Dienstag, 11. Mai 2004 15:41 schrieb Peter Hansen: > If you plan to try selling them, note that in North America it's > generally "nybble", by analogy with "byte". Nibble is the British > English spelling. I guess he refers to the other meaning of nibble (from dictionary.com): 1. A very small quantity, especially of food; a morsel. Heiko. From domma at procoders.net Fri May 28 08:19:00 2004 From: domma at procoders.net (Achim Domma) Date: Fri, 28 May 2004 14:19:00 +0200 Subject: CreateProcess / redirect output References: Message-ID: "Richie Hindle" wrote in message news:mailman.402.1085738565.6949.python-list at python.org... > Unless you have a specific reason for using CreateProcess, you can use > os.popen*() - see http://www.python.org/doc/current/lib/os-newstreams.html The code is part of a COM object which is used in an ASP page. Using popen I get the following error: [Errno 5] Access is denied: 'C:\\WINDOWS\\system32\\cmd.exe /c path_to\\ExtractingDummy.exe "path_to\\some_dummy.doc"' The IUSER has the required rights on all these files. Don't know how to solve that. > If you really do need to use CreateProcess, this might help: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/bas e/creating_a_child_process_with_redirected_input_and_output.asp That looks like the info I was looking for. Thanks! Achim From jcm at FreeBSD-uk.eu.org Tue May 4 08:32:44 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Tue, 4 May 2004 13:32:44 +0100 Subject: Growing database? Message-ID: <20040504123244.GA29212@dogma.freebsd-uk.eu.org> This might be a silly question, so I'm warning you ahead of time. I have a persistence database that is saving a 'month' object out with its data. A single month pickled is about 50k. My database of shelved objects contains 4 months of data is over 3 megs. Does the db object journal, or do some other recordkeeping that could explain the huge size difference between pickling to a file and pickling to a 'shelve'? jm -- My other computer is your Windows box. From tjreedy at udel.edu Mon May 31 16:14:54 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 May 2004 16:14:54 -0400 Subject: 2.2 <-> 2.3 surprise References: Message-ID: "Roman Suzi" wrote in message news:Pine.LNX.4.58.0405312107460.3672 at rnd.onego.ru... > > Hi! > > I really like python 2.3 but sometimes I write for 2.2 too. > > New cool feature of doing: > > f = open('file') > for line in f: > do_something(line) > > works strange in 2.2: I can't just quit first loop and do: > > for line in f: > do_some_more(line) In 2.2, the file iterator read chunks of the file and then fed out lines. When you quit loop, read but unprocessed stuff got tossed. tjr From R.Brodie at rl.ac.uk Fri May 21 04:47:02 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 21 May 2004 09:47:02 +0100 Subject: Help w/ HTMLParser lib References: <40ad7619$0$3114$61fed72c@news.rcn.com> Message-ID: "Kevin T. Ryan" wrote in message news:40ad7619$0$3114$61fed72c at news.rcn.com... > I'm somewhat new to python (about 1 year), and I'm trying to write a program > that opens a file like object w/ urllib.urlopen, and then parse the data by > passing it to a class that subclasses HTMLParser.HTMLParser. On the web > page, however, there is javascript - and I think that is causing an error > in parsing the data. The trouble is there is so much junk HTML on the web, which only vaguely follows the syntax. If you are feeding your program with a wide variety of pages, I would recommend sanitising the page using Tidy or uTidylib first. From sc0rp at hot.pl Wed May 5 00:37:29 2004 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Wed, 05 May 2004 06:37:29 +0200 Subject: Urllib2/threading errors under Cygwin References: <40931230.84EECF31@hot.pl> <20040504122927.GC2352@tishler.net> Message-ID: <40986F89.2298BC81@hot.pl> Hi, > > $ python MtUrllib2Test.py | tee out.txt > > 4 [win] python 1744 Winmain: Cannot register window class > > C:\cygwin\bin\python2.3.exe: *** WFSO failed, Win32 error 6 > > The above has been reported before: > http://www.cygwin.com/ml/cygwin/2004-01/msg01371.html I've seen this. I should had mention it. > > [snip] > > Can anyone help me on those two? > > I would recommend trying the latest Cygwin snapshot: > http://cygwin.com/snapshots/ I've tried with latest official 1.5.9. > If that doesn't help, then I would post the smallest possible test case > to the Cygwin list -- you will hopefully get better traction there. I've been rewriting test case in C++, however I've found another socket-related bug that slowed me down. Thanks for help, anyway. Best regards, Jacek. From imbosol at aerojockey.invalid Fri May 7 01:13:50 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 07 May 2004 05:13:50 GMT Subject: Scope rule pecularities References: Message-ID: Holger T?rk wrote: > a1 += b > > is not a shortcut for > > a1.__iadd__ (b) > > but for > > a1 = a1.__iadd__ (b) > > with the advantage of a1 evaluated only once. Nitpick: a1 is only evaluated once in both of them. If it were (for example) a1[0] instead of a1, then a1 would be evaluated once in the former, twice in the latter. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From newsgroups at jhrothjr.com Sat May 1 19:59:00 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 1 May 2004 19:59:00 -0400 Subject: except AttributeError, TypeError: References: <19zy0i7gw5uym.dlg@thorstenkampe.de> Message-ID: <1098efbjvo8nf0f@news.supernews.com> "Thorsten Kampe" wrote in message news:19zy0i7gw5uym.dlg at thorstenkampe.de... > What is the best way to except two errors, when the except handling in > both cases is the same? > > "except:" would just except every error and not just those I want. > > except Attribute error: > do_much_stuff > except TypeError: > do_the_same_stuff > > is bad because of the duplication and > > def do_it(): > do_much_stuff > except Attribute error: > do_it() > except TypeError: > do_it() > > would work but is rather unelegant? What is the best way to except to > errors with the same exception handling? except (AttributeError, TypeError): John Roth > > Thorsten From r.gable at mchsi.com Sat May 29 07:02:22 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 29 May 2004 04:02:22 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> <22b7fd40.0405240325.7b2b6376@posting.google.com> <5d1dd116.0405270818.46f43d5b@posting.google.com> Message-ID: <22b7fd40.0405290302.50c9005a@posting.google.com> I tried this bur it did not work. From that I assume they are using cookies. Since I am not handling them (using this method), the figure that out and fill in the page with dashes where I get data when processing the HTML through MSIE. Thanks for your suggestion. milas_gi at hotmail.com (tutu) wrote in message news:<5d1dd116.0405270818.46f43d5b at posting.google.com>... > > > I'm not sure why you need to go through IE, but maybe this will get you into > > > the right direction: > > > > > > >>> import urllib > > > >>> f = urllib.urlopen('http://www.python.org') > > > > > > > Sorry. I forgot to mention that I have tried that. The data I want is > > being stripped out when I access the URL via urllib. > > > Try something like this: > It may be the site does not like urllib agent so try to pretend you are using IE. > class URLHandler(urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler): > pass > agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)" > request = urllib2.Request(url) > request.add_header("User-Agent", agent) > opener = urllib2.build_opener(URLHandler()) > opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent > htm = opener.open(request) > opener.close() > htm.read() > > Good Look From brett at coombs.anu.edu.au Fri May 14 00:25:13 2004 From: brett at coombs.anu.edu.au (Brett Calcott) Date: Fri, 14 May 2004 16:25:13 +1200 Subject: exhaustive subsets Message-ID: I've found some python solutions to find the set of subsets for a given set, but how do you find the set of the set of subsets whose union is the given set and whose intersections is the empty set. ie. Given a cake divided into 6 unique pieces (0-5), how many different ways can I distribute the cake so that there are no pieces left. eg. ((0), (1,2,3,4)) or ((0),(1),(2,3,4)) or ((0,1),(2,3),(4)) or ((0,4),(1),(2,3)) Is there a name for this problem? Cheers, Brett -- Brett Calcott Philosophy Program, RSSS, ANU Canberra, ACT 0200, AUSTRALIA From tjreedy at udel.edu Thu May 13 12:12:28 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 May 2004 12:12:28 -0400 Subject: iterators References: Message-ID: "Manlio Perillo" wrote in message news:o996a0t6ra0pj42emgjpjsr9c375dracrf at 4ax.com... > Hi. > > Python support forward iterators, Actually, it supports general linear iteration, which is to say, one-at-a-time processing of every item in any collection, however structured, in whatever order. Structured collections usually have special orders like forward and backwards for sequences, alphabetic for string collections, pre-order and post-order for trees, and also in-order for binary trees. Support has three aspects: a definition of 'iterator-ness' (having __iter__ and next methods -- the 'iterator protocol') that users can implement, implementation of the protocol for all appropriate builtin collection types as well as provision of two special interator types that serve as return values for iter() and generator functions, and use of the protocol by for statements. < but what about bidirectional List .push and .pop can be thought of as a type of bidirectional access. More generally, one can augment .next with a .prev method, and people have. This is specifically appropriate for a doubly-linked list, actual or virtual. If a collection can be randomly accessed (see below), then bidirectional access is easily accomplished with a cursor that is incremented and decremented, but there is usually no reason to limit index changes to +-1. For a multidimensional array, one could define a corresponding multidirectional cursor. > random access ones? See __getitem__ methods and index (object[]) syntax, which apply to both sequences and associations. A random access cursor is a name bound to an approprite index object or a collection object containing such. Terry J. Reedy From beta at thinksql.co.uk Thu May 27 19:30:05 2004 From: beta at thinksql.co.uk (Greg Gaughan) Date: Fri, 28 May 2004 00:30:05 +0100 Subject: how to store binary file data to a database blob References: Message-ID: Your DB-API driver should allow you to pass binary data easily via a typed parameter to execute (or executemany for multiple rows). For example, in ThinkSQL, you can say: blobdata=open('image.jpg', 'rb').read() s1.execute("INSERT INTO picture_table (image) VALUES (?)", (ThinkSQL.Binary(blobdata),)) Regards, Greg Gaughan www.thinksql.co.uk "David Stockwell" wrote in message news:mailman.363.1085669805.6949.python-list at python.org... > Hi, > > I'd like to read the contents of a file into memory. The problem is that > this file is binary. I then want to store the whole thing in memory to a > database as a blob. > I have no problem reading from a file: I did this: > > import os > f = open('/bin/ls' , 'r+b') > data = f.read() > f.close() > > How do I place that in a blob? If I concatenate this to a sql string, how > will the database sql parser know where my data string ends, knowing that my > data string could contain lots of ' and " and other little things in it. ??? > > storeString = "insert into mytable (filedata) values ( %s ) " % data > > Does that look right? I don't think it would execute correctly. > > Thanks > > > David Stockwell From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Fri May 21 03:00:08 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 21 May 2004 09:00:08 +0200 Subject: GetClipboardData(CF_BITMAP) unimplemented References: <90924643.0405200902.610baf23@posting.google.com> <40ad4bbd_1@127.0.0.1> Message-ID: Hi ! For screen-capture, with PIL, you can do too : import Image, ImageGrab ImageGrab.grab().save(filename) But the question talk of CLIPBOARD and bitmap. @+ -- Michel Claveau From irmen at -nospam-remove-this-xs4all.nl Thu May 20 15:31:00 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 May 2004 21:31:00 +0200 Subject: Socket sample? In-Reply-To: References: Message-ID: <40ad0774$0$33919$e4fe514c@news.xs4all.nl> Daniel Orner wrote: > Hmm... I'm looked at the SocketServer, but I'm pretty confused about > how to use it. As far as I can tell it doesn't actually do any > forking/threading/selecting at all. There's a lot of generic stuff which > seems to allow that behavior for subclasses, but I can't see any > specific code that does that kind of thing. Or maybe I'm just missing > something stupendously obvious. If so, would you be so kind as to give > me a quick example of how it would be used? The SocketServer docs say: "The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour. " And if you look in SocketServer.py (from python 2.3.3) you'll see at line 479: class ForkingUDPServer(ForkingMixIn, UDPServer): pass class ForkingTCPServer(ForkingMixIn, TCPServer): pass class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass So it already defines 4 specialized server classes for you to use :-) Threading, or forking, whatever suits you best. If you want a TCP server that uses a new thread for each request, just use SocketServer.ThreadingTCPServer instead of SocketServer.TCPServer and you're done! --Irmen From premshree_python at yahoo.co.in Tue May 11 17:39:13 2004 From: premshree_python at yahoo.co.in (=?iso-8859-1?q?Premshree=20Pillai?=) Date: Tue, 11 May 2004 22:39:13 +0100 (BST) Subject: Watch That Post In-Reply-To: <0rOnc.20115$7n5.16403@pathologist.blueyonder.net> Message-ID: <20040511213913.59742.qmail@web8306.mail.in.yahoo.com> If you see in the source code, a couple of lines are commented; you need to play around a bit :-) I'll work on it later. -Premshree --- Steven wrote: > Premshree Pillai wrote: > > > Hello, > > > > I recently posted a simple Python script--Watch > That > > Post--that lets you watch a URL for any changes. > > > > I wrote it to watch posts on LiveJournal, but it > can > > watch any URL. > > > > It's at > http://premshree.seacrow.com/code/python/watch > > > I tried running it. It works fine until it tries to > run the watch function a > second time, then it does this: > > Traceback (most recent call last): > File "watch.py", line 76, in ? > watch() > File "watch.py", line 58, in watch > size2 = len(urllib.urlopen(url).readlines()) > File "/usr/lib/python2.3/urllib.py", line 76, in > urlopen > return opener.open(url) > File "/usr/lib/python2.3/urllib.py", line 181, in > open > return getattr(self, name)(url) > File "/usr/lib/python2.3/urllib.py", line 410, in > open_file > return self.open_local_file(url) > File "/usr/lib/python2.3/urllib.py", line 420, in > open_local_file > raise IOError(e.errno, e.strerror, e.filename) > IOError: [Errno 2] No such file or directory: > 'www.kde-apps.org' > > I really like the idea, > > Steven > -- > http://mail.python.org/mailman/listinfo/python-list ===== -Premshree [http://www.qiksearch.com/] ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From HughMacdonald at brokenpipefilms.com Wed May 12 16:08:44 2004 From: HughMacdonald at brokenpipefilms.com (Hugh Macdonald) Date: Wed, 12 May 2004 21:08:44 +0100 Subject: Why is a None appearing in my output? References: Message-ID: <013a01c4385c$f0843780$0600a8c0@Hugh> ----- Original Message ----- From: "David Stockwell" To: Sent: Wednesday, May 12, 2004 8:46 PM Subject: Why is a None appearing in my output? > I entered the following text into a 'module file' and saved it: > > def fib6(n): # write Fibonacci series up to n > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b > else: > print "done b[",b,"], n[",n,"], a[", a,"]" > > print "fib6:", fib6(50), "---" > print "next" What it's doing is this: print "fib6:", run fib6(50) print b various times print "done b[",b,"], n[",n,"], a[", a,"]" print what was returned from fib6(50) (in this case None) print "---" print "next" Your best bet would be to change the line: print "fib6:", fib6(50), "---" to print "fib6:", fib6(50), print "---" OR change the function itself to: def fib6(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b return "done b[",b,"], n[",n,"], a[", a,"]" Hugh Macdonald From jarod68 at despammed.com Sun May 9 14:37:22 2004 From: jarod68 at despammed.com (jarod) Date: Sun, 9 May 2004 20:37:22 +0200 Subject: Python for Nokia Series 60 References: Message-ID: <2g7c6lF52kr4U1@uni-berlin.de> > I have found : > > http://xenian.net/~enki/ > and > http://feetup.org/blog/dev/python/symbianPython.html are you sure there is some source-binary project downloadable ? I haven't found. Seems a personal project for porting Python to Symbian, not the Nokia Amaretto (Python for Series 60) described in the previous article. Salut Jarod From nhodgson at bigpond.net.au Sun May 23 17:46:03 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sun, 23 May 2004 21:46:03 GMT Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01><30260531.0405222153.5027c135@posting.google.com> Message-ID: gabor: > hmmm...i understand that you can cast away const, > but what about... > > class C > { > private x; > }; Technique 1: class D { public: int x; }; C c; (reinterpret_cast(&c))->x = 1; Technique 2: #define private public #include #undef private C c; c.x = 1; In both of these it is obvious that the encapsulation rules are being broken which is exactly the same situation as when someone uses the mangled name in Python. I have used technique 2 in production code where a library could not be altered and access to private methods was required. Neil From tor.iver.wilhelmsen at broadpark.no Mon May 10 17:52:13 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 10 May 2004 23:52:13 +0200 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: wjb131 at web.de (Wolfgang Buechel) writes: > for (a,b,c,d) in [(x,y,z,t) for x in range(M) > for y in range(M) > for z in range(M) > for t in range(M)] : > matr = [[a,b],[c,d]] Try assigning range(M) to a variable instead of creating four copies of it. For larger ranges, experiment using xrange instead. From manatlan at online.fr Thu May 20 15:30:56 2004 From: manatlan at online.fr (marco) Date: Thu, 20 May 2004 21:30:56 +0200 Subject: drag drop from linux to a wxpython application In-Reply-To: <30260531.0405190935.6c171a@posting.google.com> References: <40ab3ae7$0$21248$636a15ce@news.free.fr> <30260531.0405190935.6c171a@posting.google.com> Message-ID: <40ad0771$0$14063$626a14ce@news.free.fr> simo a ?crit : > marco wrote in message news:<40ab3ae7$0$21248$636a15ce at news.free.fr>... > >>I've got a wxpython application >>and when i drag'n' drop files from(linux) rox/nautilus/konqueror to my app >>i've got strange chars in filenames (on win32 : it works well) >> >>example: >>- my dir "my photos" will become "/home/marc/my%20photos" >>- a dir "f?tes ? strass" will become (something like this) >>"/home/marc/f%A8%CFtes%20%8F%AC%20strass" > > > This is URL encoding. Basically because the use of top-bit-set > characters and spaces in filenames is evil. Don't forget that most > file managers are basically web browsers.... > > You'd need to URL decode the chars to get your original filename as on > Windows, try: > > import urllib > print urllib.unquote_plus("f%A8%CFtes%20%8F%AC%20strass") > > That will fix your %xx characters, although I don't get the same > encoding as you're getting there (maybe it's a unicode thing?): > > print urllib.quote("f?tes ? strass") > f%EAtes%20%E0%20strass thanks a lot ... From __peter__ at web.de Thu May 27 05:11:01 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 May 2004 11:11:01 +0200 Subject: Cleaner idiom for text processing? References: <95aa1afa.0405270044.71307d09@posting.google.com> Message-ID: Michele Simionato wrote: >>>> import itertools >>>> def chop(it, n): > ... tup = (iter(it),)*n > ... return itertools.izip(*tup) > ... >>>> list(chop([1,2,3,4,5,6],3)) > [(1, 2, 3), (4, 5, 6)] >>>> list(chop([1,2,3,4,5,6],2)) > [(1, 2), (3, 4), (5, 6)] >>>> list(chop([1,2,3,4,5,6],1)) > [(1,), (2,), (3,), (4,), (5,), (6,)] > > (I don't remember if this is already in itertools ... ) I don't think so. IMO the itertools examples page would be a better place for the above than the cookbook. If an example had to be removed in exchange, that would be iteritems(). Raymond, are you looking? Peter From b.niemann at betternet.de Wed May 26 09:00:31 2004 From: b.niemann at betternet.de (Benjamin Niemann) Date: Wed, 26 May 2004 15:00:31 +0200 Subject: sys.stdout linebuffered In-Reply-To: References: Message-ID: > I start a long running script like this (unix): > > nohup foo.py > foo.log & > > Now Python thinks sys.stdout should not be > line buffered. How can I force linebuffering? > > I want to see the log file while the script is > still running. > > I don't like this solution (Wrapping sys.stdout > with an own class) > > http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&selm=u4rz0icqq.fsf%40ctwd0143.fitlinxx.com > > The "-u" switch is not an option. Even if you use #!/usr/bin/python -u in your script? From danb_83 at yahoo.com Thu May 20 03:19:12 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 May 2004 00:19:12 -0700 Subject: alternatives to making blocks like { } or other ?? References: Message-ID: Grant Edwards wrote in message news:... > On 2004-05-18, CYBER wrote: > >> Of course there is another way! > >> > >> Just use # in front of your favourite block separator. ... > You realize that was a joke, right? > > Please, please don't write code like that. You'll be shunned > just like the BASIC programmers who switched to C and pulled > crap like > > #define IF if ( > #define THEN ) { > #define ELSE } else { > #define ENDIF } Also, #define ELSEIF } else if { because using "ELSE IF" gives you unbalanced braces. > #define WHILE while ( > #define DO ) { > #define DONE } I don't remember BASIC ever using the syntax "WHILE cond DO ... DONE"; you've probably got it mixed up with another language. "WHILE cond ... WEND" would be more accurate, but then it's harder to deal with the ")" on the first line. Also, you might want to support the QBasic DO...LOOP syntax, which had four forms: ' 1. Pretest loop (while), positive condition DO WHILE cond : statements : LOOP ' 2. Pretest loop (while), negative condition DO UNTIL cond : statements : LOOP ' 3. Posttest loop (do...while), positive condition DO : statements : LOOP WHILE cond ' 4. Posttest loop (do...while), negative condition DO : statements : LOOP UNTIL cond I doubt it's even possible to #define DO, LOOP, WHILE, and UNTIL to handle all of them. From mozumder at dsmpro.com Thu May 6 14:57:28 2004 From: mozumder at dsmpro.com (Bobby Mozumder) Date: Thu, 6 May 2004 14:57:28 -0400 Subject: Qt Widget? Re: Where is IDLE? In-Reply-To: References: Message-ID: <38481B24-9F8F-11D8-9B86-000A95C8902E@dsmpro.com> It's for an engineering app that uses a Python interface. Anyone have a Qt widget for a python interpreter? -bobby On May 6, 2004, at 2:24 AM, CHEN Benfeng wrote: > There are lots of Python IDEs, why do you want to implement another > one ? > > -- > Best Regards > "Bobby Mozumder" wrote in message > news:mailman.293.1083822310.25742.python-list at python.org... >> I can't find it in the 2.3.3 source tarkit. Shouldn't it be in the >> Tools directory? >> >> BTW I am trying to embed an IDLE-type interpreter into a Qt TextEdit >> widget. Has anyone done the same? >> >> -bobby >> >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed May 5 11:06:31 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 May 2004 11:06:31 -0400 Subject: improving the Python docs -- a wiki? copy PHP's model? References: Message-ID: "Stephen Ferg" wrote in message news:b16e4ef7.0405050516.4552c6c4 at posting.google.com... > > Is submitting a bug or patch to sourceforge really that much of a barrier? > > Yes, it is a significant barrier. It requires knowledge of both Latex > and a certain way of using diff. Neither are required to submit a doc bug report, which can then be used by someone else with the required knowledge to actually make the fix. Typos currently get fixed pretty quickly once reported. A suggested sentence to replace an incorrect sentence may take longer to get inserted. But I have helped fix a few reported more-than-one-word-typo doc glitches, without knowing either Latex or diff, by submitting comments with a suggested sentence or two and with specific suggestion locations. > In general, I'd agree that the Python documentation is outstanding. > But there are gaps -- a qualifying phrase here, a missing reference > there, a small example in many places. Filling those gaps would make > the difference in those places between documentation that is just > barely adequate and documentation that is really excellent. I admit I don't know whether 'text patches' would be as welcome for enhancements as for fixes. If I were inclined to submit such, I might inquire first. Terry J. Reedy From mensanator at aol.com Mon May 24 20:01:04 2004 From: mensanator at aol.com (mensanator) Date: 24 May 2004 17:01:04 -0700 Subject: Prothon vs. Python integers References: Message-ID: "Mark Hahn" wrote in message news:... > "Paul Prescod" wrote > > > I think that in this case, Python is demonstrably better than Prothon. > > > > C:\temp\prothon\Prothon>python > > ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on > > Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on > > win32 > > Type "help", "copyright", "credits" or "license" for more information. > > > > >>> print 2**65 > > 36893488147419103232 > > > > >>> print 2**65 == (2**65 + 1) > > False > > > > > > C:\temp\prothon\Prothon>prothon > > > > Prothon 0.1 Interactive Console, Build 532, May 21 2004 (Ctrl-D to exit) > > > > >>> print 2** 65 > > 3.68935e+19 > > > > >>> print 2**65 == (2**65 + 1) > > True > > > > If Prothon is a language designed for the next ten years then it should > > be tuned for correctness and ease of use, not for limitations of today's > > hardware. > > I'm sure this isn't the only place Python is better. > > Prothon has the long integer support in the parser if anyone wants to take > the trouble to put the long object code in. I did nothing to preclude it. I > just didn't see any need for it myself and didn't take the trouble to put it > in. > > Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely > once you get to 3.7e19 you are in floating point territory. Unless you're working on problems in Number Theory, in which every single decimal digit of 2**177525 - 1 is significant. >I can't imagine counting anything up to 10**19. Not every sequence increments by 1. Putting 2**177525 - 1 into the Collatz Conjecture results in a mere 2.5 million iterations, not 10**53000. Limiting the loop counts to <10**19 doesn't mean you have to limit the values. From chris.cavalaria at free.fr Tue May 18 14:44:22 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Tue, 18 May 2004 20:44:22 +0200 Subject: PEP: import version References: <40a52416$0$22119$636a15ce@news.free.fr> Message-ID: <40aa5988$0$22949$636a15ce@news.free.fr> David Fraser wrote: > Have you actually used it extensively? If so, I doubt you would be > saying this... > wxWiindows (now wxWidgets) doesn't have aconstantly mutating API. > But the new major revision does have some changes. The point is you can > still get programs to work with both versions, so you don't need to have > a new name. Sorry but breaking existing code with some change and calling that a minor version upgrade not worth a new name qualifies for my definition of a constantly mutating API ;) > But if a program does rely on a particular version, it would > be nice to have a way to specify it. Yes, and why couldn't you do it like that : import wxPython24 as wxPython From deetsNOSPAM at web.de Wed May 19 13:15:39 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 19 May 2004 19:15:39 +0200 Subject: Socket sample? References: Message-ID: Daniel Orner wrote: > I'm a newcomer to socket programming... I need to use a server socket > which should be able to handle more than one connection at a time. I've > read the HOWTO, but I'm still a bit confused about some of the more > intimate details. I've also seen a few pieces of sample code scattered > here and there, but nothing substantial. > Does anyone know of some sample code that handles multiple connections > (either by using select() or forking/threading processes)? > Thanks very much! use twisted - its well worth the effort, and supports the things you need. -- Regards, Diez B. Roggisch From vdbergh at luc.ac.be Sat May 15 08:59:45 2004 From: vdbergh at luc.ac.be (Michel Van den Bergh) Date: Sat, 15 May 2004 14:59:45 +0200 Subject: code of webbrowser.py Message-ID: <40A61441.4000604@luc.ac.be> Hello, I was looking at the code of webbrowser.py included in python 2.3.3. I think there are some obvious problems with it (tested with mozilla on Linux). (*) If you open an url (with the option "new window") and the browser is not already running then it opens *two* windows: the home page and your url. This is different for example from the default behaviour on Windows. (**) There is another related problem: if you open an url and the browser is not already running then the code starts a new browser, does a timed sleep and then issues a "-remote" command. Using a timed sleep is *very fragile*, and indeed I had failures because the delay (PROCESS_CREATION_DELAY) was not long enough. At the very least the -remote command should be tried a couple of times. BUT: there is no reason *at all* to issue a -remote command in this case. All browsers I know accept an url as argument. So one can just start a new browser with the url as argument. (***) Mozilla type browsers now have a -remote "ping()" command. This is perhaps a cleaner way to detect a running browser. Any comments? Best regards, Michel From j_mckitrick at bigfoot.com Mon May 24 18:37:07 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 24 May 2004 15:37:07 -0700 Subject: Problem building pygtk-2.3.92 References: Message-ID: > Do you have latest gtk+ , glib, pango and family ? I do. It turns out there was an extra semicolon that tripped up gcc 2.95.3. I have it working now. thanks, jonathon From ron at projectmessiah.com Mon May 10 23:17:39 2004 From: ron at projectmessiah.com (Ron Griswold) Date: Mon, 10 May 2004 20:17:39 -0700 Subject: Int tuple element scope Message-ID: <00a001c43706$9617a540$6501a8c0@ANIMATOR2> Can anyone tell me why the following will cause the returned tuple elements to remain un collected when the tuple goes out of scope: PyObject * iobj = PyObject_New( PyIntObject, &PyInt_Type ); iobj->ob_ival = val; PyTuple_SetItem( tuple, index, iobj ); return tuple; while the following will collect the elements: PyTuple_SetItem( tuple, index PyInt_FromLong( val ) ); return tuple; both PyObject_New and PyInt_FromLong return new references and I have verified that in all cases the refcount upon return is 1 for all objects involved. So I'm just wondering if I'm missing something fundamental. Thanks in advance! Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn at drizzle.com Thu May 6 01:46:35 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 06 May 2004 05:46:35 -0000 Subject: Unification of Methods and Functions References: <16752bcc.0405050817.4ca77017@posting.google.com> Message-ID: <1083822394.7883@yasure> Quoth David MacQuigg : ... | The second problem with the "avoidance/denial" strategy is that it | involves moving the troublesome functions outside of the class | definition. This results in a less-than-optimal structure for your | program. Look at the show() methods in Animals_2.py They must be | callable without any specific instance. Moving them outside the | appropriate classes is not good programming. When you want to change | a class later, you will need to remember to look in some other place | for any "static methods" associated with the class. | | If you could do me one more favor, please take a look at the | Animals_2.py example starting on page 7 of the Prototypes document at | http://ece.arizona.edu/~edatools/Python Can you write this in Python? | Give it a try, and let me know if you had any difficulties. Were | there any parts you had to stop and think, or look up in a manual? Mine came out 66 lines, most of it very introductory level and nothing exotic. The first dozen lines deal with the inventory problem, which I gather is the issue you're interested in. I don't maintain a count in each class, but rather keep the counts in a single data structure in the base class, and I provide a single show() function that prints them. If I were writing this in C++, I might make that a static function. But then, I hate C++. Now, you could argue that I changed the problem to suit my purposes, but your approach repeats some stuff all over the class hierarchy in a kind 'similar but not quite the same' way that I don't like at all. If we need to implement some functionality that's general to the hierarchy, then let's implement it once. I can imagine in principle the need for a class specific function. In such a case, I would define the function above the class definition, and refer to it inside a data structure at the class level. I have a vague notion that there are newer Python features that address these issues, but I'm not interested - it isn't important. Donn Cave, donn at drizzle.com ----------------------------------- def show(): for k, v in Animal.inventory.items(): if v == 1: f = '%s: %s' else: f = '%ss: %s' print f % (k, v) class Animal: home = 'Earth' inventory = {} def __init__(self): self.register('Animal') def register(self, name): i = self.inventory.get(name, 0) self.inventory[name] = i + 1 class Reptile(Animal): pass class Mammal(Animal): def __init__(self, sound = 'Maa... Maa...'): self.sound = sound self.register('Mammal') Animal.__init__(self) def talk(self): print 'Mammal sound: ', self.sound class Bovine(Mammal): pass class Canine(Mammal): pass class Feline(Mammal): genus = 'feline' def __init__(self): Mammal.__init__(self) self.register('Feline') class Cat(Feline): def __init__(self, name='unknown', sound='Meow'): Feline.__init__(self) self.register('Cat') self.name = name self.sound = sound def talk(self): print 'My name is ...', self.name print 'I am', self.genus, 'from', self.home Mammal.talk(self) a = Animal() m = Mammal() print 'm:', m.talk() f = Feline() print 'f:', f.talk() c = Cat() print 'c:', c.talk() show() cat1 = Cat('Garfield', 'Purr') cat1.talk() From ndbecker2 at verizon.net Wed May 5 14:21:03 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Wed, 05 May 2004 14:21:03 -0400 Subject: Best IDE? References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> Message-ID: SM wrote: > Hi, > Just to let you all know that there is a new version of SPE being > developped with a much faster class/index/todo browser (can be even > realtime!), wxPython 2.5 support, simultaneous view of source code, > you can choose between MDI or SDI both with tabs, better control of > calltips (only first paragraph or all doc) ... If you are curious, > you can download it from http://projects.blender.org/projects/spe/ The > windows XP version is already quite stable, for linux and mac os x, > I'm dependent of other users. > Stani > Does SPE feature running python subprocess? Python debug? Jump to error? From winexpert at hotmail.com Thu May 27 11:22:05 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 15:22:05 +0000 Subject: How to I print without newline ? Message-ID: Hi, This might work: print "25\r", the \r would do a carriage return with no line feed. the , would try to keep it on the same line. not sure though. David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: "fowlertrainer at anonym.hu" >To: python-list at python.org >Subject: How to I print without newline ? >Date: Thu, 27 May 2004 17:06:17 +0200 > >Hi ! > >I want to print, but without newline. I want to create a progress for ftp, >but the print is drop a newline for every percent. >I want like this: > >0% 25% 50% 75% 100% > >But this happening: >0% >25% >50% >75% >100% > >How to I prevent the newlines ? > >Thanx for help: >FT > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ From sross at connectmail.carleton.ca Fri May 14 09:04:50 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 14 May 2004 09:04:50 -0400 Subject: beginner's question References: Message-ID: "Hadi" wrote in message news:c82d51$78s$1 at lust.ihug.co.nz... > Hi, > I have two files and the array that contains 20 words in it. > I'm trying to write python script that suppose achieve the following: > -Open file-1, read the line that contains 20 words separated with commas > -Compare each word with words in the array > -Open file-2 > -if the word appears in the array write 'true' in file-2 > -if not write 'false' > -repeat this for every line in the file-1 > > so, two file will be identical in terms of number of lines and number of > words in each line. > However, file-2 will only contain wods 'true' and 'false'. > > Can anyone give some example or point me to som useful web sites please. > > Thanks, > hadi > > lexicon = ["our", "list", "of", "words", "to", "be", "compared"] # open the source and destination files src = file("file1/path") # open for reading dst = file("file2/path", 'w') # open for writing # Hadi: does file1 contain one or more lines? This only works for one line. # For more lines, you'll need to do further processing ... # # Make a list of the words in src. We split the line at each comma, and # remove any excess whitespace from around the word words = [w.strip() for w in src.readline().split(',')] # Now we see if the words are in our list and write the results to dst for w in words: dst.write(str(w in lexicon)) # writes 'True, ' or 'False, ' # Python will eventually close the files for you, or you can do it explicitly src.close() dst.close() Hope that helps, Sean From dietpaopao at netscape.net Mon May 3 00:06:29 2004 From: dietpaopao at netscape.net (Yang Wang) Date: Mon, 03 May 2004 00:06:29 -0400 Subject: Need Suggestions for Python/Tk/VTK Message-ID: <4095C545.1030907@netscape.net> Dear All, I am totally new to Python, however had some experience with Tcl/Tk. Currently I am doing a project that will need Python/Tk as well as VTK(Visualization Toolkit) for image processing and visualization. Have anyone had any experience in this that can give me some suggestions or references? And I also wonder how Tk is working with Python in the process of constructing GUI, is it like the way that with Tcl? Any help will be greatly appreicated. Thanks. Yours, Casper From http Thu May 20 04:40:40 2004 From: http (Paul Rubin) Date: 20 May 2004 01:40:40 -0700 Subject: Python compilers? References: <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> <38Yqc.166$eO6.128@fe2.columbus.rr.com> Message-ID: <7x1xlf8p9z.fsf@ruckus.brouhaha.com> Carl Banks writes: > > The example above kills any attempt to turn a.bar() into a static > > procedure call. > > Of course it does--but it's one method. A compiler, if it's good, > would only make the optization on methods named "bar", and it could > probably pare the number of possible classes it could happen to down > to only a few. How could it possibly know? The reassignment of a.bar could happen anytime, anywhere in the code. Maybe even in an eval. > I mean you could have a Turing nightmare on your hands, with all kinds > of crazy setattrs and execs and stuff, in both Python and Lisp, and > then there's not much a compiler could do but emit totally general > code. I assume Lisp compilers do this sometimes. Lisp compilers might have to do that sometimes, but Python compilers would have to do it ALL the time. Psyco took one way out, basically generating code at runtime and caching it for specific operand types, but the result is considerable code expansion compared to precompilation. From grante at visi.com Fri May 21 10:37:18 2004 From: grante at visi.com (Grant Edwards) Date: 21 May 2004 14:37:18 GMT Subject: GTK or TKinter (or what else?) References: Message-ID: On 2004-05-20, Marco Terzuoli wrote: > [...] I know you can use wxWindows as well... I have tried it > in my C program and didn't like the way events were handled. I had the same reaction. > Are there any differences in Python? Not really, unless you use a higher-level wrapper on top of wxWindows -- something like "wax". Wax hides most of the event details. -- Grant Edwards grante Yow! Are we THERE yet? My at MIND is a SUBMARINE!! visi.com From sean_berry at cox.net Wed May 5 19:13:27 2004 From: sean_berry at cox.net (Sean Berry) Date: Wed, 5 May 2004 16:13:27 -0700 Subject: Newbie question about list method remove Message-ID: Why is this: >>> li2 =['this.txt', 'that.txt', 'April04', 'more.txt'] >>> for item in li2: if ".txt" in item: li2.remove("%s" %item) >>> li2 ['that.txt', 'April04'] I would think that 'that.txt' would be removed as well. Where am I wrong? TIA From swtprog at yahoo.com Thu May 27 12:38:40 2004 From: swtprog at yahoo.com (SWT) Date: 27 May 2004 09:38:40 -0700 Subject: Offsite python programmer position Message-ID: Looking for offsite experience python programmer, familiar with wx-Python and Bit Torrent code base. Please email resume and requirements to swtprog at yahoo.com From flo at via.ecp.fr Wed May 5 06:06:28 2004 From: flo at via.ecp.fr (Florent Rougon) Date: Wed, 05 May 2004 12:06:28 +0200 Subject: pyxmms trouble References: Message-ID: <87fzafxk63.fsf@florent.maison> [ Please note that I am not subscribed to this group. A friend of mine kindly pointed me to this thread (since I am the author of PyXMMS). If you want to be sure that I read other posts in this thread, please Cc me. ] David Smith wrote: > Hi: Hi, > I am a newbie to python and in general programming. My problem is > that I am trying to use the pyxmms remote to add songs to the xmms Don't confuse PyXMMS and PyXMMS-remote... the latter is a command-line interface to the former. > playlist. However, no matter whether I open the interpreter or put it in > a file and run the script the output is the same. It just sits there > with no error msg of any kind and doesn't add the file to the playlist. libxmms/xmmsctrl.c is not very helpful with respect to errors. For instance: void xmms_remote_playlist_add(gint session, GList * list) { gchar **str_list; [...] xmms_remote_playlist(session, str_list, num, TRUE); g_free(str_list); } You see, PyXMMS has no way to tell whether an error happened in this function. > I then have to ctrl-c to break it and alot of times this makes the > keyboard stop working and I have to restart X to get it working again. Ugh, that sounds a bit excessive. Did you make sure that all xmms processes were dead? ps -el | grep xmms ("| less" instead of "| grep xmms" to see the column headers first) kill and if this is not enough: kill - with signumber being 1, then 15 if it wasn't enough, then 9 (the last one should not fail except in very, very bad situations) > Here is the I'm using code: [...] > os.popen2('/usr/bin/xmms') There is a problem here: you are effectively opening two pipes, one connected to xmms's stdin and one connected to its stdout; but you never read from them since you don't even reference them from a variable. First, you miss xmms' messages (yes, it might give you error messages!). Second, in case xmms happens to output enough stuff on one of these pipes (I believe it is 4096 bytes on Linux), it will simply block until you start reading from the pipe(s) that is/are full. That is what I would call suboptimal behavior. You should make sure your code avoids this blocking issue. One way is to make as in /src/control.py, line 321: child_pid = os.fork() if child_pid == 0: # We are in the child, me MUST NOT trigger any exception (look at # _spawnvef in Python's os.py). try: os.execvp(abs_prog_name, (abs_prog_name, "-p") + tuple(seq)) except: # We cannot know in the father process if the child's execvp # failed, but AFAIK, there is no simple solution since I don't # want the father to wait for the child's completion. init # will be a good father. :-) os._exit(127) > time.sleep(5) Mmm, I don't usually start XMMS this way (and in the previous example, the first command given to XMMS is its -p command-line option, which avoids the problem of having to wait until XMMS is ready), so I'm not sure what the best practice is here. If I were you, I would try to wait before XMMS' control socket appears in /tmp[1] and see if it is responsive from that point on. I think that should be enough: libxmms (called by PyXMMS) would be able to write your first request to the socket and defer the answer until XMMS is ready and writes it to the socket. > print xmms.control.is_main_win(0) > if xmms.control.is_main_win(0) == 1: Well, you don't need the "== 1" part but it will work of course. Since Python introduced True and False, you should try to be consistent with that choice and simply use "if xmms.control.is_main_win(0):". (and yes, one day, PyXMMS will probably yield True and False where booleans are returned but this was written before True and False existed in Python) > seq = "/home/eomer/tumes.m3u" > xmms.control.playlist_add_allow_relative(seq, 0) Ahhh. That is your problem. Let me quote PyXMMS' documentation: playlist_add_allow_relative(seq, session=0) Add files/URLs to the playlist, allowing relative file names. seq -- a sequence of files/URLs session -- the XMMS session to act on Return None. Your 'seq' is not a sequence of files and/or URLs. Oh, wait. Yes, it is! And that is why you don't get a TypeError or something from PyXMMS (PyXMMS does perform error handling where it is possible). But this is most probably not the sequence you want, since its elements are: "/", "h", "o", "m", "e", "/", "e", "o", "m", etc. Now you wonder why XMMS cannot add these files to the playlist... > Under the interpretor I do access it differently (and I opened xmms > myself): > import xmms.control > xmms.control.playlist_add('/home/eomer/tumes.m3u', 0) > > I have used both of these functions both ways. Both produce the same > result. The playlist_clear function works perfectly. Also I have tried > other files that aren't actually m3u lists. All have the same effects. Interactive use is nice, but if something is wrong in a script, it is also wrong in the interactive shell... > I am running Xmms 1.2.10 (just in case you need to know :D). Oh also if > you know a better way to open xmms from the script and allow the script > to still run please feel free to comment. I think that was done above. > Oh, this is just an experiment not life or death (yet :)). What? I didn't save your life?! Oh shhhhh***t... PS : you could solve most of your problems by studying the code of PyXMMS-remote since this can be considered as example code for most PyXMMS functions (well, the ones from xmms.control; for xmms.config, there are examples in the documentation). [1] /tmp/xmms_${USER}.${XMMS_SESSION}, I believe. -- Florent From ajsiegel at optonline.com Mon May 31 09:55:26 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 31 May 2004 13:55:26 GMT Subject: terminological obscurity References: <1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <55ijb01a95i9ccfn2hut9q8dv1gvogut4c@4ax.com> <1085933508.579296@yasure> <63okb0tv8f5fc2ahcfuohafk0og60ic0q0@4ax.com> <40baeaee$0$27038$9b622d9e@news.freenet.de> Message-ID: On Mon, 31 May 2004 10:21:02 +0200, "Martin v. L?wis" wrote: > >With duck typing, the need to even introduce the notion of >types goes away: you invoke operation on objects, and if the >operation makes sense for the object, it will proceed. At >that point, it is irrelevant what other objects would also >allow the operation to proceed. So I am not unjustified in a position that in not understanding typing in Python, I am understanding it fine. which is exactly what my intuition has told me. Art From mrjean1 at comcast.net Tue May 18 16:21:47 2004 From: mrjean1 at comcast.net (Jean Brouwers) Date: Tue, 18 May 2004 20:21:47 GMT Subject: Creating self-contained apps References: Message-ID: <180520041331325503%mrjean1@comcast.net> Check cx_Freeze from /Jean Brouwers In article , Ed Leafe wrote: > Is it possible to create a version of Python, along with several > specific modules, and somehow package it together to be distributed as > a single unit? I remember that Zope did something similar in the past, > but can't recall how that was accomplished. I looked into bdist in > DistUtils, but couldn't find enough info on it to determine if it would > do what I want. > > I have an app that requires a specific version of Python, along with > specific versions of various modules. What I need is a single file that > I can distribute that will run my packaged version of python, assuring > that the user, no matter what Linux distro they are using, will be able > to run it? And while I'm at it, is this also possible in Windows? > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ > > From paddy3118 at netscape.net Sat May 29 03:46:54 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Sat, 29 May 2004 08:46:54 +0100 Subject: Character search Algorithm Message-ID: <7dXtc.31365$FV7.11121@doctor.cableinet.net> Hi, My problem is I'm trying to learn about the implementation of assertion languages like PSL/Sugar in digital logic simulators. The assertion language allows you to more easily say "if this signal combination/sequence follows that signal combination/sequence then ..." I feel that you should be able to think of this as the simulator providing a stream of signal values over simulator time that could be translated into a string of characters interleaved with clock cycle markers. Then the temporal assertion could be translated into a regular expression acting on the string. When I make the mental analogy above, then I think of the practicle problems of such an implementation. The first is, if you have a finite bounded re - e.g. no infinite matches i.e. no plus or star characters in the RE, but you have a simulator churning out a huge sequence of characters, how do you do the RE match efficiently? I am thinking of a program skeleton that looks something like this psl_re = PSL_subset_to_RE(PSL) simulator.start(psl_re.clock, psl_re.signals_to_capture) for cycles_psl_signals in simulator.next_cycle(): if psl_re.optimised_search(cycles_psl_signals): raise PSL_PRE_CONDITION_FOUND It is the psl_re.optimised_search() routine that I am after. Is there any way of computing how big a string buffer needs to be (call it B), so that you could then maybe keep a sliding buffer of a minimum of just the last 2*B characters, sliding along and matching in B character increments and guarantee to find the matches? Help, or alternative algorithms would be appreciated. Thanks, Paddy. From __peter__ at web.de Mon May 17 08:18:52 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 May 2004 14:18:52 +0200 Subject: function causing core dump References: Message-ID: Xaver Hinterhuber wrote: > My problem is now, that I get unicode encoding errors. > I am working on a german windoze machine. > Could you plz give me a tip what encoding I should use (iso8859-1 and > utf-8 dont't work)? Other popular encodings are cp1252 and ISO-8859-15. Since your new problem is totally unrelated to code objects and core dumps, you should start a new thread. Remember to include as many hints that could help solve your problem as possible. Providing a piece of code and a traceback is always a good idea, since you could be misusing the api rather than have picked the wrong encoding. Having this newsgroup suggest random encodings is certainly not the way to go. Good luck, Peter From riccardo_cut-me at cut.me.sideralis.net Mon May 3 22:17:43 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Tue, 04 May 2004 04:17:43 +0200 Subject: python/pyGtk : How to generate a keyboard interrupt? References: Message-ID: On Mon, 03 May 2004 13:36:01 -0400, Peter Hansen wrote: > Riccardo Attilio Galli wrote: > >> On Sat, 01 May 2004 08:31:07 -0700, ahk wrote: >> >>>I would like to emulate the keyboard interrupt through other means >>>other than the actual hitting on the keyboard such that a call to >>>scaninput() (a C function call?) will be able to pick up the >>>interrupt. How is it possible to do that in python/pyGTK? TIA. >> >>>>>raise KeyboardInterrupt >> >> Traceback (most recent call last): >> File "", line 1, in ? >> KeyboardInterrupt > > I think I detect two people on very different wavelengths > here. Forgive me if I'm wrong. > > I think the OP is talking about the "keyboard interrupt" > in the sense of the low-level mechanisms by which keystrokes > get into the PC. Each key hit on the keyboard causes data > to be sent on the serial link between the keyboard and the > motherboard. The motherboard has circuitry which decodes > the keystroke and generates a hardware interrupt through the > PIC (Programmable Interrupt Controller) chip or the modern > equivalent. > > People with a hardware or low-level software background will > sometimes talk about "keyboard interrupts" when they really > just mean to ask about receiving raw keystrokes in their > software. shame on me. I'd have a low background, but I forget to use it :) I completely misunderstood the OP. ops Riccardo From maney at pobox.com Sat May 15 14:55:14 2004 From: maney at pobox.com (Martin Maney) Date: Sat, 15 May 2004 18:55:14 +0000 (UTC) Subject: Cash Register References: <2gdlu5F1kmmvU1@uni-berlin.de> Message-ID: Greg Ewing wrote: > I notice it's nicely agnostic about what kind > of numbers are used. This will come in very handy > if complex currency is ever introduced... > ITEM $ 3.50 > ITEM $ 2.30j > ITEM $ 1+2j > ITEM $ 0 > TOTAL $ (4.5+4.3j) > CASH $ 50 > CHANGE $ (45.5-4.3j) Beautiful demonstration of the principle behind the rule that items with complex prices may only be sold in conjugate pairs! :-) -- automation: replacing what works with something that almost works, but which is faster and cheaper. - attributed to Roger Needham From m4 at polite.se Thu May 27 16:40:36 2004 From: m4 at polite.se (Alex Polite) Date: 27 May 2004 20:40:36 GMT Subject: Saving recursive objects to disc. cPickle wan't work. In-Reply-To: References: <20040526142220.GA2289@matijek.v10a.ath.cx> Message-ID: <20040527204037.GB2175@matijek.plusseven.com> On ons, maj 26, 2004 at 04:34:00 +0200, Lutz Horn wrote: > Hm, the documentation of Python 2.3.2, Section 3.14.1 "Relationship to > other Python modules" states that recursive objects, which are defined > as "objects that contain references to themselves" can't be handled by > marshal, but that pickle and cPickle should be fine: "pickle stores > such objects only once, and ensures that all other references point to > the master copy". > > What exactly are your problems? That sound promising. I'm building a library to generate markov models from text, much like dadadodo. You can get the code here. http://snippsnapp.polite.se/wiki.pl?PyDodo When I run my testsuit that tries to pickle a generated markov model I get this: python test/basicsuite.py 1000 E ====================================================================== ERROR: test_pickle (__main__.BasicTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "test/basicsuite.py", line 73, in test_pickle print sys.settrecursionlimit(4000) AttributeError: 'module' object has no attribute 'settrecursionlimit' ---------------------------------------------------------------------- Ran 1 test in 0.002s If I up the recusionlimit the testsuit will segfault. alex -- Alex Polite http://polite.se From "schwartz+ at usenet " at bio.cse.psu.edu Fri May 14 17:13:42 2004 From: "schwartz+ at usenet " at bio.cse.psu.edu (Scott Schwartz) Date: 14 May 2004 17:13:42 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> <8gisf1ihvc.fsf@galapagos.bx.psu.edu> Message-ID: <8g4qqik8zd.fsf@galapagos.bx.psu.edu> "Andrew Dalke" writes: > > 2) Python generators on stdin behave strangely. For one thing, > > they're not properly line buffered, so you don't get any lines until > > eof. But then, eof is handled wrongly, and the loop doesn't exit. > > There's a command-line flag to make stdin/stdout be unbuffered. > Try your test again with 'python -u'. No effect, because that's not the problem. The generator is reading ahead and doing it's own buffering, in addition to whatever the stream is doing (or not doing). Hence the bug. From skip at pobox.com Sun May 2 14:52:59 2004 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 May 2004 13:52:59 -0500 Subject: [OT] does the charset lie? In-Reply-To: <409530F5.5040306@python.org> References: <16533.8123.5800.539196@montanaro.dyndns.org> <40952451.3020106@python.org> <16533.12062.56470.647993@montanaro.dyndns.org> <409530F5.5040306@python.org> Message-ID: <16533.17291.943262.233745@montanaro.dyndns.org> >> data = unicode(data, "iso-8859-1").encode("utf-8") >> data = map_entities_to_utf_8(data) >> data = unicode(data, "utf-8") David> Or, even simpler, skip the intermediate step: David> data = unicode(data, "iso-8859-1") David> data = map_entities_to_unicode(data) David> map_entities_to_unicode() could use htmlentitydefs.name2codepoint David> from the stdlib. Thanks, I always forget there's an htmlentitydefs module. Skip From fredrik at pythonware.com Tue May 25 09:05:27 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 15:05:27 +0200 Subject: Newbie question References: Message-ID: "mp312" wrote: > Taking a user id that is in the format 'userid at MACAddress', read the > userid portion (varying length) and concatenate with @honigman.com. here's one way to do it: userid.split("@")[0] + "@honigman.com" for more on string/text handling in Python, see: http://gnosis.cx/TPiP/ From shalabh at cafepy.com Fri May 21 16:30:23 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Fri, 21 May 2004 13:30:23 -0700 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Michael > Chermside wrote: > >>> All tuple methods are also list methods, and most list methods >>> are also tuple methods; among those that are NOT also tuple >>> methods, there are exactly two ('count' and 'index') that do >>> not involve mutation. Is there any special reason why they >>> AREN'T also tuple methods? >> >> Yes. Both make sense only if you consider a tuple as a homogeneous >> sequence of items, and that's not what Guido intended it to be >> used for. > > I'm sure I'm being dim, but I don't understand what homogeneity > has to do with it. > > For example, why shouldn't index() find an object in a > non-homogeneous sequence? Either the object is in the sequence or > it's not. If it is, there is an index that corresponds to it. > > The relationship > > (a,b,c,d,e)[3] is d > > is true regardless of the types of a,b,c and e. > > I can maybe see why not supporting sort() or reduce() on a > non-homogeneous sequence makes sense if one was of the opinion > that it should be illegal to use a binary operator on two > objects whose types differ, but I don't see why either count() > or index() should have anything to do with homogeneity, since > it pretty much has to be OK to use "is" or "==" on objects of > differing types. > I believe it is conceptual homogeneity and not type homogeneity that characterises the difference between lists and tuples. Consider use of tuples such as (hostname, port) or (firstname, lastname, middleinitial) or (x_coordinate, y_coordinate). In all cases you *know* what the first element means, what the second element means etc. It is usually not useful to find a value since the different values mean different things. You might rather do this something like - if host_port[1] == 80:... This might be the reason there is no index() on tuples - no convincing use case. -- Shalabh From vorbote at shangri-la.invalid Thu May 20 15:44:27 2004 From: vorbote at shangri-la.invalid (Alejandro =?iso-8859-1?Q?L=F3pez-Valencia?=) Date: 20 May 2004 19:44:27 GMT Subject: How to Build Python 2.3.3 C/C++ Extensions in Windows Using Mingw32 References: Message-ID: On 2004-05-20, C. Barnes wrote in : > > 2. Get PExports from either of: This is awfully outdated. > > http://sebsauvage.net/python/pexports-0.42h.zip > > http://starship.python.net/crew/kernr/mingw32/pexports-0.42h.zip > > Extract pexports.exe to your Mingw bin directory. Rather go to http://mingw.org/ and download the mingw-utils package. Hopefully that's the same place you obtained your compiler, linker and libraries. A better writer wants to submit a patch for the distutils manual? -- Alejandro L?pez-Valencia qenqhy ng rgo qbg arg qbg pb http://dradul.tripod.com/ \u864e\u306e\u795e\u6bbf From tdelaney at avaya.com Thu May 6 02:54:50 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 6 May 2004 16:54:50 +1000 Subject: What does 'is' do? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01729D87@au3010avexu1.global.avaya.com> Derek Fountain wrote: > I recently saw a use of 'is' in a piece of Python code. I was trying > to find out what it does. I can't find it in the online docs. I have > the "Python in a Nutshell" book and that mentions it as a keyword, > but I can't find a description of it in there either. It's not in the > index. > > Can someone tell me where to look? http://docs.python.org/lib/comparisons.html Tim Delaney From svein+usenet01 at brage.info Mon May 17 17:49:08 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Mon, 17 May 2004 23:49:08 +0200 Subject: Python compilers? Message-ID: Is anyone working on a python-to-native compiler? I'd be interested in taking a look. Come to think of it, is anyone working on a sexpr-enabled version of Python, or anything similar? I really miss my macros whenever I try to use it... From peter at engcorp.com Sun May 16 09:43:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 16 May 2004 09:43:25 -0400 Subject: Python for Large Projects In-Reply-To: <10ae406ck3q1gb1@corp.supernews.com> References: <10ae406ck3q1gb1@corp.supernews.com> Message-ID: Ixokai wrote: > There is some concern that if we do this same > thing with Python, the performance hit of loading an interpreted environment > over the shared filesystem will be prohibitive. Some basic testing has made > this seem to be the case. Just focusing on this one point: it doesn't make sense to me that this would be the case, and in my experience it is not. The interpreter (python23.dll for example on Win32) is less than 1MB and that's basically _tiny_ these days. We always had a single shared instance of Python and never noticed more than a small fraction of second delay compared to loading it locally. This was a network with only about fifteen developers as users, and 100MBps throughout, but I would think almost any program these days is going to be 1MB or more, so I can't see that Python has any disadvantage in this area. -Peter From andrew-pythonlist at puzzling.org Thu May 13 03:05:28 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 17:05:28 +1000 Subject: perl to python In-Reply-To: References: <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: <20040513070528.GC20388@frobozz> On Thu, May 13, 2004 at 06:06:23AM +0000, Andrew Dalke wrote: [...] > > Trying doing that sanely with any programming language expressed > all on the command-line. No credit if you can't handle the '&' and space. I'm almost positive you can do that entirely with bash[1], actually. I don't have time to prove it right now, though... but you ought to be able to use features like ${paramater%word} expansions, e.g.: $ x='something.mbox/mbox' $ echo ${x%/mbox} something.mbox Obviously you'd need to be careful about quoting things like & and space, but that doesn't seem too hard. -Andrew. [1] And standard file utilties like mv and rmdir, obviously... From roy at panix.com Thu May 6 15:44:31 2004 From: roy at panix.com (Roy Smith) Date: Thu, 06 May 2004 15:44:31 -0400 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: In article <997a06e0.0405061128.6768676d at posting.google.com>, pugnatio2 at yahoo.com wrote: > What's the standard way to implement polymorphic behavior in a python > method, given that method arguments can't declare their types as > they're being passed in, and method definitions don't have signatures? > > For instance, if I wanted to write a method that auto-detected whether > it was being passed a string or a tuple/list, how would I do so > without using type() to identify the parameter's type? Using type() is > deprecated in the documentation I've read. > > Thanks in advance. For the most part, the kind of polymorphism you see in staticly typed languages like C++ and Java just isn't necessary in Python. Between dynamic typing (i.e. you can take the str() of anything without knowing what type it is) and keyword arguments, there's very little reason to have to know what type an argument is. The most common reason is the example you gave, where you want a function which will operate on either an item, or a bunch of items. You might want to be able to say: nuke ("Perl") to get rid of everybody's least favorite language, and also be able to pass in a bunch of them: nuke (("C++", "Java", "Perl")) to get rid of all three at once. If you really wanted to do that, you could define nuke something like: def nuke (lang): if isinstance (lang, types.TupleType): for oneLanguage in lang: nuke (oneLanguage) else: whatever In general, however, I try to stay away from stuff like that. From j_mckitrick at bigfoot.com Mon May 24 10:33:15 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 24 May 2004 07:33:15 -0700 Subject: Problem with PyGTK/Glade2 ComboBox vs ComboEntryBox References: <40AF5FDD.7030604@draigBrady.com> Message-ID: Thank you both! I have the latest pygtk AND used the docs to get the combo box working. Thanks again! jonathon From howard.stearns at charter.net Sat May 29 14:48:46 2004 From: howard.stearns at charter.net (Howard Stearns) Date: Sat, 29 May 2004 13:48:46 -0500 Subject: generic functions in python In-Reply-To: <2hr9vnFfaqsjU1@uni-berlin.de> References: <2hr9vnFfaqsjU1@uni-berlin.de> Message-ID: <40B8DB0E.1040105@charter.net> Funny you should mention this today -- I was just sitting down to implement generic functions myself. It tends to be the first thing I do when learning a new language, and I'm brand new to Python. My needs are limited, so I'm not thinking past the first pass, in which there will be no provision for subclassing your own kinds of Generic_Function and no syntactic sugar (e.g, no defmethod, just hand intialization at load time of new methods, and hand coordination between the function object and the Generic_Function object, and no Funcallable_Instance class). Just basic multimethod dispatch with a simple cache. As much as I believe Dylan's class precedence linearization is "The Right Thing(tm)", I'll just do whatever's easiest for ordering the classes. Anyway, I'll know more when I get into it. When I finish (who knows when?), I'll try to remember to post here and cc you, Jim. Please do the same with me if you come up with anything, and please ping me after a bit if I forget. Jim Newton wrote: > hi all, i'm relatively new to python. I find it a > pretty interesting language but also somewhat limiting > compared to lisp. I notice that the language does > provide a few lispy type nicities, but some very > important ones seem to be missing. > > E.g., the multiple class inheritance is great, > but there are no generic functions (at least that > i can find). If i have classes X, Y, and Z, > and subclasses X_sub, Y_sub, and Z_sub respectively. > > I'd love to write methods which speicialize on pairs > of these classes. It works in lisp as follows > > (defmethod mymethod (( x X) ( y Y)) ;; # 1 > ...) > > (defmethod mymethod (( x X_sub) ( y Y)) ;; # 2 > ...) > > (defmethod mymethod (( z Z) ( x X)) ;; # 3 > ..) > > > Then for example if i call mymethod with > an instance of X_sub and Y_sub then # 2 > gets called. > > These multi-methods are extremely useful to the > lisp programmer. > > How do python programmers work around this limitation? > > One option would be to force all methods to have > a huge case statement inside them which tests > the class of the second argument. And everytime a new > class is added, all the case statements have to be > revisited and updated accordingly? > > Is there a better way? perhaps there is a standard > mult-method-dispatch package available for use? > > -jim > From Scott.Daniels at Acm.Org Mon May 17 18:52:24 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 17 May 2004 15:52:24 -0700 Subject: module for working with the result set In-Reply-To: References: Message-ID: <40a94736$1@nntp0.pdx.net> Try: ... for coldesc in cursor.description: print coldesc[0], print for row in cursor.fetchmany(10): print row .... -- -Scott David Daniels Scott.Daniels at Acm.Org From zunbeltz at wm.lc.ehu.es.XXX Mon May 31 08:30:58 2004 From: zunbeltz at wm.lc.ehu.es.XXX (Zunbeltz Izaola) Date: 31 May 2004 14:30:58 +0200 Subject: exceptions References: <0s6dnS4bi552vybdRVn-jw@powergate.ca> Message-ID: Peter Hansen writes: > Zunbeltz Izaola wrote: > > I've the following problem with try/exception. > > I've a try block that will raise some exceptions. > > I want the program to ignore this exceptions completely. Is it > > possible? > > In the following, all exceptions will be ignored: > > try: > # something that raises exceptions > except: > pass > I've trid this, but the problem is that this finished the try block. I want to continue executing the try block from the point the exception was raised. > This is definitely *not* a recommended way to write software, > however. You should really understand what you are doing before > writing code this way. > I know. I need this feature for testing. I will desable it later. Zunbeltz > -Peter -- Zunbeltz Izaola Azkona | wmbizazz at lg dot ehu dotes Materia Kondentsatuaren Fisika Saila | Zientzia eta Teknologia Fakultatea | Phone: 34946015326 Euskal Herriko Unibertsitatea | PK 644 | Fax: 34 944648500 48080 Bilbo (SPAIN) | From amartin at wpsnetwork.com Fri May 28 03:21:07 2004 From: amartin at wpsnetwork.com (Aurelio Martin) Date: Fri, 28 May 2004 09:21:07 +0200 Subject: pdf2txt In-Reply-To: References: Message-ID: <2ho7j6Ff6up8U1@uni-berlin.de> B P wrote: > Is there a way via Python or even Perl to capture records from a pdf and > output a delimited text file? My work has a situation with a trunk > load of data forms that were scanned as pdfs. > > The data needs to be taken from the forms and moved into a database, so > I figure that comma-delimited format will work fine. The amount of > man-hours it would take to manually do this is very cost-prohibitive for > what we have to work with. > > I know that a txt2pdf exists, was checking to see if the opposite would > as well. > > BP You may try XPDF http://www.foolabs.com/xpdf/ They include source code and some utilities like pdfimages of pdftotext. Maybe you can call these from Python, or link via a C extension. Hope this helps Aurelio From fractalgfx at ameritech.net Thu May 27 12:50:37 2004 From: fractalgfx at ameritech.net (Michael Robinson) Date: Thu, 27 May 2004 16:50:37 GMT Subject: Sporadic problems importing xml.dom.minidom Message-ID: Sometimes when I run a program I get the message "Import:Error No Moduel named dom.domino", sometimes it imports OK. It seems to depend on the working directory when I star the program. /home/mike/projects/xml_test/test.py: Gives an erroor, the same file luanched from /home/mike/projects/xml1/test.py: runs without a problem I am running the python 2.3 package, bundeld with Fedora Core 2. From jfabiani at yolo.com Fri May 14 00:35:49 2004 From: jfabiani at yolo.com (john fabiani) Date: Fri, 14 May 2004 04:35:49 GMT Subject: I need newbie help In-Reply-To: References: <10a83t8qku40d44@corp.supernews.com> Message-ID: Sean Berry wrote: > "Joseph Davidson" wrote in message > news:10a83t8qku40d44 at corp.supernews.com... > >>I am an experienced perl programmer learning python ( no commente please >>). >> >>In looking at a sample script at >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708 >> >>I found the following code snippet. >>-------------------------------------------------- >>location = 'myHome' >>fileLocation = {'myHome' :path1, >> 'myOffice' :path2, >> 'somewhere':path3}[location] >> >>----------------------------------------------------- >> > > > fileLocation takes the 'value' of the 'key' "location" > equilvalent to: > > location = 'myHome' > files = {'myHome' :path1, 'myOffice' :path2, 'somewhere':path3} > fileLocation = files[location] > > >>It seems that this is setting up fileLocation as a dictionary, but what >>is the "[location]" doing? >> >>Joe Davidson >> >>-- > > > I'm also a newbie. Did the programmer that wrote the code not use your way (3 statements) because his statement was faster or because it better python? John From winexpert at hotmail.com Tue May 25 08:51:14 2004 From: winexpert at hotmail.com (David Stockwell) Date: Tue, 25 May 2004 12:51:14 +0000 Subject: hard disk serial Message-ID: Hi, What OS are you targeting? Or are you looking for an OS independent solution? David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: >To: python-list at python.org >Subject: hard disk serial >Date: Tue, 25 May 2004 14:44:49 +0200 > >Hi every one >I try to get hard disk serial number >how can i do this ? > >-> THANK'S A LOT > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Best Restaurant Giveaway Ever! Vote for your favorites for a chance to win $1 million! http://local.msn.com/special/giveaway.asp From jfabiani at yolo.com Thu May 13 01:19:56 2004 From: jfabiani at yolo.com (john fabiani) Date: Thu, 13 May 2004 05:19:56 GMT Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: References: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <87pt99tmyl.fsf@pobox.com> Message-ID: <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> Peter Hansen wrote: > john fabiani wrote: > >> I'm guessing but I bet that simple text can be sent to a printer using >> Python (looping of course). But in today's world most users want >> graphics along with the data. Like an invoice with a logo, boxes >> around the bill to and ship to, along with column lines. So I'm >> hoping that someone has at least started a project to print reports. > > > That would be "ReportLab", I would think... Google for it. > > -Peter I book marked it - but it looks like a web solution?????? John From jcarlson at uci.edu Wed May 12 18:39:41 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 12 May 2004 15:39:41 -0700 Subject: Ideas for Python 3 In-Reply-To: <2r91a0tlksovkn20maa7mk5vekr8h2joa5@4ax.com> References: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> <2r91a0tlksovkn20maa7mk5vekr8h2joa5@4ax.com> Message-ID: >>I've read the link you posted, and I've previously taken a look at >>Prothon. Prototype syntax does not suit my taste in programming >>languages. If Python 3.0 becomes Prothon, I'll fork the most recent >>Python 2.x codebase that I prefer, maintaining it myself if necessary. >> >>Just as my anti-prototype perspective colors my opinions on what is >>reasonable, I would imagine that your pro-prototype perspective colors >>yours. > > I am currently neutral on the idea of prototypes, still waiting for > anyone to show me a good use case, so I can include it in my webpage. > I still have "cloning" of instances in my proposal, but you will > notice they are at the bottom of the list of benefits at > http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm Considering that you provide an animal heirarchy use-case to illustrate what you propose, I'd say that you're a bit on the positive side of neutral. I don't believe I understand the idea of "cloning", at least in terms of prototypes. In my mind it brings up either using a copy() method on instances, or using instance1.__dict__.update(instance2.__dict__) to transfer instance variables. Unless there is more (or an actual) description about what a "clone" is, I can't say whether it is a benefit or drawback. > I typically get enthusiastic about something when I first see it, then > I learn a little more, and some of the new tricks/features drop to the > bottom of my list. What remains of my original enthusiasm for Prothon > is still in the unification of methods and functions. I guess I must be an "Expert", because unifying methods and functions doesn't seem to be necessary to me. While some (including yourself) state that it would make learning portions of Python easier, never having had issues handling lambdas, functions, class methods, static methods, or instance methods, I don't know what people have issues with. Really the question is: "Is there a problem with current function, method, etc., syntax?" If there is a problem, the next question is, "What are people having problems understanding?" At some point there would likely be examples provided that show where the user was confused. Documenting those examples to explain the syntax, I believe, would be sufficient, but then again, I RTFM. In terms of instance variables and accessing via .variable, I would imagine the lack of 'this' (for C++ or Java programmers) or 'self' (for Python programmers) to be somewhat disconcerting, and though '.' is used to denote a namespace heirarchy in functions, modules, classes, etc., having it lead a an instance variable or function suffers from the same "punctuation-itis" that is listed as a drawback for various function definition syntaxes. For those that I come across who are hung up on the handful of syntaxes available for functions/methods, I point out that really only two are generally needed (function(), instance.method()). The others are merely there to make life easier for 'advanced' users, and if are not labeled as such, should be (class.method(instance) is pretty useful, as can be lambda, and are the two 'advanced' function types that I use). By only introducing the two major syntaxes, whose only difference is the naming of the referenced instance (for flexibility), I believe the vast majority of people who had troubles before, would have very few now. > The key to finding what is fundamentally good in these other > languages, and what is just someone's personal preference for being > different, is keeping an open mind. It's astonishing how few people > can do that in comparing computer languages. I guess it is just > easier to be "anti" or "pro" and skip the investigation and thinking. On that note, I am relatively closed-minded about (even suggested) alterations to Python because it works so well for me /now/, I'm being paid to write software with it /now/, of the alterations that are being offered, I don't believe any would increase my productivity /soon if ever/, and I find them to be both aesthetically unpleasing, as well as relying on the assumption that people don't /currently/ understand Python. I believe that the current learning curve of Python is sufficiently gradual as to allow the vast majority of people to use it effectively. Knowing the ins and outs of the entirety of the language is not necessary, and even a reasonable subset excludes staticmethods, metaclasses, etc. >>I would also expect that someone who enjoys using lisp or >>perhaps SML would have their opinion on what is reasonable, colored by >>their preferences. Considering that Python is not a prototype-based >>language today in 2.3 (or the forthcoming 2.4 in the fall), having it >>become one in Python 3 would be quite a drastic change, quite literally >>like going from Python 2.3 to Prothon. > > I continue to find new surprises in Python. The ability to change > classes into prototypes by using descriptors is the latest exammple. > This seems like a drastic change, but it is all within the capability > of Python. Being able to use prototypes, without prototype syntax, is not changing the language syntax. The fact that Python doesn't need prototype syntax to have prototypes, I believe, is an argument against altering Python's syntax. > Prothon does have some changes that are more drastic, but in my > opinion have no real benefit over Python. I measure drastic by how > much effort it will take to translate existing Python programs to > Prothon. By this measure, the unification of functions and methods is > not a drastic change. I believe it will be possible to automatically > translate all Python methods into the new form. So if we categorize > syntax changes as ( Compatible / Migratable / Totally Different ), the > proposed changes are in the middle. Function/method unification is certainly migratable, I've never claimed otherwise. In fact, with a good refactoring tool, it is trivial (and actually a search+replace will go a long ways towards migrating). The '.' prefix "punctuation-itis" I described earlier, coupled with your statement that __self__ is magical (more or less so doesn't matter much), suggests that together, they are trying to replace an easy to understand magic, with another easy to understand magic. The only /real/ change that the function unification is advocating, is the replacement of an explicit name for something that is passed implicitly, with an implicit name for something that is passed implicitly, and the replacement of an explicit instance name with no name at all. Which is better is debatable, but I prefer the current Python syntax, due to the reduced number of implicit items (only the instance is implicit, as compared with the instance, name, and instance references in prototype syntax). - Josiah From nospam at nospam.com Sat May 22 14:13:35 2004 From: nospam at nospam.com (Sholtz) Date: Sat, 22 May 2004 18:13:35 GMT Subject: newbie: how to capture/write to stdio on NT Message-ID: Hi, I am trying to figure out how to 'control' the input & output using popen/popen2 etc on Python 2.3 I have found examples for unix such as the one below but I can't get it to work on Windows NT. If I use the os.popen module I can read OR write not both. Anybody have any ideas? Regards, Sholto. # Open command in a pipe # which reads from stdin and writes to stdout import popen2 pipe = popen2.Popen4("wc -l") # Unix command pipe.tochild.write("line 1\nline 2\nline 3\n") pipe.tochild.close() output = pipe.fromchild.read() From ocrow at skymind.com Sun May 2 13:54:44 2004 From: ocrow at skymind.com (Oliver Crow) Date: 2 May 2004 10:54:44 -0700 Subject: Efficient string concatenation methods References: Message-ID: Peter Hansen wrote in message news:... > You left out the StringIO module (having done only the cStringIO > version of that). I should probably add that one just for reference. I left it out originally because my instinct was that it would perform less well than the string += operator. I think it uses ordinary immutable python strings for internal storage. > Note also that, for any of the ones which do method calls, > you can speed up the call by saving a reference to the > bound method in a local variable. For example, in method 4 > you can do "app_list = str_list.append" and then use > "app_list(`num`)" instead of str_list.append(`num`). This > saves an attribute lookup on each loop iteration. It's > not "idiomatic" to do so except in (a) cases of optimization > obsession, or (b) benchmarks. ;-) I hadn't thought of this, although it makes sense. It looks like I could do this in methods 3, 4 and 5. But I also feel that it makes the code a little less readable. I think the unstated goal I had was to find a method that could be learned by python programmers and used in real programs without having to think *too* hard about the various performance trade-offs. So, in that spirit I should definitely measure the difference, but perhaps not go so far as to recommend it as part of the best overall approach. > Interesting and useful results. Thanks! :-) Thanks! Oliver From lho at gmx.de Thu May 13 04:22:56 2004 From: lho at gmx.de (Lutz Horn) Date: Thu, 13 May 2004 10:22:56 +0200 Subject: Smalles Possible Browser to display python cgi program In-Reply-To: References: Message-ID: <2ggpjuF2lselU1@uni-berlin.de> * Cornel Ghiban wrote: > * matthiasjanes at gmx.net (matthiasjanes) wrote: > > I would like to know what would be the smalles possible WebBrowser for > > displaying Python CGI application. > > try this one: > http://jan.kneschke.de/projects/lighttpd/ Erm, didn't the OP ask about a browser, not a server? ;) Anyway, take a look into the GNU Free Software Directory, category "Web browsers"[0] or dmoz[1]. A very small browser is links[2], which has both a text and a graphics mode. Lutz [0] http://www.gnu.org/directory/network/browsers/ [1] http://www.dmoz.org/Computers/Software/Internet/Clients/WWW/Browsers/ [2] http://atrey.karlin.mff.cuni.cz/~clock/twibright/links/index.html From timothy.williams at nvl.army.mil Fri May 14 22:02:08 2004 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 14 May 2004 19:02:08 -0700 Subject: How to update window after wxGrid is updated? References: <40a11859$0$560$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: Brian Kelley wrote in message news:<40a11859$0$560$b45e6eb0 at senator-bedfellow.mit.edu>... > Tim Williams wrote: > > Hi. > > > > I'm starting to learn wxPython and for an exercise I'm writing a > > simple CSV file viewer. I just read in the CSV file and create a > > wx.Grid with the data. I'm using Python 2.3.2 with wxPython 2.4.2.4. > > > > Everything runs fine under linux, but when I try the same code on a > > Win XP machine, I have a window, but the frame the grid is in isn't > > seen until I do a minimize/maximize on the window. Besides that, it > > seems to run fine. I tried to do a self.Refresh(True, > > self.grid.GetRect()), but that didn't help. > > Annoying isn't it? There are probably many solutions to this problem, > but the one that I use is: > > > self.grid.AutoSizeColumns(True) > > #self.Refresh(True, self.grid.GetRect()) > self.twiddle() > > def twiddle(self): > x,y = self.GetSize() > self.SetSize((x, y+1)) > self.SetSize((x,y)) > > This forces a repaint of the window and will also add scroll bars if > necessary. You are welcome to join us on the wxpython user list as well > for more in-depth answers. > > You have an unrelated bug in your code as well: > > for i in len(row): > > should be > for i in range(len(row)): > > > Brian Thanks. I caught this bug after I posted. I've been in a class the last 3 days. When I get back on Monday, I'll try out your answer and the other poster's one. From christopher_culverbutnotthis at yahoo.com Fri May 7 14:29:56 2004 From: christopher_culverbutnotthis at yahoo.com (Christopher Culver) Date: Fri, 07 May 2004 18:29:56 GMT Subject: Newbie : Greek letters References: <8KDmc.45741$Sf4.40969@newssvr29.news.prodigy.com> Message-ID: <533d6c6fafbf3d9231eb53099cf64982@news.teranews.com> On Fri, 07 May 2004 03:52:36 +0000, asdf sdf wrote: > Oh Kyu Yoon wrote: >> Is there an easy way to include greek letter symbols in TextCtrl of >> wxPython? >> >> > this is only a idea. no experience with it myself. Try using SetFont > to get Symbol font. Symbol font is available on WinPCs. Couldn't say > about any other platforms though. That is a bad idea. Not only does it break cross-platform compatibility (the goal of wxWindows) by using a proprietary font, it totally ignores Python's excellent Unicode support. Greek has it's own block in Unicode, you just have to create the characters from there. Using special fonts to overcome character sets is sooooo 1998. Christopher Culver From csgcsg39 at hotmail.com Wed May 12 10:58:18 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Wed, 12 May 2004 15:58:18 +0100 Subject: max value in list Message-ID: Dear all, I have a few lists. What's the best way of finding the maximum number of all the lists. For example, [2,3,4],[1,2,3],[4,7] The max is 7. Thanks Colin From dplatte1 at rochester.rr.com Wed May 5 15:24:36 2004 From: dplatte1 at rochester.rr.com (Dave Platten) Date: Wed, 05 May 2004 19:24:36 GMT Subject: pty.py Message-ID: could someone please help me with how to use this with a couple of examples? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From noemail at noemail4u.com Tue May 4 08:48:48 2004 From: noemail at noemail4u.com (Daniel 'Dang' Griffith) Date: Tue, 04 May 2004 12:48:48 GMT Subject: changing directories from within the shell References: Message-ID: On Mon, 3 May 2004 09:27:09 -0400, Darren Dale wrote: >I am sure this has been covered in the documentation, but I havent found >it. Could anyone tell me how to change directories from within the >python shell? Or install IPython, and you can use "cd xyzzy", just like you were in the usual command line shell. (And a whole lot more!) Details available at: http://ipython.scipy.org/ --dang From mcfletch at rogers.com Wed May 26 16:01:36 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 26 May 2004 16:01:36 -0400 Subject: Inclusion Guards Necessary? In-Reply-To: <889cbba0.0405261147.3835adef@posting.google.com> References: <889cbba0.0405261147.3835adef@posting.google.com> Message-ID: <40B4F7A0.30606@rogers.com> Kamilche wrote: >Are inclusion guards necessary to prevent multiple modules from >importing the same shared module multiple times? > > No, multiple imports of a python module just do a lookup and return the same module object as was returned by the previous import. HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ blog: http://zope.vex.net/~mcfletch/plumbing/ From cookedm+news at physics.mcmaster.ca Thu May 20 18:52:39 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 20 May 2004 18:52:39 -0400 Subject: GTK or TKinter (or what else?) References: Message-ID: At some point, "David M. Cook" wrote: > While not absolutely ideal for win32 because of look-and-feel issues, Gtk > does run well under win32. There's even a win32 theme, so it just comes > down to feel in a few places. Maybe someone else can speak to the Mac > situation. > > Dave Cook There is no native port of GTK+ 2 to the Mac, so you'd be stuck running under the X server (not ideal). There is a port of GTK+ 1.2, though (gtk-osx.sf.net). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From cookedm+news at physics.mcmaster.ca Thu May 6 19:39:13 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 06 May 2004 19:39:13 -0400 Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> Message-ID: At some point, Steve Lamb wrote: > On 2004-05-06, Graham Dumpleton wrote: >> I then type ^Ke and it will pipe the whole contents of the file being edited >> through "expand" which will turn all tabs into appropriate number of >> spaces. Typing ^Ku does the opposite. > >> You could run the "expand" program outside of vi as well as part of a shell >> script and do all your files at the same time. > > Couldn't they just also just add a global %s/\t/ /g to the loading of > .py files and be done with it? :) Not if you've mixed tabs and spaces. A tab isn't 8 spaces (or 4 spaces); it should move to the next tabstop, so for instance the '*' line up in the following: >>> print ' \t*' * >>> print '\t*' * -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From peter at engcorp.com Sat May 15 00:10:28 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 00:10:28 -0400 Subject: NIC adress of incoming socket. In-Reply-To: <40a4f772$0$2280$afc38c87@news.easynet.fr> References: <40a4f772$0$2280$afc38c87@news.easynet.fr> Message-ID: RosalieM wrote: > How can i know the nic adress from an incoming socket ? > I can easily know the ip adress and port number but how do i have some > information about arp level ? In addition to Andreas' answer: I'm not even sure the problem has a well-defined solution in general. Isn't it possible that individual packets in the data stream (assuming this is TCP, for example) can be routed through different networks (and, therefore, different NICs) on some machines? If you want to limit this to the simple case of one NIC per machine, then you still need to resort to platform-specific things like parsing the output of some external command to match up IP address and "NIC address" (which is also not necessarily well-defined, but I assume you mean Ethernet address there). -Peter From cappy2112 at yahoo.com Mon May 31 03:12:12 2004 From: cappy2112 at yahoo.com (Tony C) Date: 31 May 2004 00:12:12 -0700 Subject: OT: Python in a Nutshell References: Message-ID: <8d3e714e.0405302312.1e496de5@posting.google.com> "kbass" wrote in message news:... > Does anyone have an idea when the next release of the book, ' Python in a > Nutshell' will come out? I am looking for reference material that covers > Python 2.3 other than the online documentation. I also notice that Amazon > and other book outlets have cut the price on this book so I am hoping that > this is an indication that another book is coming out soon. Your thoughts. > Thanks! > > kbass Python in a Nutshell DOES cover Python 2.3(but not exclusively), and often contrasts the differences between 2.2, and 2.3. (Take a look at the upper right corner of the book) Learning Python Second Edition (also from Oreilly) also covers Python 2.3, and was just released in 2004 From __peter__ at web.de Mon May 3 05:34:23 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 May 2004 11:34:23 +0200 Subject: Sorry, was Re: Method binding confusion References: Message-ID: Sorry, my above answer has several errors, please discard. Peter From eurleif at ecritters.biz Tue May 18 00:22:03 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 18 May 2004 04:22:03 GMT Subject: Python compilers? In-Reply-To: References: Message-ID: Svein Ove Aas wrote: > Is anyone working on a python-to-native compiler? > I'd be interested in taking a look. What are you trying to achieve? If it's faster code execution, the primary slowdown with a very high-level language like Python is caused by high-level data structures (introspection, everything being an object, etc.), not the code itself. A native compiler would still have to use high-level data structures to work with all Python code, so the speed increase wouldn't be very much. If it's ease of distribution you're looking for, I think distutils can make standalone programs on Windows, and most Linux distros have Python installed by default. If you just think a compiler would be cool (or would like to see how it would be done), check out Psyco, Pyrex, and probably some other projects. Pyrex even combats the speed issue by allowing native C types to be used in addition to Python high-level types. From grante at visi.com Thu May 13 18:37:47 2004 From: grante at visi.com (Grant Edwards) Date: 13 May 2004 22:37:47 GMT Subject: struct doesn't handle NaN values? References: <10a7sklcp58eb5f@news.supernews.com> Message-ID: On 2004-05-13, John Roth wrote: >> > /* XXX This sadly ignores Inf/NaN issues */ >> > >> > That is, the outcome of this is also an accident. >> >> Ah. That needs to be fixed. It should either return a correct >> value or raise an exception. Silently returning wrong answers >> is hardly the way of "least surprises". > > A lot of people would like the whole mess to be fixed. > Unfortunately, nobody has stepped forward to do it, > considering that it's quite a job to do right. Fixing struct would be a start, but I'm a little confused by the documentation. There's a table that clearly defines when it uses "native" vs. "standard" byte-order and size-and-alignment. One assumes that the floating point _representation_ could likewise be native or standard (IEEE), but it never specifies which FP representation is used when. Since "IEEE" is mentioned in the discussion of "standard size and alignment", I would guess that FP native vs. standard representation matches the native vs. standard state of "size and alignment". Is that how others interpret the doc? Is that the behavior others would want? -- Grant Edwards grante Yow! They don't hire at PERSONAL PINHEADS, visi.com Mr. Toad! From jmeile at hotmail.com Wed May 19 12:41:45 2004 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 19 May 2004 18:41:45 +0200 Subject: zope & cvs In-Reply-To: References: Message-ID: <40ab8ff3$1@pfaff2.ethz.ch> Lukasz Indyk wrote: > i work in programming team that has 6 members. we develop our > application in Zope, and we write code using ZMI (Zope Management > Interface). we want to use cvs to control versions of our software. is > it possible use cvs with Zope (without abandoming ZMI), or is there any > other solution that give similar features like cvs and can be used with > ZMI? I think this is not possible because you are storing everything on the Zope DB (or Data.fs) and not on external python Products. The cvs system can't access what inside the Data.fs file is, so, you will see different versions of this file, but you won't be able to know what the differences are. I know Zope has some Version system, but I don't use it because I have had some problems with it a long time ago and I have heard lots of people complaining about it; however, those problems could be already solved in the latest version. Just to take a look to the Zope book, section: "Zope services". You could also tried to search cvs on zope.org; perhaps you can find some product, which does it. You could also tried to post a message on the zope lists (lists.zope.org), since this is a more python specific list. Regards, Josef From tim.one at comcast.net Mon May 24 10:53:24 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 24 May 2004 10:53:24 -0400 Subject: r'\' - python parser bug? In-Reply-To: <5155aad2.0405240635.6c2915a5@posting.google.com> Message-ID: [Konstantin Veretennicov] > ActivePython 2.3.2 Build 232 > >>> '\\' > '\\' > >>> r'\' > File "", line 1 > r'\' > ^ > SyntaxError: EOL while scanning single-quoted string > > Is this a known issue? Yes, and a documented one: an r-string cannot end with an odd number of backslashes. Note that your first expression ('\\') did create a string with a single backslash, although the repr of that string may have fooled you into thinking you got two backslashes. >>> '\\' '\\' >>> len('\\') 1 >>> print '\\' \ >>> > Should i submit a bug report to development? Nope: it's not a bug, and won't change. From apardon at forel.vub.ac.be Fri May 7 03:12:35 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 7 May 2004 07:12:35 GMT Subject: Scope rule pecularities References: Message-ID: Op 2004-05-06, Peter Otten schreef <__peter__ at web.de>: > Antoon Pardon wrote: > >> work arounds to make it work. The point is that although a += b >> is supposed to be syntactic sugar for a.__iadd__(b), you need >> a global (and even that won't help if you have nested functions >> and the a is on an intermediate level) to make the first work >> but not for the second. > > a += b is not just syntactic sugar for a.__iadd__(b), it also rebinds a: > > >>> class A: > ... def __iadd__(self, other): > ... return "marker" > ... >>>> a = A() >>>> a.__iadd__(None) > 'marker' >>>> a ><__main__.A instance at 0x4029bbac> >>>> a += None >>>> a > 'marker' >>>> > > The equivalent a += b would then roughly be a = a.__iadd__(b). Well I would say that seems to go against the intention as stated in the reference manual. += and associated should attempt the operation in place. If you do an operation in place there is no need to rebind the variable. -- Antoon Pardon From gregory_a_bakken at groton.pfizer.com Wed May 12 12:56:38 2004 From: gregory_a_bakken at groton.pfizer.com (Greg Bakken) Date: 12 May 2004 09:56:38 -0700 Subject: zlib and gzip Message-ID: <71401622.0405120856.1e9baf60@posting.google.com> I am writing a python program that recieves 'compressed and encoded' strings from another piece of software. I can successfully uncompress and decode the strings via import base64, zlib def getString(s): s = base64.decodestring(s) s = zlib.decompress(s, -15) return s Now, I want to take a 'readable' text string, and compress and encode it the same way as the other piece of software. I first tried the seemingly obvious (but incorrect) import base64, zlib def makeString(s): s = zlib.compress(s, 9) s = base64.encodestring(s) return s I have also tried using the gzip module to do this like import base64, gzip, StringIO def makeString(s): sio = StringIO.StringIO() gzipper = gzip.GzipFile(mode="wb", fileobj=sio) gzipper.write(s) s = base64.encodestring(sio.getvalue()) return s What I would like to be able to do is take a string s, pass it through the makeString function, and pass the result through the getString function, and end up with the original string s back. I have to stick with the way getString is, so I can handle strings from another program, so I need to adapt makeString accordingly, but cannot figure out how. Greg From michael at foord.net Thu May 27 12:13:50 2004 From: michael at foord.net (Fuzzyman) Date: 27 May 2004 09:13:50 -0700 Subject: ANN : ConfigObj 3.0.0 - Simple config file parsing References: <8089854e.0405260620.230f8319@posting.google.com> <87vfijyxm1.fsf@blakie.riol> Message-ID: <8089854e.0405270813.41cc3fa3@posting.google.com> Wilk wrote in message news:<87vfijyxm1.fsf at blakie.riol>... > michael at foord.net (Fuzzyman) writes: > > > There have been a couple of config file 'systems' announced recently, > > that focus on building more powerful and complex configuration files. > > ConfigObj is a module to enable you to much more *simply* access > > config files. > > What do you thing about yaml for config file ? it's very pythonic with > indentation : > > import yaml > print yaml.load(""" > rub1: > - one > - two > rub2: > - three > - four > """).next() > > {'rub1': ['one', 'two'], 'rub2': ['three', 'four']} > > it can also work on the other side : > > print yaml.dump({'rub1': ['one', 'two'], 'rub2': ['three', 'four']}) > --- > rub1: > - one > - two > rub2: > - three > - four I'm sure YAML is fine - I think ConfigObj is still probably 'simpler'. A basic config file can be created with : config = ConfigObj(filename) config['keyword1] = value1 config['list keyword] = [value2, value3, value4] . . config.write() You can then read it back with : config = ConfigObj(filename) Lot's of extra options of course. The created config files look like config files that most people will be used to creating : "keyword1" = "value1" "keyword2" = "value2" . . . Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From donn at drizzle.com Sun May 23 12:13:14 2004 From: donn at drizzle.com (Donn Cave) Date: Sun, 23 May 2004 16:13:14 -0000 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> Message-ID: <1085328791.560793@yasure> Quoth Arthur : | > |> Consider use of tuples such as (hostname, port) or (firstname, lastname, |> middleinitial) or (x_coordinate, y_coordinate). In all cases you *know* |> what the first element means, what the second element means etc. It is |> usually not useful to find a value since the different values mean |> different things. You might rather do this something like - if host_port[1] |> == 80:... |> |> Can you quote _both paragraphs_ of the above and point out the |> circularity in his explanation? | | Given a tuple (1,1,1) representing X,Y,Z corrdinates, I - for one - | have trouble explaining the heterogenous nature of the data, outside | of the "tuple" sense of the word. I don't know what you mean by `outside the "tuple" sense of the word", but in a way I think that may be nearly the problem. Of course if you consider these objects on their own, the contents of the tuple but isolated from that context, they're as homogeneous as you could want, in fact they would be the very same object. But (I hope) no one articulating this point of view says "homogeneous data", or "homogeneous contents", etc. Of course the very same objects could occur in two separate sequences, one homogeneous and the other heterogeneous. This point is that the tuple itself is heterogeneous, each element having a separate non-interchangeable role; the list is homogeneous, having at most some sort order. The objects don't express this on their own, it's a property of the sequence. |> I don't know if homogeneity is the most useful term to get at the |> distinction as I understand it, but evidently that's how Guido tried |> to explain it, so that's where we start. It can take some explaining. |> We could try to think of better ways to approach it - maybe bring in |> the notion of a tuple as a "product" of its elements - but the parties |> to that discussion would have to 1) understand the distinction, and |> 2) not be satisfied with the way it's currently explained. No sign |> of anyone in that corner yet. | | The best reason to describe the current explanations as a tautology, | is precsiely because it can only really be understood as a meaningful | explanation to those who don't really need one. It does little, in my | opinion, to serve as help for those who might. Well, I don't know if anyone really needs an explanation, and I'm struggling with my understanding of "tautology" to fit it in here, but there is something to what you say. It's kind of a Python nerd topic, not a key that's going to unlock the waiting potential of the language. But for me, I know I didn't get it on my own at first. I tended to use tuples as a `more efficient' sequence type. I think the impetus to reform my thinking came from here, and I think nerd chatter like this does serve some purpose. Donn Cave, donn at drizzle.com From faizan at jaredweb.com Fri May 14 21:30:45 2004 From: faizan at jaredweb.com (Fazer) Date: 14 May 2004 18:30:45 -0700 Subject: Retrieve Email Attachments References: <7b454334.0405131902.60550e4c@posting.google.com> <62328c.l5b.ln@news1.interplanet.it> Message-ID: <7b454334.0405141730.42a454dc@posting.google.com> Wow! Exactly what I needed. Thanks a million! deelan wrote in message news:<62328c.l5b.ln at news1.interplanet.it>... > Fazer wrote: > > > Hello, > > > > I need to access a POP or mayb IMAP based email account and extract > > attachments (probably images) from the email messages. How can this > > be done with the current two module libraries? > i've posted an example script non too long ago: > > > cheers, > deelan From pit.grinja at gmx.de Sat May 1 05:57:23 2004 From: pit.grinja at gmx.de (Piet) Date: 1 May 2004 02:57:23 -0700 Subject: Newbie: Create Executable from single script file Message-ID: <39cbe663.0405010157.781b8610@posting.google.com> Hello, I wrote a python script with a GUI made from wxPython which handles XML files via pyXml. I would like to use that app on a computer which does not have a python installation (and will probably not get one easily). I went (or better ran) through the documentation of the distutils and had a brief look at the py2exe page on sourceforge, but I couldn?t find a detailed description for my particular problem. I don?t want to make a well-documented module for distribution and general use by others, I also do not need anything that makes the installation of my program easy, I do not need any extra files apart from my script (and of course the modules that are imported), I just want to have my single script file run on a machine without python. Is there a simple and fast solution for that? Unfortunatly, I do not have the VC++ compiler, only the nmake-utility (which I have never used before and of which I do not even know the exact purpose). Any hints are greatly appreciated. Piet From newsgroups at jhrothjr.com Thu May 6 12:06:53 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 6 May 2004 12:06:53 -0400 Subject: classes vs dicts References: Message-ID: <109komcifkij6a2@news.supernews.com> "Charlie" wrote in message news:be05f1d.0405060212.43929fe1 at posting.google.com... > Greetings, > > I am pretty new to Python and like it very much, but there is one > thing I can't figure out and I couldn't really find anything in the > docs that addresses this. > > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? > I guess using dictionaries is fastest and easiest, but is this > recommended? > > Thanx for any help. As a number of people have said, there is no "right" answer. My take on it is to ask how the rest of the program is organized. If the rest of the program is object oriented, I'd use a class; if it's procedurally oriented, I'd use a dictionary. In other words, I'd try to keep some conceptual integrity with the program as a whole. John Roth From hamilcar at never.mind Tue May 4 04:19:59 2004 From: hamilcar at never.mind (Hamilcar Barca) Date: Tue, 04 May 2004 02:19:59 -0600 Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> Message-ID: <20040504041954.863$8G@news.newsreader.com> In article <4096E9F8.38ABF26D at shaw.ca> (Tue, 04 May 2004 00:55:13 +0000), SeeBelow wrote: > Must function defs appear earlier in a file than use of their name? No. Function definitions must be executed before the name of the function is referenced. References can be calls but can also be arguments in method calls and values in assignment statements (and there are probably other cases but it's 2:00AM). From tjreedy at udel.edu Sun May 2 23:09:05 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 May 2004 23:09:05 -0400 Subject: Is classless worth consideration References: <69cbbef2.0404290259.fd8d71c@posting.google.com><69cbbef2.0404291209.7a98a799@posting.google.com><8ef9bea6.0404292307.66b78b83@posting.google.com><84Kdnfu3OoN4oA_dRVn-vg@powergate.ca><69cbbef2.0404301243.451c7b26@posting.google.com> <69cbbef2.0405020222.6024b162@posting.google.com> Message-ID: "has" wrote in message news:69cbbef2.0405020222.6024b162 at posting.google.com... > s " wrote in message news:... > > > Quoting from a previous post quoting by someone else: > > > Modules are an encapsulation mechanism, just like class instances, so > > > I'd say the large and obvious overlap counts as unnecessary > > > > I don't see this. 'Class instance' is an abstract concept, not a > > particular object. > > Please forgive my linguistic sloppies. How about if I say 'an object > of type "instance"'; does that sound clearer? In a way, yes. In the old class/instance system, all user-defined classes were instances of type 'class' and all instances of user-defined classes were instances (objects) of type 'instance'. So that is what you appear to be referring to whether you mean to or not. When Python get a code-breaking overhaul, this now redundant system will be dropped. Python is currently a language for manipulating typed objects. Changing it to a languge for manipulating prototyped objects, with types eliminated, would be a major change. But I currently believe it is possible to do prototyping within the current system. Several years ago, I posted (another group, maybe cross-posted here) a prototype Self class (based on second-hand descriptions of Self, and therefore possibly inadequate) for doing just that. But I have not yet had reason to go any further with it. So, for me, the way for someone to promote prototyping in Python, and serious discussion thereof, would be to write a similar class and then a neat application that exploits that class. > I'm sorry if this sounds personal; I am not interested in pseudopersonal 'advice' from someone who knows me not. I prefer reading and discussing various Python topics. Terry J. Reedy From jjl at pobox.com Thu May 27 17:52:10 2004 From: jjl at pobox.com (John J. Lee) Date: 27 May 2004 22:52:10 +0100 Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> Message-ID: <87y8ndilmd.fsf@pobox.com> Manlio Perillo writes: [...] > I'm trying to fix the regular expression patternin Cookie.py but it > does not work: [...] Yeah, IIRC there's some odd stuff in there, that doesn't even seem to come from the standards, let alone reality ;-) The Cookie module really doesn't know how to handle cookies on the client side. Use this, which does: http://wwwsearch.sf.net/ClientCookie/ You can just say: ClientCookie.urlopen("http://www.example.com/") and be done with it. John From simon at metaplay.com.au Tue May 11 20:57:16 2004 From: simon at metaplay.com.au (Simon Wittber) Date: Wed, 12 May 2004 08:57:16 +0800 Subject: OT: Idea for Python T-shirt In-Reply-To: Message-ID: <200405120048.i4C0mugr012020@redpill.digitalventures.com.au> A python T-Shirt? Funnily enough, I was thinking on this last night. Something eloquent, something slightly obscure, which only other Pythonistae would recognize: "import this" Sw. From bokr at oz.net Mon May 24 15:44:32 2004 From: bokr at oz.net (Bengt Richter) Date: 24 May 2004 19:44:32 GMT Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <2h55ajF9alv2U1@uni-berlin.de> <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> Message-ID: On Fri, 21 May 2004 05:08:20 -0700, David MacQuigg wrote: >On Fri, 21 May 2004 13:45:52 +1200, Greg Ewing > wrote: > >>David MacQuigg wrote: >>> I'm still waiting for that one simple example that you say will do it >>> all, and do it right. >> >>I don't think you should be trying to cram all the features >>of OOP into a single example. > >I agree. Digestible chunks is the right approach. Animals_1.py is >the first example of classes, including data, methods, instance >variables, and inheritance. Thats a pretty large chunk, but what >makes it digestible is the student's prior knowledge of modules, >functions, and all forms of data. > >Animals_2a1.py (the current version) adds more levels to the >hierarchy, a special method __init__, static methods, bound and >unbound methods, the odd scoping rule for class variables, and >_private variables. This is all the basics that students will need if >they will be writing their own classes. > >There probably won't be an Animals_3, but instead, "level 3" will be a >bunch of examples to illustrate various techniques, like the robust >programming that JM has been pushing, and maybe some topics from >chapters 21 - 23 of Learning Python. > >>Also, I worry that the zoo topic will seem contrived. Why >>not base your examples on some real problems from your >>audience's subject area? > >Given the goals of the level one and two examples ( cover all the >basic features in two simple examples ) I think any example will be >contrived. The level 3 examples will be the right place to introduce >real circuit design problems. > If you take some wood and saw off pieces to make a box with some fasteners, and then you put the leftover pieces of wood *in* the box, you have pieces of wood with two different kinds of relationship to the box. I suspect reflecting on this distinction in terms of your examples might be fruitful. I can't spend the time to participate more than stolen moments right now, so I haven't seen all of the thread. Sorry if I am rehashing something. Regards, Bengt Richter From greg at cosc.canterbury.ac.nz Sun May 9 23:08:26 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 10 May 2004 15:08:26 +1200 Subject: Unification of Methods and Functions In-Reply-To: References: <16752bcc.0405050817.4ca77017@posting.google.com> <16752bcc.0405060737.bd43802@posting.google.com> <2g0f8iF34iasU1@uni-berlin.de> Message-ID: <2g8a1cF5il06U1@uni-berlin.de> David MacQuigg wrote: >>In Python, staticmethods are not fundamentally necessary, >>full stop. We keep trying to tell you that, but it seems >>you have your fingers in your ears. > > I will stop this subthread right here unless you change your tone. Sorry, I take that back. I stand by the point I was trying to make, though. You don't need to use static methods at all in a language, like Python, which doesn't force you to make all functions a method of something. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From RobbTiger at softhome.net Fri May 21 11:40:43 2004 From: RobbTiger at softhome.net (Noldoaran) Date: 21 May 2004 08:40:43 -0700 Subject: "Extracting" a dictionary References: <5fd6ba56.0405200818.60b0259@posting.google.com> Message-ID: <5fd6ba56.0405210740.7b0e300f@posting.google.com> Peter Otten: > Saying self.__d = dont_care invokes __setattr__() to set __d, __setattr__() > asks __getattr__() for __d, which asks __getattr__() for __d to determine > __d ...ad infinitum. > To avoid the recursion you must bypass __setattr__() by accessing __dict__ > directly. (snip) > While this works, you can achieve the same functionality in a more elegant > way: > > >>> class AttrDict: > ... def __init__(self, d): > ... self.__dict__.update(d) > ... (snip) > A standard trick, by the way. Can't think of the right google keywords right > now, so I use another standard trick and leave finding them as an excercise > to the reader :-) > > Peter Thanks, Peter. I found another way that also works: >>> class AttrDict(dict): ... __getattr__ = dict.__getitem__ ... __getattribute__ = __getattr__ ... __setattr__ = dict.__setitem__ ... __delattr__ = dict.__delitem__ ... >>> d = AttrDict({'foo': 23, 'bar': 42}) >>> d.foo 23 >>> d.bar 42 >>> d.spam = 123 >>> d.spam 123 >>> d {'spam': 123, 'foo': 23, 'bar': 42} ---- ~Noldoaran From gabor at z10n.net Mon May 24 05:11:37 2004 From: gabor at z10n.net (gabor) Date: Mon, 24 May 2004 11:11:37 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <1085389897.13786.15.camel@dubb> On Sun, 2004-05-23 at 15:04 -0700, Mark Hahn wrote: > Does any Python user have a story of regret of using an object's attribute > when they should not have and encapsulation would have saved their butts? not exactly... i don't need restriction, only a hint... if i look thru some java code, i immediately see what variables/methods should/can i access... it's not the same for python... for example at work where i use java, there are classes that have 10-15methods, but only 4public ones... it immediately gets simplier to understand/use the class gabor From rawbobb at hotmail.com Sat May 1 14:08:19 2004 From: rawbobb at hotmail.com (bobb) Date: Sat, 01 May 2004 18:08:19 GMT Subject: calling functions at the same time References: <1095ijdb5jotvf1@corp.supernews.com> Message-ID: "Bart Nessux" wrote in message news:c6unuq$d0f$1 at solaris.cc.vt.edu... > Cameron Laird wrote: > > > In article , > > bart_nessux wrote: > >>I need a script to call several functions at the same time. How does one > >>call more than one function simultaneously? > >> > >> > >> > > > > This has several smart-alecky answers, including "you don't", > > and "with co-routines". The best way you can help yourself is > > to describe a concrete situation where your (Python?) script > > has a need to call even two functions simultaneously. > > I need to ping 4 hosts at exactly the same time from the same machine (I > plan to timestamp the pings) to test and measure network conditions over > different routes to different hosts. Putting all the ping hosts in a list > and looping through it is not a fair or balanced way to do this because of > the time differences. > The network guy in me says that pinging 4 machines at the same time from 1 machine is not fair and balanced. your network card really only does 1 request at a time... I would think that the only fair judge is to do it on 4 machines on the same segment, or 4 cards in the same machine, otherwise you're bottleneck becomes the single network card.. My opinion... bobb > > > > It turns > > out "simultaneously" has a plethora of meanings, and you're the > > only one in a position to get others to understand which you > > have in mind. > > I mean it to mean: at the *exact* same time... concurrently. Like runners > starting a race together. > > > > > It'll also help to know whether you mean "function" as specific > > to the Python language, or more abstractly, as a unit of useful > > accomplishment. > > Specific to Python. From greg at cosc.canterbury.ac.nz Wed May 12 22:58:19 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 13 May 2004 14:58:19 +1200 Subject: Unification of Methods and Functions In-Reply-To: <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> Message-ID: <2gg6idF2bvnfU1@uni-berlin.de> David MacQuigg wrote: > The real issue is whether we can unify all forms of functions and > methods. This requires we do something different with 'self'. From a > unification standpoint, an equally acceptable solution is that we add > 'self' to *all* functions and methods, whether they need it or not.] I still don't see the benefit of unifying them to this degree. Even if you added 'self' to every function, there would *still* be two kinds of function, those that use their 'self' and those that don't. The difference in usage is still there, even if it's not directly reflected in the syntax. I can't see the point in trying to pretend otherwise. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter.maas at mplusr.de Tue May 25 09:21:47 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Tue, 25 May 2004 15:21:47 +0200 Subject: Newbie question In-Reply-To: References: Message-ID: mp312 wrote: > I have a script that I need to do the following: > > Taking a user id that is in the format 'userid at MACAddress', read the > userid portion (varying length) and concatenate with @honigman.com. mac_user_id.split('@')[0] + '@honigman.com' Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From robin at SPAMREMOVEjessikat.fsnet.co.uk Tue May 25 17:27:17 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Tue, 25 May 2004 22:27:17 +0100 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <1xNsc.17979$bF3.1356@fed1read01> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <40B394F2.8020807@jessikat.fsnet.co.uk> <1xNsc.17979$bF3.1356@fed1read01> Message-ID: <40B3BA35.8050907@jessikat.fsnet.co.uk> Mark Hahn wrote: > "Robin Becker" wrote > > >>In fact the python time for fib(35) was about 31.1 seconds (ie less than >>prothon for fib(25)) so something is spectacularly amiss with prothon. > > > Yes, and that something is that Prothon is pre-alpha and full of debug code. > Take a look at the interpreter loop in interp.c and the reason will be > obvious immediately. We are not going to be addressing efficiency until > after the language is designed in July. > > One step at a time... Wasn't criticising. I expected some degredation from an early version, but this seems too much. From the memory usage I would guess that perhaps the frames aren't being released. -- Robin Becker From dmq at gain.com Wed May 19 15:05:34 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 19 May 2004 12:05:34 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <2gqu12F5qqk9U1@uni-berlin.de> <16752bcc.0405181600.3b6d6373@posting.google.com> Message-ID: On 18 May 2004 17:00:12 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg wrote in message news:... >> On Mon, 17 May 2004 16:40:00 +1200, Greg Ewing >> wrote: >> >> >David MacQuigg wrote: >> >> James has been telling me it is terribly wrong to keep data as >> >> attributes of classes >> > >[snip] >> >> This makes a lot more sense than a total ban on data in classes. >> > >Just to clarify, once again - I was not suggesting a ban on data in >classes - I was objecting to the specific way in which the data was >being passed around and used in the class heirarchy. You have some good ideas, but you have been making extreme statements and over-generalizing. """ 5/17/04: OK: "The whole idea of having these structures in any program is wrong." Firstly, the program uses a class hierarchy as a data structure. That isn't what class heirarchies are designed for, and not how they should be used IMO. But it's what any bright student will pick up from the example. """ We could avoid a lot of non-productive discussion if you were more careful with these statements. Instead of the above, you could say: """ Generally, its not a good idea to store *changeable* data in the class itself. The Animals_2 program has variables like _numAnimals, which change when any instances of subclasses are created. If this were a much bigger program with hundreds of classes being implemented by many different programmers, one of those programmers might forget to add a call to the parent's __init__, and all counts of classes above the new class would be wrong. """ Then we could have a productive discussion on whether, in this case, _numAnimals is OK. I would argue yes, but I understand your point about the possibility of new, incorrectly written classes causing a problem. The reasons I would argue yes are: 1) This is a very simple hierarchy, even if it grows to a hundred classes. 2) The incrementing of the _num... variables is a simple and standard part of every __init__ in this hierarchy. A programmer who would ignore that, is a programmer who would completely mess up modification of a more complex program involving automatic generation of classes. 3) This is not a database or transaction processing system that needs to stay online for days at a time, and is vulnerable to out-of-sync problems arising from interupted sessions, etc. 4) This is an example for students who are new to OOP. I would rather keep the example simple, and point out how it might be improved, than burden the students with all the details of a production-quality program. I've made your program, Animals_JM.py at http://ece.arizona.edu/~edatools/Python/Exercises/ the next example *after* Animals_2. The topic of techniques to make a program robust and maintainable is worth a whole chapter, but it would be a distraction in the introductory chapter. I would still like to see a way to gain the benefits of both Animals_2 and Animals_JM in one program. My attempts to follow up on suggestions in this discussion have only added complexity, not improved the program. -- Dave From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat May 22 16:19:52 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sat, 22 May 2004 22:19:52 +0200 Subject: GetClipboardData(CF_BITMAP) unimplemented References: Message-ID: Hi ! The question is on CLIPBOARD + bitmap. From kirk at eyegor.jobsluder.net Wed May 12 11:46:48 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Wed, 12 May 2004 15:46:48 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <2gbtt0Fvso5U2@uni-berlin.de> Message-ID: On 2004-05-12, Roy Smith wrote: > Kirk Job-Sluder wrote: >> And here is the fundamental question. Why should I spend my time >> writing a module in python to emulate another tool, when I can simply >> use that other tool? Why should I, as a resarcher who must process >> large quantities of data, spend my time and my employer's money >> reinventing the wheel? > > At the risk of veering this thread in yet another different direction, > anybody who does analysis of large amounts of data should take a look at > Gary Perlman's excellent, free, and generally under-appreciated |STAT > package. > > http://www.acm.org/~perlman/stat/ > > It's been around in one version or another for something like 20 years. > It fills an interesting little niche that's part data manipulation and > part statistics. Thanks. I'll check it out. From peter at engcorp.com Sat May 1 12:57:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 01 May 2004 12:57:14 -0400 Subject: calling functions at the same time In-Reply-To: <4093d389$0$17262$a1866201@newsreader.visi.com> References: <1095ijdb5jotvf1@corp.supernews.com> <4093d389$0$17262$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Knio wrote: > >>You can't get greater then 1ms accuracy when measuring a time >>on todays machines, and that will be less when measuring time >>over a network... > > Not sure what you mean by "todays machines", but on a > Pentium-class machine running Linux, you get approx 1us > resolution with calls to time.time(): Keep in mind the difference between "accuracy" and "resolution" (or "precision"). I think Knio is probably right that, unless you are running on a realtime OS, you won't be able to guarantee anything better than 1ms accuracy, and quite probably not even that. -Peter From me at privacy.net Sat May 1 11:53:13 2004 From: me at privacy.net (Duncan Booth) Date: 1 May 2004 15:53:13 GMT Subject: a=([],); a[0]+=[1] References: <7ff790taojrrqka0trq9ltm82g0ac95ria@4ax.com> Message-ID: Andrea Griffini wrote in news:7ff790taojrrqka0trq9ltm82g0ac95ria at 4ax.com: > When reading about python "warts" i stepped in this > example I find quite puzzling: > > a = ( [] , ) > a[0] += [1] > > this gives an error, because a tuple cannot be > modified. But if you print the content of "a" > it will show it has indeed been modified. > > How can this happen ? if "+=" for list was called > then no modification to the tuple was requested and > so no error should have been raised; if instead "+" > and "=" was executed then after a failing assignment > the original list is safe... (or at least I thought > so; if you type "a[0] = [2]" you get the error and > "a" is not modified). > > Is there an explanation simpler than investigating > on python sources ? > += is implemented by calling the __iadd__ method (if it exists, otherwise __add__ is called). In either case the result of the method is then assigned to the destination. So what is happening here is that list.__iadd__ modifies the list in place, but then the attempt to assign the result into the tuple fails. Although __iadd__ extends the list in place this need not be true for all types. An object could have an implementation for inplace addition that actually creates a new object, so Python cannot optimise out the store. See http://groups.google.co.uk/groups?threadm=3CFCF3E7.AE891EBE%40noaa.gov for a (long) discussion of this topic. From gry at ll.mit.edu Wed May 19 10:51:21 2004 From: gry at ll.mit.edu (george young) Date: 19 May 2004 07:51:21 -0700 Subject: unique number generator References: Message-ID: <78b6a744.0405190651.6fc8c04a@posting.google.com> "Joe Wong" wrote in message news:... > Hi, > > I need to implement a unique number generator that 1 or more processes > on same or different machines will make use of it. Is there any library > / project available already for this? Try: http://egenix.com/files/python/mxUID.html or http://www.alcyone.com/software/uid/ From esj at harvee.org Fri May 28 17:03:03 2004 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 28 May 2004 17:03:03 -0400 Subject: Fwd: Python opening in NY In-Reply-To: <10b7kgnmdpd1iaf@corp.supernews.com> References: <10b7kgnmdpd1iaf@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article , > Steve Holden wrote: > >>Hans Nowak wrote: >> >> >>>I got the following email from Darsh Mehta. I am unable to move to New >>>York myself, but maybe someone else here will be interested. In that >>>case, please contact this person. He says he can pay up to $35/hr. >>> >> >>[...] >> >>Just as a matter of interest, is $35 currently considered an acceptable >>hourly rate for programming in the Big Apple? I wouldn't have thought so ... > > . > . > . > While "programming" is, of course, far more heterogenous > than we're pretending for the current purposes, $35 / hour > in NYC sounds WAY low to me. an alternative view says they are: 1) looking for a intern/student 2) justifying importing H1B or L1 talent (look, we advertised the job and got no takers) --- eric From osuchw at ecn.ab.ca Sat May 8 18:54:32 2004 From: osuchw at ecn.ab.ca (Waldemar Osuch) Date: 8 May 2004 15:54:32 -0700 Subject: CGI Proplem displaying image References: Message-ID: matthiasjanes at gmx.net (matthiasjanes) wrote in message news:... > Hi, > Maybe someone of you can help me. > > I'm trying to display an image in memory(open file) with an cgi script > - but it want work proberly: > > I'm running an Cgi webserver (CgiServerGui.py). > > both files are in the /cgi/ folder > > ################# > #my CGISRIPT: test.py > > #! /usr/bin/env python > > print ("Content-type: image/jpeg"); > print # End of headers! > > filename="cgi-bin//dog.jpg" > infile = open(filename, 'rb') > doginmemory=infile.read() > print doginmemory > > ################## > Use sys.stdout for output in CGI scripts. Escpecially with binary files. Try this and see if the problem goes away ################# #my CGISRIPT: test.py #! /usr/bin/env python import sys sys.stdout("Content-type: image/jpeg\n\n") filename="cgi-bin/dog.jpg" img = open(filename, 'rb').read() sys.stdout.write(img) ################## Remember Google is your friend http://starship.python.net/crew/davem/cgifaq/faqw.cgi waldek From fgeiger at datec.at Sun May 30 11:53:39 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 30 May 2004 17:53:39 +0200 Subject: "Private" Member Variables References: Message-ID: "Scott Brady Drummonds" schrieb im Newsbeitrag news:c97r0b$jqq$1 at news01.intel.com... > Hi, everyone, > > I'm still learning Python as I develop a medium-sized project. From my > previous experience with C++, I've burnt into my mind the notion of > information hiding. I'm having trouble understanding to what extent I > should follow this policy in my Python code so I thought I'd ask the group. > > I read from a previous post that to attain a private-like status of member > variables, I should prefix the variable name with two underscores ("__"). > This does work, but in another post someone asked me if this was really > necessary. Given that the very nature of the language precludes any > compile-time type dependencies I'm wondering if there is any benefit to > naming variables with leading underscores and providing accessor functions > like this: > class C: > ... > def value(self): > return self.__value > ... > > The problems that arise from directly relying on the member variable in C++ > (compile-time type dependency, as I said above) don't exist in Python. So > why provide an accessor at all? Why not just allow direct reading and > writing of the member variable? Is there something here I'm missing? Classes should offer services, not data. This holds for any programming language. If you remember this while designing your software you will stop to think of variables and their not/privateness. Most people who speak of information hiding don't get it right. They end up def'ing private variables and then they write getters and setters to access them. This is NOT information hiding, it's the opposite (simple data containers being an exception, of course). Now, if you know all this it really doen't matter much if you write self.whatToSay or self._whatToSay or self.__whatToSay because your call should be myObj = MyClass("Hello") myObj.sayIt(Printer()) and NOT myObj = MyClass() s = myObj._whatToSay print s In Python things concerning even the bad example are somewhat better because you do not know explicitly what type s is of. In C++ most people show all the world, that they access a string, no matter if they use a getter or not. Sure, they def'ed the string as private, but the information is not hidden, by no means: Everyone knows, it's a string! HTH Franz GEIGER > > What are your thoughts? How much privacy should I build into my code? > Should I be using variables beginning with "__" and accessors? Or is that > simply not necessary (or normal) in Python code? > > Thanks, > Scott > > -- > Remove .nospam from my e-mail address to mail me. > > > From __peter__ at web.de Fri May 21 04:04:51 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 May 2004 10:04:51 +0200 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> <545cb8c2.0405201645.16ac3364@posting.google.com> Message-ID: Jim Hefferon wrote: > Peter Otten <__peter__ at web.de> wrote >> So why doesn't it just concatenate? Because there is no way of knowing >> how to properly decode chr(174) or any other non-ascii character to >> unicode: >> >> >>> chr(174).decode("latin1") >> u'\xae' >> >>> chr(174).decode("latin2") >> u'\u017d' >> >>> > > Forgive me, Peter, but you've only rephrased my question: I'm going to > decode them later, so why does the concatenator insist on decoding > them now? As I understand it (perhaps this is my error), > encoding/decoding is stuff that you do external to manipulating the > arrays of characters. Perhaps another example will help in addition to the answers already given: >>> 1 + 2.0 3.0 In the above 1 is converted to 1.0 before it can be added to 2.0, i. e. we have >>> float(1) + 2.0 3.0 In the same spirit >>> u"a" + "b" u'ab' "b" is converted to unicode before u"a" and u"b" can be concatenated. The same goes for string formatting: >>> "a%s" % u"b" u'ab' >>> u"a%s" % "b" u'ab' The following might be the conversion function: >>> def tounicode(s, encoding="ascii"): ... return s.decode(encoding) ... >>> u"a" + tounicode("b") u'ab' Of course it would fail with non-ascii characters in the string that shall be converted. Why not allow strings with all 256 chars? Again, as stated in my above post, that would be ambiguous: >>> u"a" + tounicode(chr(174), "latin1") u'a\xae' >>> u"a" + tounicode(chr(174), "latin2") u'a\u017d' >>> By the way, in the real conversion routine the encoding isn't hardcoded, see sys.get/setdefaultencoding() for the details. Therefore you _could_ modify site.py to assume e. g. latin1 as the encoding of 8 bit strings. The practical benefit of that is limited as you cannot make assumptions about machines not under your control and therefore are stuck with ascii as the least common denominator for scripts meant to be portable - which brings us back to: >> Use either unicode or str, but don't mix them. That should keep you out >> of trouble. Or make all conversions explicit with the str.decode()/unicode.encode() methods. > Well, I got this string as the filename of some kind of Macintosh file > (I'm on Linux but I'm working with an archive that contains some pre-X > Mac stuff) while calling some os and os.path functions. So I'm taking > strings from a Python library function (and using % to stuff them into > strings that will end up on the web, which should preserve > unicode-type-ness, right?) and then .join-ing them. > > I didn't go into the whole story when posting, because I tried to boil > the question down. Perhaps I should have. While details are often helpful to identify a problem that is different from the poster's guess, unicode handling is pretty general, and it was rather my post that was lacking clarity. Peter From miki.tebeka at zoran.com Sun May 23 09:13:53 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 23 May 2004 15:13:53 +0200 Subject: Freeze and Resume execution In-Reply-To: <20040523115548.DF2E.SLAWEK@cs.lth.se> References: <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> <20040523101619.GH1916@zoran.com> <20040523115548.DF2E.SLAWEK@cs.lth.se> Message-ID: <20040523131353.GS1916@zoran.com> Hello Slawomir, > I must admit I don't really understand what your problem is, so my > solution may not be what you are looking for. However, maybe it will > be useful: > > ********************************************************************** > > def generator(): > i = 0 > while 1: > i += 1 > yield i > > class A: > def __init__(self): > self.gen = generator() > def work(self): > i = 0 > while True: > print self.gen.next() > i += 1 > if i > 5: > raise ValueError > My problem is that the one raising the error is the generator. And I'd like to resume the generator just after the exception was raised. Something in the lines of: class BufferFull(Exception): pass def send_one_bit(bit): pass OUT_BUFFER_SIZE = 10 def output(bits): size = 0 for bit in bits: send_one_bit(bit) # HW call size += 1 if size == OUT_BUFFER_SIZE: raise BufferFull # I'd like to resume just after this point size = 0 Note that the output buffer is called about 3-5 stack frames down from the function catching the exception. Bye. -- ------------------------------------------------------------------------- Miki Tebeka http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From nichloas at sohu.com Wed May 19 08:31:09 2004 From: nichloas at sohu.com (Li Daobing) Date: Wed, 19 May 2004 20:31:09 +0800 Subject: What's the meaning of Dutch in "The Zen of Python" Message-ID: Hello, Does anyone know what's the meaning of Dutch in "The Zen of Python"? Thanks in advance Li Daobing 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 __peter__ at web.de Fri May 28 02:47:25 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 May 2004 08:47:25 +0200 Subject: partial / wildcard string match in 'in' and 'list.index()' References: <2hnu7nFfa63oU1@uni-berlin.de> Message-ID: Jon Perez wrote: > For a given list: > > fruits=["apples","oranges","mangoes","bananas"] > > > > > Is it possible to do wildcard matches like shown below? > > 1. "man*" in fruits > > 2. fruits.index("man*") > > 3. "*nanas*" in fruits > > 4. fruits.index("*nanas") > > > > or is there any way to achieve an equivalent effect > short of doing a while loop? >>> import fnmatch >>> def find(seq, pattern): ... pattern = pattern.lower() ... for i, n in enumerate(seq): ... if fnmatch.fnmatch(n.lower(), pattern): ... return i ... return -1 ... >>> def index(seq, pattern): ... result = find(seq, pattern) ... if result == -1: ... raise ValueError ... return result ... >>> def contains(seq, pattern): ... return find(seq, pattern) != -1 ... >>> fruit = "apples oranges mangoes bananas".split() >>> contains(fruit, "man*") True >>> contains(fruit, "*nas") True >>> index(fruit, "*ANA*") 3 >>> find(fruit, "*") 0 >>> find(fruit, "m*s") 2 >>> find(fruit, "m*x") -1 >>> If you want case-sensitive matches, use fnmatchcase() and remove the .lower() conversions. Peter From segphault at sbcglobal.net Wed May 12 12:56:52 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 12 May 2004 16:56:52 GMT Subject: newbie question: should I learn TKinter or skip it and learnmoreadvanced toolkit? References: Message-ID: > pyQt doesn't look like an option on Windows and pyGTK looks like it is even > less documented than wx although I may be wrong here. pyGTK is very well documented. You can find a rather comprehensive reference manual here: http://www.moeraki.com/ And you can find other assorted pyGTK/pyGNOME references here: http://www.pycage.de/coding.html --SegPhault From python at quixs.com Mon May 10 15:58:20 2004 From: python at quixs.com (Lars Heuer) Date: Mon, 10 May 2004 21:58:20 +0200 Subject: Class update detection In-Reply-To: <109vn4b8bhe98f4@corp.supernews.com> References: <109vn4b8bhe98f4@corp.supernews.com> Message-ID: <171412027.20040510215820@quixs.com> Hi Axium, [...] > this information will be accessible from a UI. The problem I am running > into is when the user is done working in the UI I need to determine if > any of the class attributes have been changed to I can issue an update > query to the database with the changes. Is there a generally accepted [...] I.e. SQLObject (and other ORMs, too) does this job. If you update a class attribute, it automatically updates the underlying DB tables. http://sqlobject.org/ Best regards, Lars From kfast at poczta.onet.pl Wed May 19 10:53:02 2004 From: kfast at poczta.onet.pl (Jakub Fast) Date: Wed, 19 May 2004 16:53:02 +0200 Subject: BANALE ma utile In-Reply-To: References: Message-ID: <40AB74CE.7040704@poczta.onet.pl> Try this: if nomeelemento in confini: pass k. Armand Federico - INFO wrote: > Devo scoprire se un elemento esiste in una lista > > Se metto confini.index(nomeelemento) mi da errore nel caso non esista e mi > da l'indice nel caso esista > > Il mio problema ?: > se l'elemento non esiste, devo fare la stessa cosa con un altro elemento. > > Come posso evitare l'errore??? > > > *** > Avevo provato con > > if confini.index(nomeelemento): > return qualcosa > else: > continue > > *** > Oppure con > > if confini.index(nomeelemento)>-1: > return qualcosa > else: > continue > > Ma nel caso non venga trovato l'elemento da errore > > From bnet at ifrance.com Mon May 31 01:51:26 2004 From: bnet at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Mon, 31 May 2004 07:51:26 +0200 Subject: API : constness ? References: Message-ID: Le Mon, 31 May 2004 11:56:57 +1000, Delaney, Timothy C (Timothy) a ?crit?: > Beno?t Dejean wrote: >> static const char * const kwlist[] = { "uri", "open_mode", "exclusive", >> "perm", NULL }; > > Does this give any performance or size improvement? of course, it avoids a lot of relocation, reduces load time, and manque the compiler to make further informations because data will be in a readonly segment. it is safe to apply this kind of change to static data. > > If it will simplify calling code, I don't see any reason not to do it. > However, there is a general policy of not doing large chunks of > boilerplate fixing - instead it is encouraged to make these changes in > code that is being actively worked on for some other reason. Small > patches are good. > > Perhaps you should choose a few cases that bug you the most (e.g. > PyArg_ParseTupleAndKeywords) and submit a patch just for those. you're right. i should first work on printf/scanf like functions > Additionally, if you can show a performance improvement as a result (and > importantly, no loss of performance on Windows ...) it's more likely to > be reviewed kindly ... ;) my first goal is const correctness, i don't know if i can show something. it will just remove warnings and move data to the text segment, etc From me at privacy.net Thu May 6 07:22:05 2004 From: me at privacy.net (Heather Coppersmith) Date: 06 May 2004 07:22:05 -0400 Subject: classes vs dicts References: Message-ID: On 6 May 2004 03:12:15 -0700, charlvj at yahoo.com (Charlie) wrote: > Say I want to write an address book program, what is the best > way to define a person (and the like): create a class (as I > would do in Java) or use a dictionary? > I guess using dictionaries is fastest and easiest, but is this > recommended? In the end (and in the implementation), classes are just syntactic sugar for dictionaries. object.attribute is equiv. to dictionary[ 'key' ] "Faster" is probably not applicable unless you're doing thousands of lookups (designing and coding times should be about the same). "Easiest" is a matter of personal taste. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From peter at engcorp.com Sun May 2 16:44:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 May 2004 16:44:34 -0400 Subject: urllib2/cookies - surely there's a better way ? In-Reply-To: <282f826a.0405020147.29f4945@posting.google.com> References: <282f826a.0404292248.7b71c7d6@posting.google.com> <84KdnfW3OoNKow_dRVn-vg@powergate.ca> <282f826a.0405020147.29f4945@posting.google.com> Message-ID: Richard Shea wrote: >>Search for "ClientCookie"... > > That's great ! I actually laughed when I read the doco - I was only > looking for something to parse cookies with but this does the whole > thing ! I haven't yet used it but I've had a few wriggles getting to > where the 'import ClientCookie' works so I thought I might tell the > newsgroup what I did to make it work (although that might be fairly > obvious to many). > > First of all I was installing on a W98 machine. I tried using the > install procedure "python setup.py build" but I got the message > "error: package directory 'ClientCookie' does not exist". I do have a > slightly weird setup so I wasn't all that surprised. Hmm... I believe on Windows all you should have to do is "python setup.py install", not "build". That will pretty much do whatever you did to manually install it, but it's done for you... and won't muck with your registry since it will just install it under your site-packages folder where it's supposed to go. -Peter From nospam-trice at comcast-nospam.net Sun May 2 13:53:21 2004 From: nospam-trice at comcast-nospam.net (Tim) Date: Sun, 2 May 2004 13:53:21 -0400 Subject: printing float as formatted dollars Message-ID: Is there a simple way to output float values as formatted dollar amounts? i.e. 127379.42 as $127,379.42 Thanks, Tim From greg at cosc.canterbury.ac.nz Wed May 5 03:42:53 2004 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 05 May 2004 19:42:53 +1200 Subject: ANN: Pyrex 0.9.2.1 Message-ID: Pyrex 0.9.2.1 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ I really haven't been having much luck with the setup.py file lately! Here's hoping it's finally right this time. What is Pyrex? -------------- Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From lbates at swamisoft.com Mon May 17 12:48:48 2004 From: lbates at swamisoft.com (Larry Bates) Date: Mon, 17 May 2004 11:48:48 -0500 Subject: html to image or html to postcript to image References: Message-ID: <6LqdnQ67eel2cTXdRVn-gQ@comcast.com> Python used pdfTEX to generate their .PDF manual from their HTML manual. It located at: http://www.tug.org/applications/pdftex/ -Larry "Lukasz Indyk" wrote in message news:c8ai0r$83$1 at atlantis.news.tpi.pl... > i'm sorry, i didn't make myself clear enough. once again then: i have > html defining website, and i want to generate image with this website > (without displaying it in browser window, doing print screen etc.) From newsgroups at jhrothjr.com Fri May 21 21:19:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 21 May 2004 21:19:10 -0400 Subject: terminological obscurity References: <40ae3ebe$0$17254$a1866201@newsreader.visi.com> Message-ID: <10atak03d51tpeb@news.supernews.com> "Grant Edwards" wrote in message news:slrncastid.5mc.grante at grante.rivatek.com... > On 2004-05-21, Donn Cave wrote: > > >> For example, why shouldn't index() find an object in a > >> non-homogeneous sequence? Either the object is in the sequence or > >> it's not. If it is, there is an index that corresponds to it. > > > > For example, > > tm = time.localtime(time.time()) > > i = tm.index(5) > > > > What would that mean? > > > > It's absurd to search for the location of a value in a tuple, > > because the values don't have any meaning independent of their > > location. > > OK, I see what you mean. That brings up the question of why > use integer indexes to access members of of a group of objects > when the order of the objects is meaningless? As Ahaz said, because it's lightweight. That's got its benefits and its drawbacks. In one sense a tuple is a lightweight version of a Data Object, but it doesn't segue into one cleanly. See the gyrations that they had to go through to slide a data object in under the time and stat tuples in release 2.2 (which is something I heartily approve of - now we need to add a few methods to those objects...) John Roth > > -- > Grant Edwards grante Yow! Do you guys know we > at just passed thru a BLACK > visi.com HOLE in space? From Harald.Schreiber at t-online.de Sun May 23 17:04:26 2004 From: Harald.Schreiber at t-online.de (Harald Schreiber) Date: Sun, 23 May 2004 23:04:26 +0200 Subject: Problem concerning pyparallel References: <10b1uvt47t75c94@news.supernews.com> Message-ID: John Roth wrote: > "Harald Schreiber" wrote in message > news:c8qqp4$u1$01$1 at news.t-online.com... >> Hi, >> When trying to install the pyparallel-software under Windows98SE I got an >> errormessage about a missing cl.exe. >> Can someone there out give me some explanations? > > I believe that's either the compiler or the linker. Do you > have Visual Studio installed? Or else either Cygwin or MinGW? Neither. I'll try it, thank you so far! > > John Roth > >> Harald Schreiber From barry at python.org Sat May 15 19:36:07 2004 From: barry at python.org (Barry Warsaw) Date: Sat, 15 May 2004 19:36:07 -0400 Subject: RELEASED Mailman 2.1.5 Message-ID: <1084664166.1350.374.camel@anthem.wooz.org> Today I am releasing Mailman 2.1.5, a bug fix release that also contains new support for the Turkish language, and a few minor new features. Mailman is free software for managing email mailing lists and e-newsletters. Mailman is used for all the python.org mailing lists. Mailman 2.1.5 is a significant upgrade which should improve disk i/o performance, administrative overhead for discarding held spams, and the behavior of bouncing member disables. This version also contains a fix for an exploit that could allow 3rd parties to retrieve member passwords. It is thus highly recommended that all existing sites upgrade to the latest version. For more information, please see: http://www.list.org http://mailman.sf.net http://www.gnu.org/software/mailman Finally, a personal note. I have left Zope Corporation to join Secure Software, a company started by John Viega -- Mailman's original author. Although I won't be working on Mailman in any official capacity, it is exciting to be working with him and the rest of the folks there. I leave Zope Corp on a positive note and wish nothing but success for them too. You can find Secure Software on the web at http://www.securesoftware.com. Please continue to use my barry at python.org email address for all Mailman correspondences. I don't expect much to change for the Mailman project at all. Enjoy, -Barry 2.1.5 (15-May-2004) - The admindb page has a checkbox that allows you to discard all held messages that are marked Defer. On heavy lists with lots of spam holds, this makes clearing them much faster. - The qrunner system has changed to use only one file per message. However the configuration variable METADATA_FORMAT has been removed, and support for SAVE_MSGS_AS_PICKLES has been changed. The latter no longer writes messages as plain text. Instead, they are stored as pickles of plain strings, using the text pickle format. This still makes them non-binary files readable and editable by humans. bin/dumpdb also works differently. It will print out the entire pickle file (with more verbosity) and if used with 'python -i', it binds msg to a list of all objects found in the pickle file. Removed from Defaults.py: PENDINGDB_LOCK_TIMEOUT, PENDINGDB_LOCK_ATTEMPTS, METAFMT_MARSHAL, METAFMT_BSDDB_NATIVE, METAFMT_ASCII, METADATA_FORMAT - The bounce processor has been redesigned so that now when an address's bounce score reaches the threshold, that address will be sent a probe message. Only if the probe bounces will the address be disabled. The score is reset to zero when the probe is sent. Also, bounce events are now kept in an event file instead of in memory. This should help contain the bloat of the BounceRunner. New supporting variables in Defaults.py: VERP_PROBE_FORMAT, VERP_PROBE_REGEXP REGISTER_BOUNCES_EVERY is promoted to a Defaults.py variable. - The pending database has been changed from a global pickle file, to a unique pickle file per mailing list. - The 'request' database file has changed from a marshal, to the more secure pickle format. - Disallow multiple password retrievals. - The email package is updated to version 2.5.5. - New language: Turkish. - Bugs and patches: 869644, 869647 (NotAMemberError for old cookie data), 878087 (bug in Slovenian catalog), 899263 (ignore duplicate pending ids), 810675 (discard all defers button) From greg at cosc.canterbury.ac.nz Thu May 13 22:25:15 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 14 May 2004 14:25:15 +1200 Subject: Unification of Methods and Functions In-Reply-To: <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> References: <16752bcc.0405060737.bd43802@posting.google.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> Message-ID: <2gip0dF3ffrjU1@uni-berlin.de> David MacQuigg wrote: > 1) We need to represent a hierarchy of cells, typically 5 to 10 levels > deep. > 2) Each cell has data associated with it. Some of this data is a > cummulative total of similar data from all subcells -- total currents, > total chip area, etc. > 3) The data for each cell is unique, and it must be displayed in a > format unique to that cell. > 4) We need a simple function, show() that can be called for any cell > or no cell at all (just knowing the cell type). This function should > show the cell data and the data from all cells above it. In case no > cells of a particular type have been added to the design, the > cummulative data should just show a default value, like zero. It's still not clear whether the hierarchy you're talking about is a hierarchy of *kinds* of cells (i.e. a class hierarchy), or a physical hierarchy of actual cells (i.e. an instance hierarchy). Both of these hierarchies can exist at the same time, and they are different. For example, you might have a kind of cell called NandGate, and a kind of cell called Transistor. An instance of NandGate contains instances of Transistor -- this is an instance hierarchy. But Transistor is not a subclass of NandGate -- that would imply a Transistor is a kind of NandGate, which is not true. On the other hand, NandGate may well be a subclass of Gate, and Gate and Transistor may be subclasses of Component. But that doesn't mean Gates *contain* NandGates. If prototype-based programming leads to confusion between class hierarchies and instance hierarchies, the I would say it's not helpful. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jcarlson at uci.edu Tue May 11 02:40:50 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 10 May 2004 23:40:50 -0700 Subject: Ideas for Python 3 In-Reply-To: <10a0m88d1lof458@corp.supernews.com> References: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> <10a0m88d1lof458@corp.supernews.com> Message-ID: >>I've previously taken a look at Prothon. Prototype syntax >>does not suit my taste in programming languages. If >>Python 3.0 becomes Prothon, I'll fork the most recent >>Python 2.x codebase that I prefer, maintaining it >>myself if necessary. > > Prothon syntax is changing daily (actually hourly right now). It's not going > to end up looking anything like what you see on the prothon.org website. > What's being discussed right now looks a lot better to me. You still may or > may not like the way it turns out, but it will be worthwhile to check back > in on it after things settle down a bit. Certainly looking at it will be worthwhile, though as it stands, Prothon has sufficient syntactical ugly (IMO) to make me feel nauseated (even with all the syntactical variations discussed on the mailing list). To make Mark Hahn feel a bit better, I have the same opinion of the 'Self' language, though Prothon does look quite a bit better than Self (what was/is Sun thinking?) - Josiah From apardon at forel.vub.ac.be Tue May 25 03:05:57 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 May 2004 07:05:57 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> Message-ID: Op 2004-05-22, David MacQuigg schreef : > On Thu, 13 May 2004 10:56:58 -0400, "Terry Reedy" > wrote: > >>"Antoon Pardon" wrote in message >>news:slrnca6d58.1i9.apardon at trout.vub.ac.be... >>> One could argue that all forms of methods and functions are unified. >>> It is just that python does some magic so that the method you >>> access from an object is not the actual function but the curried >>> function with the object. >> >>My view is similar: in Python, a method is a dressed up (wrapped) function. >>'Unification of methods and functions' reads to me like 'unification of >>dressed-up bodies and naked bodies'. What would that mean? One thing I >>like about Python is that there is only function-body syntax and not a >>separate, slightly different method-body syntax. To me, having only one >>type of code body *is* unification. So it is hard for me to see what is >>being proposed. Introducing a syntax like '.var' that would only be >>meaningful in a method and not a function would be dis-unification. > > There seems to be a lot of misunderstanding on the question of "magic" > in Python's method binding syntax vs the proposed syntax. I see > students having difficulty learning the current syntax. Python > experts say its real easy, and point to the explicit "self" as an > advantage of the current syntax, vs the "magic" of setting a global > __self__ variable. All of this is missing the problem. > > If Python were consistent, and *always* used a special first argument, > there wouldn't be a problem. The magic first argument would be no > more difficult than magically setting a global variable. The problem > is that some methods require a magic first argument, and others > require that it *not* be there. In one case you call cat1.talk() and > in another it is Cat.talk(cat1). I know this is not terribly > difficult to understand -- one is a bound method, the other unbound. > Still it is a problem for beginners, and it leads to unecessary > complexities like static methods. > > The recent discussion on "Method binding confusion" 5/2/04 shows that > even experts can get confused. Here is the example, reduced to its > simplest terms: > > import math > > def mypow(x, y): > return x**y > > class MathA: > pow = math.pow > > class MathB: > pow = mypow > > ma = MathA() > mb = MathB() > > print ma.pow(2,4) #=> > 16.0 > print mb.pow(2,4) #=> > # TypeError: mypow() takes exactly 2 arguments (3 given) > > How would you explain this to non-CIS students in a class on circuit > design, where there is very little time to discuss programming? For as far as it is necessary to explain this, I would explain it as a bug. IMO this is a bug because the behaviour seems to differ depending on whether the function is implemented in C or python. Users of a module shouldn't be concerned how something is implemted. -- Antoon Pardon From ajsiegel at optonline.com Tue May 25 09:26:42 2004 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 May 2004 13:26:42 GMT Subject: terminological obscurity References: <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com><1085328791.560793@yasure><1085378050.309299@yasure><0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com><7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com><1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: > >replace tuples and lists with shoes and sandals, and this thread plays like a >scene from the "the afterlife of brian, revisisted" documentary by cristopher >guest. And I keep thinking this is a thread about homogenous and hetereogenous. Tuples and lists are easy. dir( () ) vs. dir( [] ) There is no doubt in my mind that I am *using* lists correctly, where there is something esssential I need that I find with dir( [] ) and don't find with dir( () ). Art From deetsNOSPAM at web.de Mon May 17 20:37:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 May 2004 02:37:49 +0200 Subject: module for working with the result set References: <_wbqc.68175$eT6.35900@newssvr25.news.prodigy.com> Message-ID: john fabiani wrote: > See this does not make sense to me. > > > mydata[0] > ['5992 ', 'A', '5346 ', ' ', 'XX > ', 'Kathy Stromme ', 'RICHMOND AMERICAN HOMES > ', '7250 WEST PEAK, ST # 212 ', ' well - its a list, and I bet its a list of columns. The columns are mostly strings (at least at the beginning) and obviously are space padded to match up to their size. The code you posted earlier assumes that the result row is returned as dict, thus iterating over the row yields in the keys. Consider this example: d = {"key1" : 10, "key2" : 20 } for key in d: print key, d[key] that results in key1 10 key2 20 notice how putting a dict as sequence in a for ... in ... : statement iterates the keys. Now you don't get a dict, but a list of row-values. So your code for field in mydata[0]: ???print?mydata[0][field] iterates over the data you presented, yielding the '5992??????' as first value. Thats all. Of course using that value as index makes no sense. To summarize: you expect data to be returned as dict per row, where the data is returned as list. Use the cursors .description property to get a mapping between name and index. -- Regards, Diez B. Roggisch From timothy.williams at nvl.army.mil Thu May 20 08:07:49 2004 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 20 May 2004 05:07:49 -0700 Subject: alternatives to making blocks like { } or other ?? References: <2h2epuF8ckqaU1@uni-berlin.de> Message-ID: Greg Ewing wrote in message news:<2h2epuF8ckqaU1 at uni-berlin.de>... > Tim Williams wrote: > > I found a bug in one of my programs recently where a line > > of code should have been outside of an 'if', but wasn't because I hit > > TAB one too many times. > > And for some reason it wasn't obvious from looking > at the indentation? > Not right away. It wasn't until I noticed things started running differently that I ran it in the debugger and saw my error. I had the offending line in the right place at one point, but after adding some code, I mistakenly indented that one line when I was indenting the new code. (I think that's what happened anyway - it's been awhile.) I don't know about anyone else, but I've spent more than enough time looking over and over at pieces of my code where a bug existed, not finding the error sooner because I "knew" this piece of code was right. Maybe this just says something about my programming ability. > In a brace-delimited language, you can get the > opposite problem, which is much worse: the code > *looks* right judging by the indentation, but it > doesn't match the brace structure. > > Python is a WYSIWYG language! But at least there, I can turn on paren-match mode in emacs and see what code is in the block. If it's indented inconsistenly, then I can fix how it looks, but I'm not changing the logic with whitespace. Enough of this thread. I'll agree to disagree on this. From irmen at -nospam-remove-this-xs4all.nl Mon May 3 19:02:08 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 04 May 2004 01:02:08 +0200 Subject: Distributing a Python App In-Reply-To: <109dec4c2bdn38e@corp.supernews.com> References: <109dec4c2bdn38e@corp.supernews.com> Message-ID: <4096cf70$0$568$e4fe514c@news.xs4all.nl> Allan Hughes wrote: > I'm a python noob and have a question. > > I would like to write a little app and then share it with others. > > It is going to need to store potentially large amounts of data and then > generate reports based on that data. > > I could just write to a DB, but that wouldn't be very portable. Define "a DB". > I would like a solution that will work 'out of the box' for any old shmo > who wants to use it without worrying about whether they have the right > DB. How can I build this in? Suggestion? What have you done in the past? I've successfully used plain text data files, standard Python pickles, and an (py)sqlite embedded database. None of them requires a full-blown database engine to be present. PySQLite is also a self-contained package. It depends on the amount and structure of your data what the best solution will be. --Irmen From danb_83 at yahoo.com Sat May 1 04:29:20 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 May 2004 01:29:20 -0700 Subject: silent raw_input for passwords References: Message-ID: Stephen Boulet wrote in message news:... > I need a password for a script and I would like to not have it stored in a > file or shown in a terminal. > > "passphrase = raw_input()" still lets you see the input on the screen. Is > there a way to have it be hidden? It's my gpg passphrase, so I don't want > it anywhere except in my head. There's probably an easier way, but you can use: def input_password(echo=True): chars = [] while True: newChar = getch() if newChar in '\r\n': break elif newChar in '\b\x7F': if chars: del chars[-1] sys.stdout.write('\b') else: chars.append(newChar) if echo: sys.stdout.write('*') return ''.join(chars) From gsmith at oxfam.org.uk Mon May 17 11:32:56 2004 From: gsmith at oxfam.org.uk (Graham) Date: Mon, 17 May 2004 16:32:56 +0100 Subject: Thinstall Message-ID: <40a8db23$0$20512$ed9e5944@reading.news.pipex.net> Has anyone packaged Python interpreter and scripts in a Thinstall exe? I want to know what the minimum interpreter components I need to distribute with my scripts to those users who do not have the Python interpreter installed. Thanks Graham Smith -------------------------------------------------------- PeopleSoft Technical Team Leader OXFAM GB +44 (1865) 313255 gsmith at oxfam.org.uk From jfabiani at yolo.com Sat May 22 09:09:44 2004 From: jfabiani at yolo.com (john fabiani) Date: Sat, 22 May 2004 13:09:44 GMT Subject: Where's the demo for wxpython 2.5 In-Reply-To: References: Message-ID: Peter Hansen wrote: > john fabiani wrote: > >> Peter Hansen wrote: >> >>> What platform are you on? Under Windows, a link to the demo is >>> put into your Start menu when you install and the code is under >>> site-packages/wx/demo. >> >> >> Sorry, I met the actual files (I have the old files) for download. >> Every time I attempt to download the file from wxpython's website it >> states the files are not available or corrupt. > > > Then I don't understand how you managed to get 2.5 in the first > place. And if you did get it, why you don't already have the demo > files. Did you delete them? > > -Peter I don't know! I decided to download the install again and sure enough there was the demo. I'd swear I did not to anything different. But thanks anyway. John From paul at prescod.net Sat May 1 18:27:01 2004 From: paul at prescod.net (Paul Prescod) Date: Sat, 01 May 2004 15:27:01 -0700 Subject: Pyrex 0.9.1.1 compile problem In-Reply-To: References: Message-ID: <40942435.3070700@prescod.net> Stephen Boulet wrote: >>Kernel 2.6.5 >>Slackware 9.1 >>Python -V: 2.3.1 >> >>running python setup.py install yields the following error: >> >>peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ python setup.py install >>Traceback (most recent call last): >> File "setup.py", line 8, in ? >> if sys.platform in ("unix", "darwin"): >>NameError: name 'sys' is not defined >>peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ >> >>What am I missing? Perhaps this will help: http://lists.copyleft.no/pipermail/pyrex/2004-May/000727.html Paul Prescod From miki.tebeka at zoran.com Wed May 5 02:32:41 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 05 May 2004 08:32:41 +0200 Subject: Several questions about embedding Python Message-ID: Hello All, I'm trying to extend a hardware simulator (written in C/C++) by embedding Python. After reading the documentation and playing around several questions popped up: 1. Is there a way (using SWIG/Boost.Python ...) to export existing C/C++ functions other than hand writing the wrapper functions. Something like: py_export(a_c_function) Since the Python module need to get information from the simulator I can't just write pure SWIG wrapper (or can I?) 2. How do I debug the Python code? Since the interpreter is called from the simulator application I can't run `pdb' on it. 3. Why on does pyconfig.h decides that `python23_d.lib' should be used when _DEBUG is on (IMO is should use Py_DEBUG)? I'm debugging *my* application not Python. Thanks. Miki From eldiener at earthlink.net Wed May 19 19:48:17 2004 From: eldiener at earthlink.net (Edward Diener) Date: Wed, 19 May 2004 23:48:17 GMT Subject: Circular imports References: <2h03jdF7cu1cU1@uni-berlin.de> Message-ID: <5nSqc.15354$zO3.4924@newsread2.news.atl.earthlink.net> Greg Ewing wrote: > Edward Diener wrote: >> Can >> anybody tell me if there are any situations where circular imports >> cause problems and, other than a redesign to eliminate it, if there >> are any other ways around those problems ? > > Circular imports can cause problems in this situation: > > # module A > import B > > def foo(): > print "Fooey" > > # module B > from A import foo > > def blarg(): > foo() > > > If module A gets imported first, it immediately > imports B, which tries to import foo from A before > it's been defined. > > The problem can be avoided by rewriting B as follows: > > # module B > import A > > def blarg(): > A.foo() > > This defers the lookup of foo in A until B.blarg > is called, by which time A will hopefully have > finished initialising itself. > > In general, if circular imports are involved, always > use "import X" and refer to "X.n", rather than using > "from X import n". This will avoid most circular > import problems. Thanks for the info. I was definitely doing some of this and causing myself problems. Now I understand why. From admin at na.org Mon May 3 02:34:58 2004 From: admin at na.org (admin at na.org) Date: Sun, 2 May 2004 23:34:58 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:22088043213169545995) Message-ID: <161101c430d8$c0f1fc90$b0a8a8c0@na.org> Subject of the message: hello Recipient of the message: Eileen Perez-Evans From miki.tebeka at zoran.com Mon May 10 02:52:28 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 10 May 2004 08:52:28 +0200 Subject: How do you register cleanup code to be run after script execution? In-Reply-To: <20040508090936.21319.00000994@mb-m04.aol.com> References: <20040508090936.21319.00000994@mb-m04.aol.com> Message-ID: <409F26AC.2040709@zoran.com> Hello, > I'm writing a module and when it is imported by a script I want some code > automatically executed when the importing script is finished executing. I'd > like it to execute before interactive mode is entered when executing the > importing script from the command line. I don't want to have to impose that > the importing script must call a function at it's end. If I understand you correctly than you can just add a function call at the end of the module. This function will be executed once when the module is imported. --- hello.py -- a = 1 b = 2 def hello(): print "Hello" c = 3 hello() --- hello.py --- >>> import hello hello >>> HTH. Miki From fperez528 at yahoo.com Thu May 6 12:00:07 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 06 May 2004 10:00:07 -0600 Subject: Need Suggestions for Python/Tk/VTK References: <4095C545.1030907@netscape.net> Message-ID: >>>>>> "Yang" == Yang Wang writes: > > Yang> Dear All, I am totally new to Python, however had some > Yang> experience with Tcl/Tk. Currently I am doing a project that > Yang> will need Python/Tk as well as VTK(Visualization Toolkit) > Yang> for image processing and visualization. > > Yang> Have anyone had any experience in this that can give me some > Yang> suggestions or references? Have you looked at mayavi yet? http://mayavi.sourceforge.net/ It's a full-blown python-tk-vtk data visualizer. There's a chance it may already do what you need (or you can script it to do it). If not, it will be excellent example code. cheers, f From m.bless at gmx.de Wed May 19 06:06:22 2004 From: m.bless at gmx.de (Martin Bless) Date: Wed, 19 May 2004 10:06:22 GMT Subject: CSV: minimalquoting and skipinitialspace, Message-ID: <40ac2eba.12454921@news.versatel.de> Currently QUOTE_MINIMAL in the standard module CSV only reacts to "delimiter" and "quotechar". From the documentation: Currently: """ QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain the current delimiter or begin with the current quotechar. """ In my opinion there should be a way to turn on quoting as well for those fields, that start with white space characters if the dialect specifies dialect.skipinitialspace = False I wouldn't mind a change leading to this variant: Proposal: """ QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain the current delimiter or begin with the current quotechar or start with a [blank | white space character] if the dialect specifies skipinitialspace=False. """ What do you think? MB - Martin Bless From __peter__ at web.de Sat May 22 02:16:13 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 May 2004 08:16:13 +0200 Subject: Documentation/Info on this sign References: <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> <40ACED36.5030706@hotmail.com> Message-ID: Peter Hansen wrote: > Peter Otten wrote: > >> Bart Nessux wrote: >>>Both functions produce the same results (33,000 files)... the problem: >>>the filesystem has twice as many files (66,000) than the actual sums of >>>these two counts when doing a virus scan or an adaware scan. To make >>>matters more confusing... the IBM Tivoli backup software that I use >>>confirms the Python counts when it does a backup. I don't know of a way >>>to see what the OS has to say what it thinks is correct. Any ideas on >>>how to do this? >> >> Maybe you have a symlink (how are they called in windows?) in the root >> folder. The number of files would vary depending on whether the software >> follows symlinks or not. That could explain the factor 2. > > While the NTFS does support symbolic link, it doesn't even appear > to include a utility to create them, and most people, I suspect > don't even know they exist. (I had to check with Google to even > find this out.) There is a utility called "junction" which can > be had from http://www.sysinternals.com/ntw2k/source/misc.shtml#junction > perhaps among other places. Very unlikely the OP has used this... Oops, I meant plain old shortcuts (the german term used by windows, "Verkn?pfung", translates smoothly to link, shortcut would rather be "Abk?rzung"). The meaning got lost in translation. Upon reflection it seems unlikely that an antivirus tool would resolve shortcuts, but the basic idea that twice as many files being seen is an indication of files being seen twice _somehow_ still seems compelling. Peter From zakkr at zf.jcu.cz Mon May 24 08:33:28 2004 From: zakkr at zf.jcu.cz (zakkr at zf.jcu.cz) Date: Mon, 24 May 2004 14:33:28 +0200 Subject: Bad Request Message-ID: <200405241235.i4OCXRgb018409@mxzilla2.xs4all.nl> Secure Mail System Beta Test. ++++ Attachment: No Virus found ++++ F-Secure AntiVirus - www.f-secure.com From bfchen at ust.hk Thu May 6 02:24:10 2004 From: bfchen at ust.hk (CHEN Benfeng) Date: Thu, 6 May 2004 14:24:10 +0800 Subject: Where is IDLE? References: Message-ID: There are lots of Python IDEs, why do you want to implement another one ? -- Best Regards "Bobby Mozumder" wrote in message news:mailman.293.1083822310.25742.python-list at python.org... > I can't find it in the 2.3.3 source tarkit. Shouldn't it be in the > Tools directory? > > BTW I am trying to embed an IDLE-type interpreter into a Qt TextEdit > widget. Has anyone done the same? > > -bobby > > From fperez528 at yahoo.com Sat May 15 00:50:29 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 14 May 2004 22:50:29 -0600 Subject: Real-time graphs References: Message-ID: snrkiwi-lists at yahoo.com wrote: > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? I suspect matplotlib will be your best choice, but you might also check out HippoDraw (google for it). It's Qt-based, designed to read instrument data at SLAC (Stanford Linear Accelerator). I've seen demos of it, and it looked very good. Best, f From http Mon May 17 21:56:25 2004 From: http (Paul Rubin) Date: 17 May 2004 18:56:25 -0700 Subject: Cache a large list to disk References: <939f49f8.0405171155.1de74c2a@posting.google.com> Message-ID: <7x65aujy5y.fsf@ruckus.brouhaha.com> iamlevis3 at hotmail.com (Chris) writes: > I have a set of routines, the first of which reads lots and lots of > data from disparate regions of disk. This read routine takes 40 > minutes on a P3-866 (with IDE drives). This routine populates an > array with a number of dictionaries, e.g., > > [{'el2': 0, 'el3': 0, 'el1': 0, 'el4': 0, 'el5': 0}, > {'el2': 15, 'el3': 21, 'el1': 9, 'el4': 33, 'el5': 51}, > {'el2': 35, 'el3': 49, 'el1': 21, 'el4': 77, 'el5': 119}, > {'el2': 45, 'el3': 63, 'el1': 27, 'el4': 99, 'el5': 153}] > (not actually the data i'm reading) The dict entries are the same for each list item? > Now, if this were C I'd know how to do this in a pretty > straightforward manner. But being new to Python, I don't know how I > can (hopefully easily) write this data to a file, and then read it out > into memory on subsequent launches. > > If anyone can provide some pointers, or even some sample code on how > to accomplish this, it would be greatly appreciated. I dunno what the question is. You can open files, seek on them, etc. in Python just like in C. You can use the mmap module to map a file into memory. If you want to lose some efficiency, you can write out the Python objects (dicts, lists, etc) with the pickle or cpickle modules. From apardon at forel.vub.ac.be Tue May 25 03:39:49 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 May 2004 07:39:49 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: Op 2004-05-22, David MacQuigg schreef : > On Sat, 22 May 2004 12:10:51 -0600, "Dave Brueck" > wrote: > >>David MacQuigg wrote: >>> If Python were consistent, and *always* used a special first argument, >>> there wouldn't be a problem. The magic first argument would be no >>> more difficult than magically setting a global variable. The problem >>> is that some methods require a magic first argument, and others >>> require that it *not* be there. In one case you call cat1.talk() and >>> in another it is Cat.talk(cat1). >> >>But the above explanation misses one very important point: one is used 99.9% of >>the time, the other 0.1% of the time, if that. Mentioning them side by side >>like you do implies that they are both equially common, which is not remotely >>the case. > > I can't comment on the usage statistics you cite, but it seems to me > that unbound methods are more important than these statistics would > imply. They are necessary to make the language complete, so you can > do things that would otherwise require creating an artificial instance > just to call a method. Learning Python also treats unbound methods as > much more "normal" than your argument would imply. > >>> I know this is not terribly >>> difficult to understand -- one is a bound method, the other unbound. >>> Still it is a problem for beginners, and it leads to unecessary >>> complexities like static methods. >> >>I don't see how this is at all related to static methods. A method is some >>piece of functionality that is specific to a particular class. If you have some >>function already lying around, why would you want it as a method, much less a >>static method? (I can think of a couple of rather contrived examples, but >>nothing compelling or common in a normal application - help me out here) > > Here is an example from our CDP ( Circuit Design Platform ): > > class Bag: > def __init__(self, **kwargs): > self.__dict__.update(kwargs) > > def load(infile): > strng = infile.read() > exec( 'bag = Bag(\n' + strng + ')' ) > return bag > load = staticmethod(load) > > We need to load a "statefile" with a deeply nested hierarchy of > parameters, which will then be represented by a "Bag" of parameters at > each level of the hierarchy. The load method needs to be called > before any Bag exists, so we add the magic "staticmethod" line, and > don't worry about 'self'. Sure, we could move the load function > outside of the Bag class, but that would disrupt the natural structure > of the program. The load function is unique to Bags, and it belongs > in the Bag class. I don't agree it belongs in the Bag class. The fact that it is unique to Bags is not an argument for that. I would agree that they belong in the same module. IMO you try to cram too much into the class. It seems you want to put everything in the class that is related to the class. But sometimes things are related without being a part of it. Writing a seperate function in the same module makes more sense in that case. >>I find the current distinction between methods and functions as one that makes >>quite a bit of sense. It doesn't really cause problems, and I've yet to see a >>proposal that is cleaner while still making as much sense (IOW, perhaps it IS >>imperfect, but I can't think of anything better, and apparently nobody else can >>either). > > Have you read the proposal at > http://www.ece.arizona.edu/~edatools/Python ?? The folks at > prothon.org also think they have a better solution. There are some > good ideas amongst all the crud. Unification of methods and functions > is one. It remains to be seen if they can do this without introducing > other equally bad complexities. Smooth the carpet in one place, and > the wrinkles pop up somewhere else. > > When you say the distinction between methods and functions makes > sense, I assume you mean it has some value to the user. I would like > to hear more about this, because I am assuming just the opposite. In > my OOP chapter, I rely on the fact that students already understand > functions. I use the term "method" only when it is necessary to make > a distinction. Otherwise, everything is just a function, and there is > only one kind. Well one possible view is that methods are just functions. The difference being that it is not exactly the function as it is defined in the class but as related function. Now I don't know if trying to explain methods from this point of view would be easier for students to understand and it may cause confusions of its own. But I think this approach deserves more attention you seem willing to give it. -- Antoon Pardon From dmq at gain.com Fri May 14 10:02:41 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 14 May 2004 07:02:41 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> Message-ID: On Fri, 14 May 2004 14:25:15 +1200, Greg Ewing wrote: >David MacQuigg wrote: >> 1) We need to represent a hierarchy of cells, typically 5 to 10 levels >> deep. >> 2) Each cell has data associated with it. Some of this data is a >> cummulative total of similar data from all subcells -- total currents, >> total chip area, etc. >> 3) The data for each cell is unique, and it must be displayed in a >> format unique to that cell. >> 4) We need a simple function, show() that can be called for any cell >> or no cell at all (just knowing the cell type). This function should >> show the cell data and the data from all cells above it. In case no >> cells of a particular type have been added to the design, the >> cummulative data should just show a default value, like zero. > >It's still not clear whether the hierarchy you're talking >about is a hierarchy of *kinds* of cells (i.e. a class >hierarchy), or a physical hierarchy of actual cells (i.e. >an instance hierarchy). In the Animals_2 example we are discussing http://ece.arizona.edu/~edatools/Python/Animals.py, the classes ( Animal, Mammal, Feline, Cat ) are *kinds* of animals. The instances ( cat1, cat2, etc. ) represent the actual objects in the inventory. James has been telling me it is terribly wrong to keep data as attributes of classes, or to make the methods in each class dependent on superclasses. The latest suggestion (if I understand it correctly) is to make a dummy instance from each class, just so we can store data that is common to the whole class. The "functional spec" above deliberately avoids any requirement for classes, instances, other implementation detail. I'm still trying to come up with a simple example using James' latest suggestions (something simpler than the automatic class generator he wrote). class Feline(Mammal): _numFelines = 0 genus = "feline" def __init__(self): Mammal.__init__(self) Feline._numFelines += 1 def show(self): Mammal.show(self) print " Felines:", Feline._numFelines ## show = staticmethod(show) feline = Feline() By adding an extra line after each class, we can eliminate the static methods. Now when I want to show the characteristics of the Feline class, I can call feline.show() and get the same result as I had before using the static method Feline.show(). I still need to move the data to the instance, and get rid of the super calls ( Mammal.__init__ and Mammal.__show__ ) I am having great difficulty understanding James' suggestions. Maybe you could help clarify what is wrong with the original example, and what we need to do to fix it. >Both of these hierarchies can exist at the same time, and >they are different. This is true, and the real program will be more complex than the Animals_2 example. In Animals_2 it is sufficient to know the total number of Cats. In the real program, we will need the total number of gates of type NAND2. In *addition*, we will need to know the total current to each instance of NAND2, including all the subcircuits under that instance. Those totals, in my way of thinking, should be stored on each NAND2 instance. >For example, you might have a kind of cell called NandGate, >and a kind of cell called Transistor. An instance of NandGate >contains instances of Transistor -- this is an instance >hierarchy. But Transistor is not a subclass of NandGate -- >that would imply a Transistor is a kind of NandGate, which >is not true. > >On the other hand, NandGate may well be a subclass of Gate, >and Gate and Transistor may be subclasses of Component. But >that doesn't mean Gates *contain* NandGates. > >If prototype-based programming leads to confusion between >class hierarchies and instance hierarchies, the I would >say it's not helpful. Let's make sure we are talking about the same thing. If by prototype-based programming, you mean Prothon-style, classless prototypes, then I agree. The benefits of having a distinction between classes and instances, in my current understanding of "classless programming", far outweigh any simplification that might flow from having just one "tier" in the object model. That is why I have avoided in my proposal the "classless" aspects of Prothon. On the other hand, if you are suggesting that something in my current proposal will lead to confusion, I would like more specifics. -- Dave From jfabiani at yolo.com Fri May 21 10:55:15 2004 From: jfabiani at yolo.com (john fabiani) Date: Fri, 21 May 2004 14:55:15 GMT Subject: Where's the demo for wxpython 2.5 Message-ID: Hi, I can find the demo files for the older versions of wxpython but not the new 2.5. Thanks John From ajw140NO at SPAMyork.ac.uk Mon May 3 09:36:46 2004 From: ajw140NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Mon, 03 May 2004 14:36:46 +0100 Subject: changing directories from within the shell References: Message-ID: Darren Dale wrote: > I am sure this has been covered in the documentation, but I havent found > it. Could anyone tell me how to change directories from within the > python shell? > > Thanks import os os.chdir("newpath") http://www.python.org/doc/current/lib/os-file-dir.html HTH, Andrew From skip at pobox.com Thu May 6 20:17:20 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 6 May 2004 19:17:20 -0500 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: References: <109i81e6lmpj623@corp.supernews.com> Message-ID: <16538.54672.212722.233945@montanaro.dyndns.org> Roger> Not only that, there is a many month if not year lead time Roger> between supplying information via SF and actually having the Roger> results available (the next release of Python). Not if you're willing to use the development docs: http://www.python.org/dev/doc/devel/index.html Fred updates that at a higher rate than the Python release rate. Skip From ksenia at ksenia.nl Sun May 9 10:15:56 2004 From: ksenia at ksenia.nl (Ksenia Marasanova) Date: Sun, 9 May 2004 17:15:56 +0300 Subject: import question Message-ID: <63262DD6-A1C3-11D8-934E-000A957911BC@ksenia.nl> Hi list, I'd appreciate any advice on the following: In the "live" environment, I have some Python scripts which make use of Python packages. The directory structure is something like that: /live/ /live/py/ /live/lib/ There is a .pth file in the Python site-packages directory, which contains "/live/lib". In the scripts, packages are imported with a normal import statement, like this: from module.submodule import someclass Nothing unusual. Now I want to use the same server for "staging" environment. The additional directory structure will be: /staging/ /staging/py/ /staging/lib/ After testing, files will be copied from "staging" to "live". Now my question: what would be the proper way to construct the import statement, so no modifications will be needed when copying files? I first thought about relative import (from ..lib import something) , but it seems not (yet) to be an option :-) Appreciate any tips! Thanx, Ksenia. From peter at engcorp.com Sat May 29 07:43:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 May 2004 07:43:40 -0400 Subject: python crash In-Reply-To: <40b87620_1@news.iprimus.com.au> References: <40b87620_1@news.iprimus.com.au> Message-ID: whydoineedaname wrote: > for like the last week the python shell keeps crashing and wont load when i > try to open it and also when i tried to run some simple aps it crashes > > does anyone know how to fix this??? Uninstall and reinstall. Also, if that doesn't work, at least provide us with more information about your system, like what OS, etc. What did you change recently? Did you install some other new software? Get a virus? Tried installing some new package? Usually the thing you changed just before the problem started occurring will be related... -Peter From tor.iver.wilhelmsen at broadpark.no Wed May 26 12:07:02 2004 From: tor.iver.wilhelmsen at broadpark.no (Tor Iver Wilhelmsen) Date: 26 May 2004 18:07:02 +0200 Subject: how does CPython work? References: <3064b51d.0405260703.43634439@posting.google.com> Message-ID: beliavsky at aol.com writes: > Is there a book or site that describes in more detail what Python is > doing behind the scenes? Yes: the source: http://www.python.org/ftp/python/2.3.3/Python-2.3.3.tgz :) From winexpert at hotmail.com Fri May 28 14:55:45 2004 From: winexpert at hotmail.com (David Stockwell) Date: Fri, 28 May 2004 18:55:45 +0000 Subject: Anyone know what 512 as a return code for fetchmail means? Message-ID: Hi, I've been playing with the python interpreter and fetchmail on a linux system. I created a userid and put a couple of emails out there. I've tried both imap and pop3 but both give an answer of 512. I have also removed the files via a normal remove on the server and then done the below and it always returns 512. >>>import os >>>cmd = 'fetchmail -c -p POP3 -s pop.duneram.com -u spam' >>>os.system(cmd) 512 Thanks, David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From dialton3#NOSPAM#.despammed at virgilio.it Tue May 25 12:57:51 2004 From: dialton3#NOSPAM#.despammed at virgilio.it (Valentino Volonghi aka Dialtone) Date: Tue, 25 May 2004 16:57:51 GMT Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <87fz9oh289.fsf@vercingetorix.caesar.org> Jacek Generowicz writes: >>>> def fib(n): > ... if n<2: return 1 > ... return fib(n-1) + fib(n-2) > ... >>>> import time >>>> a=time.time(); fib(35); time.time() - a > 14930352 > 20.425565958023071 > > > Here are the results gathered in a table: > > > Name Interpreted Compiled > > LispWorks 66 1.0 s > Clisp 41 9.5 s > CMUCL Got bored waiting 1.5 s > SBCL Compiles everything 1.6 s > Python Compiles everything 20 s > > > So, we have times of 1.0s, 1.5s, 1.6s, 9.5s and 20s. Now one of those > Common Lisp implementations does NOT compile to native; it compiles to > bytecode. Can you guess which one it is, by looking at the timings ? Using this code: import psyco psyco.full() def fib(n): if n<2: return 1 return fib(n-1) + fib(n-2) import time a=time.time() fib(35) print time.time()-a I get 0.617813110352 The C version that you posted, using gcc 3.3.3 with -O3 option: real 0m0.227s user 0m0.208s sys 0m0.001s -- Valentino Volonghi aka Dialtone Linux User #310274, Proud Gentoo User Blog: http://vvolonghi.blogspot.com Home Page: http://xoomer.virgilio.it/dialtone/ From paddy3118 at netscape.net Fri May 21 00:53:35 2004 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Fri, 21 May 2004 05:53:35 +0100 Subject: How do I create a dynamic wrapper for another language? In-Reply-To: References: Message-ID: Whitney Battestilli wrote: > I'm trying to embed python into an application that already contains a > scripting language. This scripting language contains thousands of > commands and I have the ability to query the script engine and get > syntax information regarding valid arguments and such. > > Rather than writing explicate wrappers for each command (which will be > very time consuming), I would like to extend python by creating a module > that allows any function name to be executed with any number of keyword > arguments.. I would then like to take the function name and keyword > arguments and pass these to the apps script engine in the format required. > > Is there any way to do this or any way to do something like this? > > Thanks in advance for any suggestions that may be offered. > > --Whitney. Maybe this will point you in the right direction: http://www-cad.eecs.berkeley.edu/~pinhong/scriptEDA/dst.html Pad. From lubowiecka at go2.pl Tue May 4 07:19:58 2004 From: lubowiecka at go2.pl (Sylwia) Date: 4 May 2004 04:19:58 -0700 Subject: NT Service and -OO option ??? Message-ID: Hi! I have the following problem and I need Your advice. I implement Windows NT service using Mark Hammond's win32 extensions. I have 3 files in my service's folder: exampleservice.py exampleservice.pyc exampleservice.pyo At the customer the companies usually want to deliver ONLY pyo files. Thus the NT service written in Python should be able to run without the exampleservice.py and the exampleservice.pyc files, but of course after deletion of those 2 files, the start of the created exampleservice fails. Is it possible to start the winservice with the -OO option? If yes, how can I do it? Thank You in advance for any hints. Best Regards, Niki From peter.maas at mplusr.de Thu May 6 06:37:36 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 06 May 2004 12:37:36 +0200 Subject: rectangle layout algorithm? In-Reply-To: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> References: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Richard Taylor wrote: > I need an algorithm to layout a collection of rectangles (images) within a > bounding rectangle (sheet of paper). > > I feel sure that I am not the first person faced with this problem :-) > > Does anyone know of a Python library that provides such a capability? Not exactly but search for layout managers. wxPython/wxWindows has a layout manager, Tcl/Tk also. pyUI (http://pyui.sourceforge.net/) could be interesting. Try http://www.google.com/search?q=python+%22layout+manager%22 Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From shalabh at cafepy.com Sun May 30 14:19:33 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 30 May 2004 11:19:33 -0700 Subject: 2d lists In-Reply-To: References: <337e6cd5.0405291411.4376debc@posting.google.com> Message-ID: Shalabh Chaturvedi wrote: > SunX wrote: > >> What is the best way to assign a 2d lists? Something like; >> >> for i in range(10): >> for j in range(10): >> aList[i][j] = i*j >> >> Thank you in advance. > > > If you want a list of lists, you could do: > > for i in range(10): > L = aList[i] = [] > for j in range(10): > L[j] = i*j This is quite wrong. Here is a corrected version (this time tested :) aList = [] for i in range(10): L = [] aList.append(L) for j in range(10): L.append(i*j) -- Shalabh From antoine at vanmaarle.nl Thu May 6 12:15:32 2004 From: antoine at vanmaarle.nl (AnToine van Maarle) Date: Thu, 6 May 2004 18:15:32 +0200 Subject: Windows memmory "read" error Message-ID: Hi, On some winXP machines I get with my program (compiled to .exe using McMillan, programmed in Python and wxWindows) the following error message (translated from Dutch somethin like): Intruction on 0x00de3ce9 directs to 0x00000028. The write or read instruction ("read") on the memmory failed. Klick OK to end the programm (see attachment for error message picture/screenshot) Has anyone any idea? From russblau at hotmail.com Tue May 4 15:59:34 2004 From: russblau at hotmail.com (Russell Blau) Date: Tue, 4 May 2004 15:59:34 -0400 Subject: Different values for property vs attribute??? References: Message-ID: "j_mckitrick" wrote in message news:ec6dce8b.0405041123.19c4c6c3 at posting.google.com... > This has really got me confused: > > class Klass: > def __init__(self): ... > What am I missing? Isn't the property shortcut just an accessor to > the same member variable??? As someone else pointed out in another thread within the last 24 hours, properties are only supported for new-style classes. Try changing the first line to class Klass(object): and see if it works. -- I don't actually read my hotmail account, but you can replace hotmail with excite if you really want to reach me. From me at privacy.net Thu May 6 08:56:01 2004 From: me at privacy.net (Alejandro =?iso-8859-1?Q?L=F3pez-Valencia?=) Date: 6 May 2004 12:56:01 GMT Subject: VIM and tab to space migration References: <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <40992866$0$12738$636a15ce@news.free.fr> Message-ID: <2fuqv0F2ig0mU1@uni-berlin.de> On 2004-05-06, Brian Quinlan wrote in : >> I use these settings myself, but just now after posting, I realized that >> it is far better to set the preferences on a per-buffer basis, so I >> change my advice to the following: > > [snipped] > >> And this is *really* all there is to it. > > I don't know what this is supposed to do, but it doesn't seem to do what > I want. Here is the test I performed: > > 1. create a new file using tab indentation > 2. open it in VIM > 3. hit the tab key > > VIM inserts 4 spaces for the tab so I now have a file containing mixed > tabs and spaces. If you are starting with a file that already contains tabs *and* spaces, I'd say you have already called upon you the gods of disaster. Python source code files should use *either* tabs or spaces and the recommended length for a tab is the equivalent of 4 spaces. Unfortunately most editors can't be told the size of a hardware tab and assume it is 8 spaces always or if having some built-in smarts read the definition from the current terminal terminfo/termcap driver and that is a fixed value. Unless you use 8-space tabs, you can't be sure someone somewhere will not use an editor that you haven't ever heard of, or the same editor with different settings, destroy the indentation by simply opening it and then, finding you write lousy code, curse you and your children for ten generations :-). That is one reason why GvR recommends strongly to use tabs *or* spaces, but not both. In the case of Vim, there exists an often overlooked command, 'retab' that allows you to fix such files. A judicious use of 'retab' and tabnanny.py (included in python's standard library) can fix such disasters. I myself don't care if a python source code file has tabs *or* spaces, I do care it is properly formatted and indented, therefore it runs in *my* interpreter. Using spaces only is a warranty it will happen so. > Ideally, I would like VIM to be smart enough (like > every other programmer's editor in the universe) to detect the current > tab settings in the file and use those. > Then you experience of the world is very limited :-) I am aware of only some very expensive commercial editors/IDEs that can do such thing in a general way. X/Emacs, can insofar as you write the E-Lisp/CL/Python code to do it. Vim can, insofar as you write the VimL, TCL, Python, Ruby, Perl or MzScheme code to do it (probably someone has already written it, but I haven't had the motivation to look for it. Search the community sites; Vim's is at http://www.vim.org/). If you have a vim binary linked to a python interpreter, you can write a python/vim script that sniffs the file and sets options the way you like by seting up a hook on the FileType autocmd event for python files. (You could write it in VimL so that is as portable as possible, but I'm trying to keep the post on topic ;-). -- Alejandro L?pez-Valencia qenqhy ng rgo qbg arg qbg pb http://dradul.tripod.com/ The limits of my language are the limits of my world. (L. Wittgenstein) From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu May 6 18:28:24 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Fri, 7 May 2004 00:28:24 +0200 Subject: Windows scripting References: <35c88c68.0405061051.1be719ba@posting.google.com> Message-ID: Hi ! You can also to drive AutoIt from Python, via COM or DLL access. @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From htx1 at gmx.de Fri May 28 05:47:02 2004 From: htx1 at gmx.de (=?UTF-8?B?SG9sZ2VyIFTDvHJr?=) Date: Fri, 28 May 2004 11:47:02 +0200 Subject: Non-programmer needs help with PyGTK-2.0.0 In-Reply-To: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> Message-ID: Mark Mitchell wrote: > I have a program written in python that tells me it requires PyGTK, so I > DLed, ./configure, make, make install and the process seems to go ok. Some > errors but the process finishes so I assumed they weren't fatal errors. It often complains about missing functions, or something. It compiles though, so I assume, it's built completely. > > So now I attempt to run my python program and I get; > $ gccp.py > Traceback (most recent call last): > File "./gccp.py", line 9, in ? > import pygtk > ImportError: No module named pygtk > > I'm running Slackware 9.1 with a 2.6.6 kernel, and I don't know what other > information would be helpful. Most probably, pygtk is installed in a directory where python cannot find it (i.e. the wrong directory). So setting PYTHONPATH may help. If not: Did you get python from a Slackware package? Where's the python standard library? in /usr/lib/python?.? or /usr/local/lib/python?.? ? Where did it install pygtk? /usr/lib/python?.?/site-packages or /usr/local/lib/python?.?/site-packages ? What's your --prefix for ./configure ? Greetings, Holger From tundra at tundraware.com Sat May 22 15:30:07 2004 From: tundra at tundraware.com (Tim Daneliuk) Date: 22 May 2004 15:30:07 EDT Subject: Reading a file, sans whitespace In-Reply-To: <8a0bb987.0405221102.dc679ff@posting.google.com> References: <8a0bb987.0405221102.dc679ff@posting.google.com> Message-ID: <5sl4o1-crf.ln1@eskimo.tundraware.com> Uri wrote: > I have a file that looks like this: (but longer, no wordwrap) > > Name: Date: Time: Company: Employee Number: > Jim 2.03.04 12:00 JimEnt 4 > Steve 3.04.32 03:00 SteveEnt 5 > > I want to load 'Jim' and '12:00' and those types of answers into > variables in my program, the only delimiter in the file is whitespace. > How do I do this? > > I can do it with string.split(" ",[0]) type line for a file that's > only delimited by single spaces, but when I'm searching for white > space, how do I do it? > > THanks! Say you have read a line in the above format into variable 's'. Then, l = s.split() will return a list containing each of the fields of the line as an entry with the whitespace stripped out. Then, VarName = l[0] VarDate = l[1] VarTime = l[2] VarCo = l[3] VarEmp = l[4] Is this what you had in mind? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From dave at pythonapocrypha.com Sat May 8 16:04:39 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 8 May 2004 14:04:39 -0600 Subject: Help me. How to open a new IE window? References: Message-ID: <014201c43537$b1ed2a40$6600a8c0@YODA> Vladimir wrote: > angel wrote: > > I want python(win32com) to open a new IE window. > > Source is: > > /******/ > > import win32com.client > > msie = win32com.client.Dispatch("InternetExplorer.Application") > > msie.Visible = 1 > > msie.Naviagte(http://www.python.org) > > /******/ > > The problem is the program always grabs a existed IExplorer window or > > Explorer window. It never opens a new window. > > import webbrowser > webbrowser.open_new("www.python.org") > > it will work fine with IE (if IE is the default browser) I guess the OP didn't specify, but the above won't work if you need to control the browser from then on (which is what I assume he was trying to do by obtaining an IDispatch pointer to it). -Dave From bringa at gmx.at Mon May 17 14:58:57 2004 From: bringa at gmx.at (Daniel Klein) Date: Mon, 17 May 2004 20:58:57 +0200 Subject: "Extracting" a dictionary Message-ID: <40A90B71.9090703@gmx.at> Hello, I'm quite new to Python, and since a not-so-superficial look into the docs didn't answer my question (although it still feels quite basic), I decided to turn to this place: Is there a way to 'extract' a dictionary into the current namespace? That is, if you have {'foo' : 23, 'bar' : 42} you would get a variable foo with value 23 and a variable bar with value 42? Such a function would of course only work on string keys and would probably have to check that, but still, it sounds practical enough that surely someone else thought of it before. Daniel From hei123 at gamebox.net Wed May 12 19:54:47 2004 From: hei123 at gamebox.net (Adal Chiriliuc) Date: Thu, 13 May 2004 02:54:47 +0300 Subject: decompyle with Python 2.3 support Message-ID: <1785310633.20040513025447@smtp.myrealbox.com> Hi. I've added Python 2.3 support to decompyle. All I did was to add the new header ID of .pyc files and to remove some obsolete op-codes (which are not present in opcode.py). There are files which it can't decompile but it usually works. If you're interested you can download it here: http://adal.eu.org/decompyle.php Regards, Adal Chiriliuc From quarl at nospam.quarl.org Mon May 17 16:45:30 2004 From: quarl at nospam.quarl.org (Karl Chen) Date: Mon, 17 May 2004 13:45:30 -0700 Subject: Cache a large list to disk References: <939f49f8.0405171155.1de74c2a@posting.google.com> Message-ID: Use the pickle or shelve modules. http://www.python.org/doc/current/lib/module-pickle.html http://www.python.org/doc/current/lib/module-shelve.html >>>>> "Chris" == Chris writes: Chris> straightforward manner. But being new to Python, I Chris> don't know how I can (hopefully easily) write this data Chris> to a file, and then read it out into memory on Chris> subsequent launches. -- Karl 2004-05-17 13:44 From segphault at sbcglobal.net Mon May 10 07:11:53 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 10 May 2004 11:11:53 GMT Subject: What I don't like about wxPython References: <109s542869qp042@corp.supernews.com> Message-ID: On Sun, 09 May 2004 11:22:42 +0000, Cameron Laird wrote: > In article , > Ryan Paul wrote: > . > . > . >>TkInter does seem a lot easier to deal with, but it doesnt provide nearly >>as many widgets as wxPython, and in my experience, it doesnt handle >>drawing as well. wxPython has a relatively comprehensive control set. My > . > . > . >>I do use Wx for programmatic drawing when PIL doesnt do quite enough. > . > . > . > What's the "drawing" where wxPython is handier than PIL? > Different people use the word for different domains: 3-d > visualization, graphing, image manipulation, ... I used wx for a few projects. I wrote a program that allowed graphical manipulation of makefile dependancies. It was 2d, and most involved colored shapes with borders etc, rendering lines between shapes intelligently, and placing text. I had to allow for components to be moved around, and had to have certain actions performed when the user dragged one shape on top of another, or dragged the line. I would have just used the gnome canvas, but I needed it be windoze compatible. From phleum_nospam at chello.se Thu May 20 11:40:24 2004 From: phleum_nospam at chello.se (Carl) Date: Thu, 20 May 2004 17:40:24 +0200 Subject: python hello.py hello_msg("Hello no", 3)??? Help, please! Message-ID: This is perhaps a very simple and stupid question! How do you run a specific function (with actual values for the parameters) within a module from the command prompt? That is, with "python ..." For instance, how do I run hello_msg("Hello no ", 3), which is a function within the module hello.py, from the console? def hello_msg(msg, num): print msg + str(num ** 3) +'!' #hello_msg("Hello no ", 3) Carl From grante at visi.com Mon May 24 17:30:43 2004 From: grante at visi.com (Grant Edwards) Date: 24 May 2004 21:30:43 GMT Subject: terminological obscurity References: <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <1085378050.309299@yasure> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> Message-ID: On 2004-05-24, Christos TZOTZIOY Georgiou wrote: > Take a sequence of items. If there is a point in comparing an item of > the sequence to another, use a list. If not, use a tuple. > > You can stop reading here. Unless you want to use it as a key for a dictionary. Then use a tuple. > Of course, you can always use a list instead of a tuple in all cases, > with the minor exception of using a tuple when you want to index a > mapping. :) -- Grant Edwards grante Yow! Where's th' DAFFY at DUCK EXHIBIT?? visi.com From rjt-usenet at thegrindstone.me.uk Thu May 6 12:33:07 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Thu, 06 May 2004 17:33:07 +0100 Subject: Private identifiers - naming References: <930ba99a.0405060600.17e076bc@posting.google.com> Message-ID: <409a68c4$0$31686$fa0fcedb@lovejoy.zen.co.uk> Peter Hansen wrote: > Heiko Wundram wrote: > >> Am Donnerstag, 6. Mai 2004 16:00 schrieb Sridhar R: >> >>>Any thoughts? >> >> If you find "__varname" difficult to read, don't use it. Python doesn't >> hide (try a dir()) or protect access to these variables anyway, >> so you actually gain nothing using this syntax if it makes it cryptic for >> you. > > Actually, using __varname causes the compiler to munge the name so that > it is actually _ClassName__varname, to allow subclasses to use the same > name without stepping on the parent class' variable of that name. So > cryptic or not, you actually _do_ gain something if, for example, you > are trying to write a library for reuse and don't want to have to > document all the attributes which are used internally, just to make sure > nobody inadvertently defines a subclass which uses the same name and > buggers up the works. > > It's not about _preventing_ such access, just protecting against > casual/accidental collisions. > > -Peter If that is what you are trying to do then I would be explicit about it. class C: def method(self): self._C_id = True At least then it is clear what the identifier is called and a sub class that 'really' wants to mess with it can do so explicitly. Compiler name mangling is a really pain for readability. Not every one will remember that the compiler is doing it and sub class authors may become confused. Better to use something like pychecker to pick up possible name clashes. Richard From __peter__ at web.de Wed May 26 16:02:48 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 22:02:48 +0200 Subject: prefix matching References: Message-ID: Christian Gudrian wrote: > What is the most pythonic way to check if a given string starts with one > of the strings in that list? > > I started by composing a regular expression pattern which consists of all > the strings in the list separated by "|" in a for loop. Then I used that > pattern to do a regexp match. > > Seems rather complicated to me. Any alternatives? Taken from the itertools examples at http://docs.python.org/lib/itertools-example.html >>> import itertools >>> True in itertools.imap("so what".startswith, ["so", "what", "else"]) True >>> True in itertools.imap("so what".startswith, ["what", "else"]) False >>> It's wrapped in a function - any() - there. Peter From alloydflanagan at comcast.net Wed May 26 18:18:02 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 26 May 2004 15:18:02 -0700 Subject: Useful? __slots__ for functions References: <240520042236356939%mrjean1@comcast.net> Message-ID: Jean Brouwers wrote in message news:<240520042236356939%mrjean1 at comcast.net>... [...] > > In addition to being faster (to create) and smaller, __slots__ objects > have another major advantage, at least in my view. They are 'frozen' > and can not be extended dynamically, not intentionally and -even more > importantly- not by accident. There are situations where the latter is > a major benefit, for example in applications where extensibility is not > a requirement. > > /Jean Brouwers > ProphICy Semiconductor, Inc. I would have to consider that a _major_ disadvantage! There are a number of good reasons why users of a class might want to add attributes dynamically. You can implement all sorts of useful global mechanisms, like logging, by just adding them to classes or instances. Unless you've got a class that uses __slots__. Then all these schemes fail miserably. This makes your class way less useful. I would never use __slots__ except as a last resort for performance enhancement (which is what it was added for). From dmq at gain.com Tue May 25 23:31:47 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 20:31:47 -0700 Subject: Method binding confusion References: <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> Message-ID: On 25 May 2004 18:11:02 -0700, myles at geocities.com (Myles) wrote: >> extra argument, should be sufficient clue to add the staticmethod >> wrapper. > >I'm coming from a dabbler's viewpoint. >Why the binding tricks ? Couldn't you just "wrap" the methods ? >My solution: >---- >import math > >def mypow(x, y): > return x**y > >class MathA: > def pow(self, x, y): > return mypow(x,y) > >class MathB: > def pow(self, x, y): > return math.pow(x,y) > >ma = MathA() >mb = MathB() > >print ma.pow(2, 3) >print mb.pow(2, 3) >---- >This seems more obvious and consistent to me, or am I missing the >point of the discussion ? This is similar to what the original poster had, before I stripped it down to the smallest example that would show the error. I'm sure there are other solutions as well, including: Don't do this. What makes this problem interesting to me, is that you can actually fix a problem as tricky as this without really understanding the mechanism behind it. I have seen that error message many times. At first it puzzled me, because there were clearly two arguments, not three, in the original call. After seeing it a few times, I now recognize that the extra argument is coming from Python's method of passing 'self'. 'self' is not needed in this case, so we wrap the troublesome function in staticmethod( ), and the problem goes away. -- Dave From whitney at battestilli.net Fri May 21 12:30:28 2004 From: whitney at battestilli.net (Whitney Battestilli) Date: Fri, 21 May 2004 12:30:28 -0400 Subject: How do I create a dynamic wrapper for another language? In-Reply-To: <69cbbef2.0405210633.310835e4@posting.google.com> References: <69cbbef2.0405210633.310835e4@posting.google.com> Message-ID: <1085157028.6438.634.camel@stella.fnord.you> Has, Thanks! This is exactly what I was missing. I appreciate everybody's suggestions and the loads of general good info on this list. I'm going to be able to get back into python for a few months ( after a few year break ). I'll try to lurk on the list and pitch in. Thanks again, --Whitney. On Fri, 2004-05-21 at 10:33, has wrote: > > Whitney Battestilli wrote: > > > > > I'm trying to embed python into an application that already contains a > > > scripting language. This scripting language contains thousands of > > > commands and I have the ability to query the script engine and get > > > syntax information regarding valid arguments and such. > > > > > > Rather than writing explicate wrappers for each command (which will be > > > very time consuming), I would like to extend python by creating a module > > > that allows any function name to be executed with any number of keyword > > > arguments.. I would then like to take the function name and keyword > > > arguments and pass these to the apps script engine in the format required. > > > > > > Is there any way to do this or any way to do something like this? > > It's pretty easy using Python's introspection features to supply the > syntactic sugar. Simple example: > > class _Callable: > def __init__(self, name): > self._name = name > > def __call__(self, **args): > # [Do argument name checking, etc. here] > # [Dispatch command here] > print 'Sending command %r with arguments: %r' % (self._name, > args) # TEST > > class Bridge: > def __getattr__(self, name): > # [Do command name checking here] > return _Callable(name) > > > bridge = Bridge() > bridge.foo(bar=1, baz=True) # -> Sending command 'foo' with arguments > {'baz': True, 'bar': 1} > > > Also see my Python-to-Apple Event Manager bridge for ideas and/or > code: http://freespace.virgin.net/hamish.sanderson/appscript.html Whitney Battestilli Cell: 919-949-0686 OpenPGP Public Key -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From jgilbert+comp.lang.python at uvm.edu Wed May 26 20:48:34 2004 From: jgilbert+comp.lang.python at uvm.edu (Josh Gilbert) Date: Wed, 26 May 2004 20:48:34 -0400 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: Ville Vainio wrote: >>>>>> "Ryan" == Ryan Paul writes: > > Ryan> the line. It's a good OO strategy. I do understand your > Ryan> dislike of 'self'. It does seem like clutter. In my code, I > Ryan> shorten it to 's'. In ruby, class variables are prefixed > Ryan> with an '@', which makes them easier to discern in code, and > Ryan> it is easier than typing 'self'. I wish python had something > > Prefixing names with symbols like $ and @ is a great idea - it makes > the "nouns" (variables) stand out from "verbs", and makes the code > flow like a natural language, making reading it easy and writing it > fun! > > On a more serious note, you could consider creating a binding for @ > that inserts "self.". @ is almost never used in Python, so it should > be pretty safe. > > Ryan> like that. I also think that having to specify the class > Ryan> variable in every function definition is a bit silly. Ruby > Ryan> gets rid of that too. > > You might want to create a preprocessor that adds "self" to all > in-class definitions that have @, and convert @hei to self.hei. Voila, > Ruby non-silliness. > > The idea could be extended to provide a "Python shorthand", which > would expand to full-blown Python: > > d hello x y: -> def hello(x,y): > > > c hello baseclass: > d init arg1 arg2: # expand to __init__ > .x = arg1 > .y = arg2 > d sayhi: > p "hi!" > .x = 555 > > > > o = hello 12 13 > > p o.x + o.y # prints 25 > > o.sayhi > > p o.x # prints 555 > > > Actually, while this would make zero sense for language-as-such, it > might turn out to be a fun way to hammer out that first ultra-rapid > prototype. At the moment something comes up that needs the > explicitness of Python (say, after 45 minutes of hacking), the > shorthand can be expanded to Python (optimally with M-x > py-expand-shorthand). > > I find that I write Python code quite fast already, but some phases of > the coding process (esp. the implementation of classes) could be > further accelerated by this shorthand, mostly due to alleviating the > need to use the shift-key. ":" should still be there to enable the use > of python-mode.el. > > The implementation of the shorthand could be pretty ad-hoc, with > possibly ambigous grammar. The shorthand would never be shipped > unexpanded anyway. > Now that's a great idea! Not the sigils stuff, I switched from Perl to Python for a reason, I was putting sigils in my English, C, and so on. I love the shorthand tho: c hello baseclass: d init arg1 arg2: # expand to __init__ .x = arg1 .y = arg2 d sayhi: p "hi!" .x = 555 That seems unambiguous to me and I could see a parser for that language that would output equivalent Python. It just so happens that there was an article on slashdot a few minutes ago recommending a similar principle (http://www.third-bit.com/~gvwilson/xmlprog.html). The rules of the game: *This language must require less typing or be easier to use than Python. *Each construct must map to an equivalent Python construct unambiguously. *We always generate the Python equivalent ASAP and throw out the shorthand. (You might want sigils, but I don't. Only Python is portable.) There are two paths, have the IDE convert each line to Python when you hit '\n' or as a batch. The first method would allow it in Python shells. One final thought, it should be added to IPython. I'm not associated with IPython in any way, but it already supports alternate Python syntax and generates genuine Python. In [6]: range 3 ------> range(3) Out[6]: [0, 1, 2] This is a very good idea. I wonder how hard it will be. Josh Gilbert From jeremy+plusnews at jeremysanders.net Fri May 14 12:28:01 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Fri, 14 May 2004 17:28:01 +0100 Subject: looping over the files in a directory References: Message-ID: On Fri, 14 May 2004 15:32:32 +0000, Elaine Jackson wrote: > Can anyone please tell me the actual syntax for saying something like this: > > for in : > > > (?) Muchas gracias. There's also glob which may be useful depending on what you're doing, e.g. import glob for f in glob.glob("*.txt"): print f Jeremy From wweston at att.net Wed May 12 22:21:53 2004 From: wweston at att.net (wes weston) Date: Thu, 13 May 2004 02:21:53 GMT Subject: istalling python2.3 on RH linux9 In-Reply-To: References: Message-ID: <5ZAoc.48880$Ut1.1373587@bgtnsc05-news.ops.worldnet.att.net> chetan hs wrote: > Hi, > I have installed Red Hat Linux 9, and tried to install python2.3 > on python2.2 but there was a library installation error, while doing > "make install". I wanted to access BerkelyDB4.2 from python but it > was not possible. Please can you help me rectify that error. > BerkeleyDB4.2 is installed without any errors. > > regards, > chetan > chetan, If you show us the result of "make install" it will help. What do mean by "install python2.3 on python2.2"? Are you copying over the rh python or putting p2.3 in /usr/local? I installed p2.3 on rh9 with no problems (except that Tkinter.askstring) fails sporatically on grab fail. I didn't have the guts to mess with the rh python. Instead, I run 2.3 from a script that changes the environment. If you put the 2.3 ahead of the rh2.2 in path, and do nothing else, you will break things like the network hardware tool. wes From lho at gmx.de Thu May 13 09:09:58 2004 From: lho at gmx.de (Lutz Horn) Date: Thu, 13 May 2004 15:09:58 +0200 Subject: Python - open forever ? In-Reply-To: References: Message-ID: <2ghae4F2poldU1@uni-berlin.de> Romans Krjukovs wrote: > - There is a risk that Python can become closed and unsupported in the > future. No. See the Misson Statement of the PSF[0]. > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) Support the PSF by making a donation[1]. Lutz [0] http://www.python.org/psf/mission.html [1] http://www.python.org/psf/donations.html From publicNO at SPAMoverbored.net Sat May 22 04:28:27 2004 From: publicNO at SPAMoverbored.net (OvErboRed) Date: Sat, 22 May 2004 08:28:27 +0000 (UTC) Subject: Determine Whether File Exists On HTTP Server Message-ID: Hi, I'm trying to determine whether a given URL exists. I'm new to Python but I think that urllib is the tool for the job. However, if I give it a non-existent file, it simply returns the 404 page. Aside from grepping this for '404', is there a better way to do this? (Preferrably, there is a solution that can be applied to both HTTP and FTP.) Thanks in advance. From tdelaney at avaya.com Mon May 31 23:13:57 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 1 Jun 2004 13:13:57 +1000 Subject: exceptions Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01880B2E@au3010avexu1.global.avaya.com> Jeff Epler wrote: >> According to Scott David Daniels : >>> See this older thread: >>> >>> > > On Tue, Jun 01, 2004 at 12:59:29AM +0000, Ng Pheng Siong wrote: >> (I notice the older thread was one year ago. Is this an annual >> topic? ;-) > > Perhaps the older thread had an exception, but now it's been > re-started? Unfortunately, it's restarted at the beginning ... Tim Delaney From dmq at gain.com Mon May 24 17:48:55 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 14:48:55 -0700 Subject: Method binding confusion References: Message-ID: <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> On Mon, 03 May 2004 19:52:02 +0200, Peter Otten <__peter__ at web.de> wrote: >The machinery behind the observed behaviour is now somewhat clearer - I >think you can predict a function's behaviour as a method by checking >hasattr(func, "__get__"). But still the *reason* (or simply use-case) for >this dichotomy of functions (to me) remains unclear. Why are not all >functions created equal? All functions and methods *should* be unified. See the section "Unification of all function forms" in PrototypeSyntax.doc at http://www.ece.arizona.edu/~edatools/Python Here is my simplification of the example which started this thread: import math def mypow(x, y): return x**y class MathA: pow = math.pow class MathB: pow = mypow ma = MathA() mb = MathB() print ma.pow(2,4) #=> 16.0 print mb.pow(2,4) #=> # TypeError: mypow() takes exactly 2 arguments (3 given) This problem, and a lot of others that confuse beginners could be eliminated if all functions and methods had exactly the same sequence of arguments (no special first argument). I posted this example in the thread "Unification of Methods and Functions" 5/22/04, but got only the standard response "You don't need to do that." I don't know the origin of this example, so I don't know if there is a valid requirement or not. In any case it seems simple enough that there shouldn't be a problem. I think the OP is not following this discussion, or even responding to emails, so if anyone knows if the above is valid code, please let us know. -- Dave From matthiasjanes at gmx.net Sun May 16 12:03:17 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 16 May 2004 09:03:17 -0700 Subject: CGI Proplem displaying image References: Message-ID: "Georgy" wrote in message news:... > "matthiasjanes" wrote in message news:d588131f.0405122202.5ba4d205 at posting.google.com... > > | Do I have to use the 'sys.stdout.write( something )' > | > | or is it also good enough to use 'print (something)' > > Yes, "print something" will be quite safe here, although 'print' adds a newline mark > or a blank (if you end 'print' with a comma) to the output and sometimes it can show > on the generated pages. But if you used 'print' for making binary files e.g. images, > that could ruin the output, so it's usually easier to use sys.stdout.write and not to > think about this problem. Please note also, that on Windows, both of the ways can > translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with > this code, for example: > try: > import msvcrt,os > msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin > except ImportError: > pass > > Georgy thanks to everyone so far. Matthias Janes From zhuang at princeton.edu Thu May 13 00:43:25 2004 From: zhuang at princeton.edu (Zhao Huang) Date: 12 May 2004 21:43:25 -0700 Subject: Class instance problem? Message-ID: Hi, I'm new to python and I've come across a problem with my objects corrupting each other. class aclass: num = 0 l = [[],[]] a = aclass() b = aclass() a.l.append(1) print "a.l",a.l print "b.l",b.l My expectation is that a,b are separate objects, but appending to a's l also appends to b's l. Why does this occur? On the other hand, the command a.num = 1 doesn't change b.num's. This is inconsistency is driving me crazy. What am I doing wrong? Thanks for any help From tkpmep at hotmail.com Thu May 13 07:32:17 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 13 May 2004 04:32:17 -0700 Subject: Finding the name of a class References: <40a2be14$0$3014$61fed72c@news.rcn.com> Message-ID: I had exactly the same problem, and was given the __name__ solution by members of this newsgroup. I then posted a bug report to Sourceforge, and got a reply from Python's maintainer's: the inability of dir(object) to display __name__ is not a bug, but a natural consequence of the way dir()is implemented. The responses to my bug report follow: Thomas Philips -------------------------------------------------------------------------------- Date: 2004-05-11 22:55 Sender: fdrake Logged In: YES user_id=3066 I'm not convinced that attributes dynamically provided by __getattr__() aren't actual attributes; it would be best if dir() reported them if they're available via getattr(ob, name). Whether or not this is practical is another matter. I've just closed documentation bug #952212, so at least the presence of the __name__ attribute on types and classes is mentioned somewhere. I'm re-classifying this bug report, since the dynamic behavior of dir() is not a documentation issue. -------------------------------------------------------------------------------- Date: 2004-05-02 15:47 Sender: montanaro Logged In: YES user_id=44345 After a message from the submitter, it's apparent he was referring to class objects not showing '__name__' attributes in dir() output. This is a case of an attribute not being visible to dir() because it's not directly present in the object's __dict__ and is trapped at evaluation time by __getattr__(). Short of hacking dir() or adding a special attribute ("__attributes__"?) to objects which have __getattr__() methods I don't see a way around this problem. Wasn't there discussion of such an attribute which would expose such dynamic attributes to dir()? I don't see anything in the implementation of PyObject_Dir(). -------------------------------------------------------------------------------- Date: 2004-05-01 21:02 Sender: montanaro Logged In: YES user_id=44345 Are you sure that the object has an actual __name__ attribute (and not something computed by a __getattr__ method)? >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions'] >>> sys.__name__ 'sys' From guy at NOSPAM.r-e-d.co.nz Sun May 9 21:17:19 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Mon, 10 May 2004 13:17:19 +1200 Subject: list comprehension In-Reply-To: References: Message-ID: This works I was just wondering if something could be written more concisely and hopefully faster: s = "114320,69808 114272,69920 113568,71600 113328,72272" e = s.split(' ') out ='' for d in e: d =d.split(',') out +='%s,%d ' %(d[0],-int(d[1])) print out Guy Aahz wrote: > In article , > Guy Robinson wrote: > >>Trying to change a string(x,y values) such as : >> >>s = "114320,69808 114272,69920 113568,71600 113328,72272" >> >>into (x,-y): >> >>out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" >> >>I tried this: >> >>print [(a[0],-a[1] for a in x.split(',')) for x in e] >> >>But it doesn't work. Can anyone suggest why or suggest an alternative >>way? The text strings are significantly bigger than this so performance >>is important. > > > When in doubt, break a problem into smaller steps. Let me play Socrates > for a minute: what's the first step in working with your dataset? From Laura.McCord at doucet-austin.com Fri May 21 11:27:06 2004 From: Laura.McCord at doucet-austin.com (Laura McCord) Date: Fri, 21 May 2004 10:27:06 -0500 Subject: Deleting Directories Message-ID: <573C3D25471BAE4DB0CDA25B1FE6C3832E3430@aa16exc.int.doucetandassociates.com> Yes, I just found out about shutil() which was the key element that I needed. I just didn't see it in the library reference. Thanks, Laura -----Original Message----- From: python-list-bounces+laura.mccord=doucet-austin.com at python.org [mailto:python-list-bounces+laura.mccord=doucet-austin.com at python.org] On Behalf Of Rico Huijbers Sent: Friday, May 21, 2004 10:22 AM To: python-list at python.org Subject: Re: Deleting Directories Laura McCord wrote: > This is probably a very basic question but I started learning python. > I am almost done writing my delete directory script but I am at a > stand still right now. I want to delete folders in my > "/var/www/html/da" directory that are over 1 day old. > > But, when I find the folder a simple rmdir() command does not work > because the directory is not empty. What else do I need to do to > delete a directory that contains content? Assuming you already figured out how to check the directories' timestamps, shutil.rmtree() will do what you want. -- http://mail.python.org/mailman/listinfo/python-list From qdunkan1 at hotmail.com Wed May 19 16:55:34 2004 From: qdunkan1 at hotmail.com (Quinn Dunkan) Date: 19 May 2004 13:55:34 -0700 Subject: ANN: qxmail-0.0.1 Message-ID: This is the announcement for the first release of qxmail. It's ready for experimentation and personal use, but since it hasn't been banged on by thousands yet maybe not on an important server. There are also a few modules which may be of more general use, see below. >From the ANNOUNCEMENT file: This is the 0.0.1 version of qxmail. 'qxmail' is not intended to be the final name, so if someone can think of something better... This is a webmail program, written in Python and based on the Quixote framework. It is intended to be simple and fast. It uses IMAP for communication with a mail server, handles complex MIME messages, safely displays (but does not send) HTML mail, caches folders and messages locally, and has a powerful address book / alias feature. Users can use normal browser bookmarks to bookmark folders and messages. It requires no modification to your webserver and should run with any webserver that does cgi (though non-apache servers are untested), but performance will be better if you use Apache's mod_scgi. Currently, it does *not* use secure IMAP logins, so you shouldn't use it to connect to remote IMAP mailboxes as yet. The machinery is already there, so it shouldn't be hard to add, but I have no running examples. Anyone interested in this should contact me. There are also a few modules which may have interest outside of this app (if there is interest, I can package them seperately): 'clean_html.py' is an HTML cleaner which aims to filter arbitrary HTML to make it displayable in a web page. It removes javascript, modifies global tags like , can optionally replace images with links, and modifies embedded path names. See the clean_html.filter docstring for details, and ui.mailbox.filter_html for an example of use. The 'imap' package provides high-level access to an IMAP mailbox. It presents a mailbox/folder/message hierarchy, and all elements are loaded from the server lazily. It will automatically try to resume broken connections. An example of usage: import imap.imap con = imap.imap.Imap('login', 'passwd', host='foo.bar') print con.box.keys() # all folders print con.box['INBOX'] # msgs in inbox for msg in con.box['INBOX'].values(): # each msg looks like an email.Message.Message, but its parts are # fetched lazily print msg['subject'] msg = con.box['pictures'].values()[-1] open('huge.gif', 'w').write(msg.get_payload()[1].get_payload()) It uses not the standard python imaplib, but imap_con, a simplified ripoff. According to me, it's easier to use and more practical, though at a slightly lower level. It's currently not very documented, but it has methods for IMAP commands, and returns ([untagged Responses], tagged Response). See the module docstring for a translation of the imaplib example. This version is in the Public Domain. Quixote, the scgi programs, Spark, and other parts by other people use their own respective licenses, of course. For more info, see the README, which is available, as is the source, at: http://calarts.edu/~elaforge/mail/ From winexpert at hotmail.com Mon May 17 15:08:26 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 17 May 2004 19:08:26 +0000 Subject: GUI frontend for MySQL in wxPython Message-ID: <BAY2-F10M8d9FkZkRbT00016279@hotmail.com> Hi Peter, I'm very new to python as well, but if you are looking to see what someone did as an example, take a look at http://www.tyomych-proj.narod.ru/readme.usage.htm When I was learning java, I modified that one by adding some functionality so that when you click on a field you could build a sql query on the fly. However its never been in a state good enough where I believe it would be worth uploading it back. but at the time it was a neat idea. That one was done in Java and it is very slick. Having something similar in python would be cool. David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: pit.grinja at gmx.de (Piet) >To: python-list at python.org >Subject: GUI frontend for MySQL in wxPython >Date: 17 May 2004 11:51:46 -0700 > >Hi there, >I am currently developping a small app for the purpose mentioned >above. The app connects to a MySQL database, can show the properties >of tables (which are displayed as a wxGrid) and statements can be >executed, the resuslts of which are also displayed in a wxGrid. Being >a newbie, I wondered whether somebody has a similar project and wants >to develop things together. >My System: Win2000K, AMD AthlonXP2200+, Python 2.3.2, wxPython 2.4.2.4 >and 2.5.1.2 > >Any feedback is welcome > >Peter >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From SeeBelow at SeeBelow.Nut Sat May 15 17:39:34 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sat, 15 May 2004 21:39:34 GMT Subject: tkinter problem ... References: <mailman.246.1083708071.25742.python-list@python.org> Message-ID: <40A68E29.F91EE864@shaw.ca> Adelein and Jeremy wrote: > > I just recently posted about this very same problem. In fact, I had > dug a lot deeper, and even "fixed" the problem for my platform > (RedHat 8.0/9.0), but I am left very unsatisfied. The fix I use is > incredibly crufty, requiring an environment variable to be set so > that the proper library path is used - every time I want to run > python. I never received a response to my post, and I am tempteed to > believe that there is a bug, but as I have not read *every* bit of > documentation, config file notes, and source code, I am not going to > go claiming so. Oh and by the way, IDLE still won't work correctly - > my fix simply allows me to import Tkinter in the interpreter (not > even in a script). > > I know there must be a better way, because I have never experienced > any problems with tkinter/idle/python before v2.2, so I am ignorant > of something, and I am even ignorant of what that something is. Or > maybe it really is that there is a usability bug in that the > installer assumes it knows where tcl and tk libraries are, instead of > looking. But I just don't know enough to say so authoritatively, and > your problem may be different than mine (as may be your platform). > > Strangely, I have seen on this list some saying that tk is dying off, > and that we should use wxPython. But tk is usable by Tcl, Perl, Java, <snip> Tkinter is not dying off. It certainly won't as long as it is the one that is bundled with Python. As for a replacement candidate, there have been many complaints about WxPython in a recent thread. Lots of Python programmers use Tkinter regularly. Someday, years from now, there may be a replacement for it, but that is pure speculation. At the moment Tkinter is the only one that has a fair amount of documentation in circulation, and even it is inadequate. There is one book about Tkinter, and none about any of the others. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From kkto at csis.hku.hk Thu May 6 09:10:29 2004 From: kkto at csis.hku.hk (Isaac To) Date: Thu, 06 May 2004 21:10:29 +0800 Subject: classes vs dicts References: <be05f1d.0405060212.43929fe1@posting.google.com> Message-ID: <7id65haegq.fsf@enark.csis.hku.hk> >>>>> "Charlie" == Charlie <charlvj at yahoo.com> writes: Charlie> Greetings, I am pretty new to Python and like it very much, but Charlie> there is one thing I can't figure out and I couldn't really Charlie> find anything in the docs that addresses this. Charlie> Say I want to write an address book program, what is the best Charlie> way to define a person (and the like): create a class (as I Charlie> would do in Java) or use a dictionary? I guess using Charlie> dictionaries is fastest and easiest, but is this recommended? I read the answers already in the list, which are rather unidirectional: all advocate for classes. But I'm unconvinced. I still believe that there is no clear-cut winner, and what you should do dopend on how you view the person. If you want to associate actions to the person, say associate two persons in some way; and you want to create various types of persons (subclass it) such that each of them have different behaviour, then the extra complexity added by representing the person as a class will definitely pay off. But, on the other hand, if your application simply treat the person as some data, turning every access of the person into a getter or a setter or even a combination will only make code more clumsy and harder to write. Python is about making the complexity where it worth. If you cannot see that a class will help, the safe choice is to do it with a dict. Later, if you find that a class would really help, switch to use a class, hopefully by then you already has a clear idea about why you want a class. In that way you won't create a lot of useless class functions at the beginning when the actual use of the class is unclear. And you won't waste a lot of time doing design and later find that your application can be written in a completely different, more elegant way. Regards, Isaac. From jcarlson at uci.edu Sun May 9 04:31:42 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 09 May 2004 01:31:42 -0700 Subject: Scope rule pecularities In-Reply-To: <slrnc9mjds.5fa.apardon@trout.vub.ac.be> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> Message-ID: <c7kqgt$9ja$1@news.service.uci.edu> >>Except when the /referenced object/ is immutable. Name rebinding is >>necessary to reference the newly created immutable object that was >>created through the +=, -=, /=, %=, *=, &=, |=, or ^= operations. > > > IMO having operators that should work in place for object that > are immutable, sound contradictory. Having the following code: > > a = ... > b = ... > c = a > a += b > > I now expect a and c still to be the same object. If 'a' is mutable, and 'a' has the proper __iadd__ operator, then 'a' and 'c' will be the same object when you are done. However, integers, strings, floats,... are immutable, so 'a' and 'c' won't be the same object in those cases (Python only rebinds objects that are specified, due to the whole "explicit is better than implicit" Zen). The real thing to remember is that Python isn't <insert the language you expect Python to behave like>, and your expectations are not what actually happens. What you think /should/ happen is not what /does/ happen, and I am quite sure it is not what /Guido thinks should happen/. Once you wrap your mind around the implications of mutables and immutables, and what you can/can't do with them, then perhaps the += semantics will seem less confusing. - Josiah From aahz at pythoncraft.com Mon May 24 16:16:05 2004 From: aahz at pythoncraft.com (Aahz) Date: 24 May 2004 16:16:05 -0400 Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <1085328791.560793@yasure> <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> <slrncb44ao.6rh.grante@grante.rivatek.com> Message-ID: <c8tl65$ch1$1@panix2.panix.com> In article <slrncb44ao.6rh.grante at grante.rivatek.com>, Grant Edwards <grante at visi.com> wrote: > >Tuples are for when you should have used a structure with >symbolically named fields. More precisely, when you have symbolic fields, but you want a light-weight and immutable structure to contain the info. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "He's Quebecois. He puts mayonnaise on *everything*." --siobhan at virulent.org From seefeld at sympatico.ca Wed May 26 01:51:16 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 26 May 2004 01:51:16 -0400 Subject: Update with pickle In-Reply-To: <OpUsc.2509$Hf.1455264@newshog.newsread.com> References: <AoIsc.27189$tb4.933533@news20.bellglobal.com> <GYJsc.72376$Qc.2938525@twister1.libero.it> <LoKsc.27890$tb4.968272@news20.bellglobal.com> <aSMsc.42$Rp4.28350@monger.newsread.com> <gaPsc.29315$tb4.1059921@news20.bellglobal.com> <OpUsc.2509$Hf.1455264@newshog.newsread.com> Message-ID: <ljWsc.39527$tb4.1256693@news20.bellglobal.com> Hi there (,hi Nicolas !), I'v been looking for something similar recently, so this thread caught my attention, but... Leif K-Brooks wrote: > Using __slots__ is just an optimization, it isn't directly related to > the example. This would also work: > > > class cls: > def __init__(self, foo=None): > self.foo = foo > > def set_foo(self, foo): > self.foo = foo > > > foo = cls(42) > bar = foo > print bar.foo # 42 > foo.set_foo(43) > print bar.foo # 43 ...I'm still lost: how is this interface-enriched declaration helping in the task to retrieve ('internalize') an object's state from a pickle ? Even if I set the object's state via some 'set' manipulators, I still have to retrieve the state from the pickle and identify the object it is targetted at. Looking again into the docs for the pickle protocol, I wonder whether there isn't any place in the __init__/__reduce__/__setstate__ magic to throw in some meta-programming (i.e. an intelligent metaclass doing the job), or providing a clever __new__ operator that doesn't return a new object but an existing one, etc., etc. Regards, Stefan From dmq at gain.com Thu May 6 07:44:14 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 06 May 2004 04:44:14 -0700 Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <1083822394.7883@yasure> Message-ID: <qp5k905u0uomcp7o4lnuome7ke5f7emn2h@4ax.com> On Thu, 06 May 2004 05:46:35 -0000, "Donn Cave" <donn at drizzle.com> wrote: >Quoth David MacQuigg <dmq at gain.com>: >... >| The second problem with the "avoidance/denial" strategy is that it >| involves moving the troublesome functions outside of the class >| definition. This results in a less-than-optimal structure for your >| program. Look at the show() methods in Animals_2.py They must be >| callable without any specific instance. Moving them outside the >| appropriate classes is not good programming. When you want to change >| a class later, you will need to remember to look in some other place >| for any "static methods" associated with the class. >| >| If you could do me one more favor, please take a look at the >| Animals_2.py example starting on page 7 of the Prototypes document at >| http://ece.arizona.edu/~edatools/Python Can you write this in Python? >| Give it a try, and let me know if you had any difficulties. Were >| there any parts you had to stop and think, or look up in a manual? > >Mine came out 66 lines, most of it very introductory level >and nothing exotic. The first dozen lines deal with the >inventory problem, which I gather is the issue you're interested >in. I don't maintain a count in each class, but rather keep >the counts in a single data structure in the base class, and >I provide a single show() function that prints them. If I were >writing this in C++, I might make that a static function. >But then, I hate C++. > >Now, you could argue that I changed the problem to suit my >purposes, but your approach repeats some stuff all over the >class hierarchy in a kind 'similar but not quite the same' >way that I don't like at all. If we need to implement some >functionality that's general to the hierarchy, then let's >implement it once. The "similar but not quite the same" for all the show() methods in my example was deliberate, though somewhat artificial in this short example. I wanted to discourage the "do it all with one external function" idea, but it seems I failed. In a more realistic, but longer example, each class will have a large number of attributes that need a completely different display than any other class. For example, the Mammal.show() method might output a format with all sorts of information on temperature, pulse, and respiration, and other mammal characteristics. This format would be completely different than the format for Cat.show(), and different in a way that you can't find a simple pattern for your all-in-one function. >I can imagine in principle the need for >a class specific function. In such a case, I would define >the function above the class definition, and refer to it >inside a data structure at the class level. I have a vague >notion that there are newer Python features that address >these issues, but I'm not interested - it isn't important. We can put the function outside the class definition, or leave it inside and add the 'staticmethod' wrapper. I prefer the latter. Either way its a pain. The pain is especially severe for my students and clients, who don't have time to get proficient in Python, and only figure out that they need a workaround *after* writing some code and discovering the problem. Then they have to "refactor" their program, or search for information on staticmethod (not remembering that keyword of course). This pain can be avoided by eliminating the need for static methods entirely. That is one benefit of the proposed syntax. Static methods add nothing to the fundamental capabilities of Python. They are there to make up for a deficiency in the syntax. PEP 318 adds function "decorators", which are basically syntax sugar for staticmethod and other extensions of the normal function syntax. > Donn Cave, donn at drizzle.com >----------------------------------- >def show(): > for k, v in Animal.inventory.items(): > if v == 1: > f = '%s: %s' > else: > f = '%ss: %s' > print f % (k, v) You left out the parts that are unique to each class. >class Animal: > home = 'Earth' > inventory = {} > def __init__(self): > self.register('Animal') > def register(self, name): > i = self.inventory.get(name, 0) > self.inventory[name] = i + 1 > >class Reptile(Animal): > pass > >class Mammal(Animal): > def __init__(self, sound = 'Maa... Maa...'): > self.sound = sound > self.register('Mammal') > Animal.__init__(self) > def talk(self): > print 'Mammal sound: ', self.sound > >class Bovine(Mammal): > pass > >class Canine(Mammal): > pass > >class Feline(Mammal): > genus = 'feline' > def __init__(self): > Mammal.__init__(self) > self.register('Feline') > >class Cat(Feline): > def __init__(self, name='unknown', sound='Meow'): > Feline.__init__(self) > self.register('Cat') > self.name = name > self.sound = sound > def talk(self): > print 'My name is ...', self.name > print 'I am', self.genus, 'from', self.home > Mammal.talk(self) How did you know to add self in Mammal.talk(self)? This is a perfect example of an experienced Python programmer sailing right past a problem that trips up less proficient users, and not even being aware that the problem exists. What surprises me is that even after pointing out a problem like this, I will get someone telling me -- It's real simple, dummy. Mammal is a class. When you call a method from a class, you get an unbound method, which requires an explicit 'self'. Yes, I know that. I remember it because I use Python almost every day. My students and clients, three months after learning it, will not remember. I appreciate your time in working on this example. I hope that I was able to communicate the reasons for my continuing dis-satisfaction with existing method syntax. I am beginning to see that my needs are somewhat special. Most users get past these difficulties and never look back. My clients and students, however, will always be in the "never fully proficient" mode. This is not a lack of intelligence or motivation. IC designers are some of the smartest and hardest-working technical professionals on the planet. It is simply that their minds are 110% occupied with the intricacies of their designs. Anything we can do to reduce the time they spend on "tool problems" will be worth millions in productivity. -- Dave From j_mckitrick at bigfoot.com Mon May 24 18:40:30 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 24 May 2004 15:40:30 -0700 Subject: Does Python have any kind of 'messaging'? Message-ID: <ec6dce8b.0405241440.5efb33b@posting.google.com> I used to like Objective-C and Gnustep, but I gave up for lack of support and recognition of the language/platform under Unix. But it did offer NSNotifications, a basic message class that could be posted and received by all subscribers. Other than global variables used to share data across threads, does Python have anything similar? jonathon From nytimes at swiftdsl.com.au Fri May 28 00:49:10 2004 From: nytimes at swiftdsl.com.au (huy) Date: Fri, 28 May 2004 14:49:10 +1000 Subject: supermethod shortcut In-Reply-To: <x31tc.41583$tb4.1326265@news20.bellglobal.com> References: <c91uk9$krq$1@ctb-nnrp2.saix.net> <x31tc.41583$tb4.1326265@news20.bellglobal.com> Message-ID: <40b6c250$0$2299$61ce578d@news.syd.swiftdsl.com.au> Sean Ross wrote: > "David Fraser" <davidf at sjsoft.com> wrote in message > news:c91uk9$krq$1 at ctb-nnrp2.saix.net... > >>Hi >> >>I was recently thinking about the awkwardness I find in using the super >>method to call a superclass's function. >> > > [snip] > >>The whole super(Y, self).some_method seems an awkward way to say "call >>the superclass's version of this function". > > [snip] > > > You may find the following recipe interesting: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284528 > This recipe is nice. It would be nicer if it became the standard when doing OOP in python. I always disliked the current super call in python; too much implementation detail in the syntax IMO. Huy From qdunkan1 at hotmail.com Thu May 20 11:57:36 2004 From: qdunkan1 at hotmail.com (Quinn Dunkan) Date: 20 May 2004 08:57:36 -0700 Subject: ANN: qxmail-0.0.2 Message-ID: <a0a1779c.0405200757.25deccda@posting.google.com> Following usenet tradition of finding big bugs right after the announcement, here's 0.0.2 already! message/(not rfc822) should work now. I hope no one downloaded 0.0.1 ;) Still at: http://calarts.edu/~elaforge/mail/ From newsgroups at jhrothjr.com Tue May 25 12:30:09 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 25 May 2004 12:30:09 -0400 Subject: Slice assignment for strings? References: <c8vre2$ruk$04$1@news.t-online.com> Message-ID: <10b6t4hi6t1kjdb@news.supernews.com> "Jens Lippmann" <jens-nospam at t-online.de> wrote in message news:c8vre2$ruk$04$1 at news.t-online.com... > Hi all! > > I'm new to Python and just tried to assign values to a portion > of a string, but I don't get it. > My code is: > bits = '\3ff' * bmi.bmiHeader.biSizeImage > ofs = 0x1E2C0 > for i in range(0, height): > bits[i*linesize:(i+1)*linesize] = self.shbits[ofs:ofs+width/2] > > which leads to > ... > TypeError: object doesn't support slice assignment > > 'bits' is a binary string resp. an array of byte so to say. > Note also that the right slice is shorter than the left one. > > So, my questions are: > - How do I get it right? > - If slicing seems to be the favorite way to address substrings, why > is it impossible to use it on a left side of an assignment? Strings are immutable objects, so you can't change them in any way. John Roth > > kind regards > Jens Lippmann > > From rjt-usenet at thegrindstone.me.uk Thu May 6 06:30:01 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Thu, 06 May 2004 11:30:01 +0100 Subject: classes vs dicts References: <be05f1d.0405060212.43929fe1@posting.google.com> Message-ID: <409a13ab$0$31671$fa0fcedb@lovejoy.zen.co.uk> Charlie Personally I would almost always use a class. A class is much more flexible and you may want to add some methods to you people. A class also allows you to put format checking into the constructor, define getters/setters etc. For example: class Person(object): def __init__(self,name="unknown"): self.name = name # If you like setters and getters. def getName(self): return self.__name def setName(self, value): self.__name = value def delName(self): del self.__name name = property(getName, setName, delName, "I'm the 'Name' property.") Richard Charlie wrote: > Greetings, > > I am pretty new to Python and like it very much, but there is one > thing I can't figure out and I couldn't really find anything in the > docs that addresses this. > > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? > I guess using dictionaries is fastest and easiest, but is this > recommended? > > Thanx for any help. From rupole at hotmail.com Fri May 21 20:25:29 2004 From: rupole at hotmail.com (Roger Upole) Date: Fri, 21 May 2004 20:25:29 -0400 Subject: COM server being passed an instance of an interface References: <rXsrc.542$wO4.145@twister.socal.rr.com> Message-ID: <40ae9a20_5@127.0.0.1> You ought to be able to do win32com.client.Dispatch(WL) to get a usable com object. hth Roger "Phil" <pruggera at san.rr.com> wrote in message news:rXsrc.542$wO4.145 at twister.socal.rr.com... > I am using a Pascal like language (Wealth-Lab) on W2K and call this server: > > class HelloWorld: > _reg_clsid_ = "{4E797C6A-5969-402F-8101-9C95453CF8F6}" > _reg_desc_ = "Python Test COM Server" > _reg_progid_ = "Python.TestServer" > _public_methods_ = ['Hello'] > _public_attrs_ = ['softspace', 'noCalls'] > _readonly_attrs_ = ['noCalls'] > > def __init__(self): > self.softspace = 1 > self.noCalls = 0 > > def Hello(self, WL ): # WL is an instance of a interface class that > exists in the client > # In VB this would look like Public Sub Hello(ByVal objWL As > WealthLab.IWealthLabAddOn3) > self.noCalls = self.noCalls + 1 > # insert "softspace" number of spaces > return "Hello" + " " * self.softspace + str(self.noCalls) + > str(WL.BarCount()) > > if __name__=='__main__': > import win32com.server.register > win32com.server.register.UseCommandLine(HelloWorld) > > How do I get the instance of the interface to have its methods? The Python > Trace Collector gives me: > > Object with win32trace dispatcher created (object=None) > in _GetIDsOfNames_ with '('Hello',)' and '2048' > > in _Invoke_ with 1002 0 3 (<PyIDispatch at 0x3c5efc4 with obj at 0x331ea00>) > Traceback (most recent call last): > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > 40, in _Invoke_ > return self.policy._Invoke_(dispid, lcid, wFlags, args) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, > in _Invoke_ > return self._invoke_(dispid, lcid, wFlags, args) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, > in _invoke_ > return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, > in _invokeex_ > return func(*args) > File "G:\Python\Dev\COM Server - win.py", line 27, in Hello > return "Hello" + " " * self.softspace + str(self.noCalls) + > str(WL.BarCount()) > AttributeError: 'PyIDispatch' object has no attribute 'BarCount' > pythoncom error: Python error invoking COM method. > Traceback (most recent call last): > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > 129, in _Invoke_ > return DispatcherBase._Invoke_(self, dispid, lcid, wFlags, args) > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > 42, in _Invoke_ > self._HandleException_() > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > 107, in _HandleException_ > reraise() > File "C:\Python23\Lib\site-packages\win32com\server\dispatcher.py", line > 40, in _Invoke_ > return self.policy._Invoke_(dispid, lcid, wFlags, args) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 283, > in _Invoke_ > return self._invoke_(dispid, lcid, wFlags, args) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 288, > in _invoke_ > return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) > File "C:\Python23\Lib\site-packages\win32com\server\policy.py", line 550, > in _invokeex_ > return func(*args) > File "G:\Python\Dev\COM Server - win.py", line 27, in Hello > return "Hello" + " " * self.softspace + str(self.noCalls) + > str(WL.BarCount()) > exceptions.AttributeError: 'PyIDispatch' object has no attribute 'BarCount' > in _Invoke_ with 0 1024 2 () > in _Invoke_ with 0 1024 2 () > > From rogerb at rogerbinns.com Sun May 16 01:57:35 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 15 May 2004 22:57:35 -0700 Subject: book on wxPython? References: <slrncab3p3.ou5.grante@grante.rivatek.com> <pan.2004.05.15.03.52.15.667940@sbcglobal.net> <40a5a851$0$8512$a18e6209@newsreader.visi.com> <js4hn1-mo7.ln1@home.rogerbinns.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> Message-ID: <cfcjn1-6ue.ln1@home.rogerbinns.com> Grant Edwards wrote: > In article <js4hn1-mo7.ln1 at home.rogerbinns.com>, Roger Binns wrote: > > > Ok, now add printing, drag and drop and comboboxes. > > No thanks. I don't do printing or drag and drop. Or > comboboxes now that I think about it. My needs are fairly > simple, and Tkinter would suffice nicely, except that the > non-native look and feel seems to confuse Windows users. Then use whatever suits you best! To a certain extent this is like the differences between accessing a file and just reading lines, then moving up to structuring the information in the file as CSV and finally a full fledged database. Code that works with one step gets increasingly difficult to work with the next step, unless you adopt a new library. The APIs will assume increasing knowledge, and may even require more code to use, but the capabilities available to you in other bits of code increase. > I know. I'm paying the price, I feel like I don't get any > benefits. It depends on what the future for your application is. My main application (bitpim) runs on Windows, Linux and Mac. It makes extensive use of threading, has custom controls, data manipulation, printing, HTML integration etc etc. Obviously getting the initial bit going took a little longer than Tkinter, but after the first week or so the other parts were a lot easier and I haven't had to say no to functionality (such as printing, drag & drop, HTML etc). > > That is news to this programmer who has been doing > > wxPython for 3 years! > > What are all the calls that look like parent.AddWindow(child,...)? Ah, that is to do with the layout hierarchy, which has nothing to do with the containment hierarchy. Most people just use the sizer.Add method which is polymorphic. BTW the layout hierarchy is optional - you can use absolute sizing and positioning of your controls if you want. (And that is normal for Windows apps - note how few dialog boxes you can resize! That is a consequence of layout management being a pain using the real Windows APIs.) > I don't think that's a good excuse for what appears (to me) to > be a fragile API. The purpose of an API is to hide how the > insides work. Yes, but at some point controls, events and functions acting on events have to be bound together, sometimes taking into account the class, containment or layout hierarchies. I'll admit that wxPython's isn't the most concise or most beautiful. But they do work. They have never been a hindrance on my productivity, and a suspect many other people's. But if you have a better way of expressing that, after you understand it all at a lower level then please propose it. (I can't really think of any). > > Generally the problem is that people don't understand that > > there are three seperate hierarchives when dealing with GUIs. > > There is the classes of the various controls, there is the > > instance hierarchy and there is the layout hierarchy. > > Thank you! > > Where do I find the documentation that explains things like > that? Teasing it out of people on Usenet is obviously a waste > of everybody's time. They are actually quite hard concepts to explain, and various tutorials, the online documentation and wikis do try to explain them. I don't think any of them do a particularly good job. However do feel free to write your own explanation and contribute it to the Wiki. > All I can find is documentaiton on the class hierarchy. I've > looked at demo source code, but am having a tough time figuring > out why things are written certain ways. You should post your questions on the wxpython-users mailing list. Almost all questions are answered very quickly. > Not being aware that > there are two separate hierachies involved where I'm used to > one, it looks like there's a lot of odd redundancy involved in > setting up things. There are arguments for and against combining the containment hierarchy and the layout hierarchy. For wxWidgets it is that the layout management is kept seperate from controls that draw themselves. This makes controls less complicated since they only have to worry about how to draw, and do not have to worry about arbitrarily complex child widgets to layout. Similarly layout management objects (aka sizers) only have to worry about layout, and not about drawing. I won't argue as to what is best, but do believe the wxWidgets approach is reasonable. > > Sometimes the warts > > of underneath show through, but if you used the actual > > underlying toolkit you would be exposed to them anyway. > > I guess those warts must be from some of the "underneaths" I've > never worked with. You should try the various native gui toolkits someday - stuff like win32, MFC, Xlib, Motif. wxWidgets/wxPython is an absolute joy compared to them. The real masochist can try MFC on PocketPC. The MFC source, the PocketPC documentation and what the code actually does frequently differ. > > The good news is that Python does make it easy to put wrappers > > around wrappers. Most wxPython programmers haven't felt it > > necessary, but if you do the groundwork is already laid. > > And I'm trying to find information to help me work on that. I would recommend you give wxPython 6 months even if it is hard. It is always better to more thoroughly understand something before wrapping it, or taking a different approach. >From my own experience, each time you try something new such as one of the more complicated controls, printing, drawing, clipboard, "virtual" data or writing your own control, then there is a little bit of a learning curve. In many cases the demo (which is often overlooked) helps tremendously, the documentation helps a little, and just sitting there and writing code brings about the final closure. But that always happens to some degree with any toolkit. The quality of the toolkit, the variety of widgets, and core functionality keep getting better. The cold hard reality is that using wxPython today means you can deliver an application that will run on a large variety of operating systems, screen sizes, characters sets and unicode, and work the way the user of the operating system expects (drag and drop, printing, clipboards, common dialogs etc). It costs you nothing, there is no vendor lock-in, and there is a lively community behind it. Suits me! Roger From greg at cosc.canterbury.ac.nz Thu May 6 02:12:18 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 06 May 2004 18:12:18 +1200 Subject: Unification of Methods and Functions In-Reply-To: <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> Message-ID: <c7cl05$pgnr$1@ID-169208.news.uni-berlin.de> David MacQuigg wrote: > Explanation of Instance Variables in Python > ------------------------------------------- > """ Some of the variables inside the functions in a class have a > self. prefix. This is to distinguish local variables in the function > from "instance variables". These instance variables will be found > when the function is called... Just because a particular writer uses more waffle than necessary to explain something about Python doesn't mean the thing being explained is complicated enough to require that many words. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mark at prothon.org Wed May 26 15:51:22 2004 From: mark at prothon.org (Mark Hahn) Date: Wed, 26 May 2004 12:51:22 -0700 Subject: Prothon should not borrow Python strings! References: <mailman.230.1085420869.6949.python-list@python.org><2hfv4nFch1lmU3@uni-berlin.de> <mailman.271.1085494900.6949.python-list@python.org><7xMsc.17901$bF3.7334@fed1read01> <mailman.308.1085568334.6949.python-list@python.org> Message-ID: <_y6tc.19496$bF3.13272@fed1read01> "Paul Prescod" <paul at prescod.net> wrote > > Paul et al: I have a number of wild ideas and questions about text and > > binary strings and also a few things to discuss about the long integers you > > brought up, but the Python list is not the proper place to drag these > > discussions out. > > > > Is there any chance I can get you (and hopefully others participating here) > > to join the prothon-user mailing list for a week or two to discuss these > > issues? The traffic is only one tenth the traffic here on c.l.p. so it > > won't be much burdon. Our discussions are interesting. (We have no pesky > > users yet :-) > > I'll join, but I don't know when I'll find time to contribute...long > weekend coming up etc. Mucho Thanks. Anyone else want to tag along? From rajorshi at fastmail.fm Thu May 20 06:59:08 2004 From: rajorshi at fastmail.fm (Rajorshi) Date: 20 May 2004 03:59:08 -0700 Subject: calling destructor in python multiply-inherited class Message-ID: <85b5e3f8.0405200259.468161f3@posting.google.com> Hi, I have two classes, say, Base1 and Base2. Now Derv is a class derived from both like class Derv(Base1,Base2)..... In the destructor of the derived class, if I write something like this def __del__(self): for b in self.__class__.__bases__: b.__del__(self) then its working fine, but if I am doing something straightforward like def __del__(self): Base1.__del__(self) Base2.__del__(self) Its giving an error like : Exception exceptions.AttributeError: "'NoneType' object has no attribute '__del__'" in <bound method Derv.__del__ of <__main__.Derv instance at 0x8187484>> ignored Obviously I'm doing something wrong ! Any pointers ?? Thanks in advance! From lbates at swamisoft.com Thu May 27 17:05:23 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 27 May 2004 16:05:23 -0500 Subject: remove item from list based on name References: <c95e2g$nm2$1@solaris.cc.vt.edu> <c95hr0$ein$03$1@news.t-online.com> <40B64C36.5030600@hotmail.com> Message-ID: <XIadnbGSp_GOxSvd4p2dnA@comcast.com> I'm glad they worked for you. I tend to stay away from V2.3 "only" solutions, but I guess it's probably time I started recommending using these new features. -Larry "Bart Nessux" <bart_nessux at hotmail.com> wrote in message news:40B64C36.5030600 at hotmail.com... > Thanks Peter & Larry, > > Both of the examples work (lists and sets). I had forgotten that I had > done something similar in the past with both functions. I find the set > approach cleaner, but both approaches get the job done. > > Thanks Again! > > > Peter Otten wrote: > > Bart Nessux wrote: > > > > > >>I am generating a list of file names... some of the files are locked by > >>the OS (Windows XP) and I know the names of these files (NTUSER.DAT, > >>ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is > >>there a way that I can delete these items from the list based on their > >>names? > > > > > >>>>from sets import Set > >>>>list(Set(["a", "b", "c"]) - Set(["c", "d"])) > > > > ['a', 'b'] > > > > Remember to pass all filenames through os.path.normcase() before trying the > > above. > > > > Peter > From greg at cosc.canterbury.ac.nz Sun May 23 22:28:28 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 14:28:28 +1200 Subject: Unification of Methods and Functions In-Reply-To: <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> References: <16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><slrnca6d58.1i9.apardon@trout.vub.ac.be><mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> Message-ID: <2hd4ufFbgv5oU1@uni-berlin.de> David MacQuigg wrote: > On Sat, 22 May 2004 12:10:51 -0600, "Dave Brueck" >>But the above explanation misses one very important point: one is used 99.9% of >>the time, the other 0.1% of the time, if that. > > I can't comment on the usage statistics you cite, but it seems to me > that unbound methods are more important than these statistics would > imply. ... Learning Python also treats unbound methods as > much more "normal" than your argument would imply. The only time you really need to deal with unbound methods is when making super calls, and that accounts for maybe 1% or less of all method calls in the code I write. I haven't seen what Learning Python says about unbound methods, but if it puts any more emphasis on them than this, it's putting too much emphasis on them. > Sure, we could move the load function > outside of the Bag class, but that would disrupt the natural structure > of the program. The load function is unique to Bags, and it belongs > in the Bag class. The Pythonic way to handle this is to create a module to hold the Bag class and any functions related to it, e.g. # module bags class Bag: ... def load(infile): ... # in some other module import bags my_bag = bags.load("my_settings.ini") > Seems like my challenging statement was misleading. I have no > intention of bringing up strange binding problems in an introductory > class. This was a challenge to those who think that Python's binding > syntax is simple. But seeing as your example did something you're not meant to be doing in the first place, I don't see how any conclusions can be drawn from it about simplicity or complexity in everyday programming. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mellis at frogwing.com Tue May 25 21:39:04 2004 From: mellis at frogwing.com (Michael Ellis) Date: 25 May 2004 18:39:04 -0700 Subject: Cleaner idiom for text processing? Message-ID: <f2403000.0405251739.2a77b11d@posting.google.com> Hi, I have some data files with lines in space-delimited <name> <value> format. There are multiple name-value pairs per line. Is there a cleaner idiom than the following for reading each line into an associative array for the purpose of accessing values by name? for line in infile: tokens = line.split() dict = {} for i in range(0, len(tokens),2) dict[tokens[i]] = tokens[i+1] do_something_with_values(dict['foo'],dict['bar']) Thanks! Mike Ellis From rogerb at rogerbinns.com Tue May 25 01:35:45 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 24 May 2004 22:35:45 -0700 Subject: GTK or TKinter (or what else?) References: <SxZqc.10613$Wc.388888@twister2.libero.it> <J5isc.8231$be.5948@newsread2.news.pas.earthlink.net> <2hfui1Fch1lmU2@uni-berlin.de> <40b2c965$0$8695$a18e6209@newsreader.visi.com> Message-ID: <bi2bo1-vkr.ln1@home.rogerbinns.com> Grant Edwards wrote: > Right now I'm using wax, (a wxWindows wrapper that hides some > of that sort of thing). In relation to an earlier thread, I took a look through my Qt book again, and noted that it does require passing in the parent when creating a widget (although it is passed as the last parameter which seems wrong to me) and the layout and containment hierarchies are also different. The '-1' issue can't really go away unless Python allowed default arguments in the middle of an argument list, which would probably be a bad thing. Roger From insert at spam.here Mon May 3 12:23:56 2004 From: insert at spam.here (Doug Holton) Date: Mon, 03 May 2004 11:23:56 -0500 Subject: PyOpenGL demo in wxPython demo crashes In-Reply-To: <5b-dnVJ33JJj_gvdRVn-hQ@powergate.ca> References: <c74oir$jkt$1@newshispeed.ch> <Xns94DE67D7BCE8Arzed@63.223.5.95> <0MudnVoTELDrxAvdRVn-gw@powergate.ca> <5b-dnVJ33JJj_gvdRVn-hQ@powergate.ca> Message-ID: <tfWdnSuobuqB7wvdRVn-uQ@comcast.com> Peter Hansen wrote: > > > Okay, in spite of installing everything that I should have, > I didn't have a glut32.dll on my machine. Google led me > to http://www.xmission.com/~nate/glut.html from where I > downloaded a copy, manually stuck it in c:\windows\system32, > and PyOpenGL works now. > > Now I see that this is on the pyopengl.sourceforge.net > installation notes page... I don't recall installing this > the same way last time, but there you go. Not only RTFM, > but go back and read it again another time if things still > don't work. Right, but this means anytime you want to distribute a program using pyopengl you have to tell your users to manually install glut32.dll also. pyopengl should run without requiring glut if you do not use the glut functions, or else it should include a copy of glut32.dll itself. From aahz at pythoncraft.com Sat May 15 09:24:39 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2004 09:24:39 -0400 Subject: RELEASED Python 2.3.4, release candidate 1 References: <mailman.513.1084456098.25742.python-list@python.org> <40a39511$0$560$e4fe514c@news.xs4all.nl> <c80800$ok9$1@panix1.panix.com> <40a60334$0$65124$e4fe514c@news.xs4all.nl> Message-ID: <c855mn$ca0$1@panix3.panix.com> In article <40a60334$0$65124$e4fe514c at news.xs4all.nl>, Irmen de Jong <irmen at -nospam-remove-this-xs4all.nl> wrote: >Aahz wrote: >>Irmen deleted his own attribution: >>> >>>SimpleHTTPServer reports a wrong content-length of text files on >>>windows The bug is still there in this release. Any change of getting >>>my patch applied? >> >> Not at this point, sorry. It's generally assumed that people who care >> about the progress of release schedules are subscribed to python-dev; >> perhaps that assumption should be challenged. > >Pardon my ignorance, but why is it that currently on python-dev there >are talks about including new modules into the standard lib for 2.4 >(such as cookielib), while relatively trivial patches to existing modules >are no longer taken into account for 2.4? 2.4 has plenty of time for patches to get accepted. There will be at least a month after the first published alpha before a release candidate gets created. I'm confused now because this thread has been about 2.3.4, which is a relatively low-effort bugfix release. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From rmb25612 at yahoo.com Sun May 9 12:18:41 2004 From: rmb25612 at yahoo.com (Richard James) Date: 9 May 2004 09:18:41 -0700 Subject: What I don't like about wxPython References: <ec6dce8b.0405081140.16b8143d@posting.google.com> <pan.2004.05.09.01.31.27.334940@sbcglobal.net> <Xns94E3E2829C3B9OKB@130.133.1.4> <c7kisp$n2s$1@atlantis.news.tpi.pl> Message-ID: <2c60f0e0.0405090818.78562d10@posting.google.com> Jarek Zgoda <jzgoda at gazeta.usun.pl> wrote in message news:<c7kisp$n2s$1 at atlantis.news.tpi.pl>... > OKB (not okblacke) <BrenBarn at aol.com> pisze: > > >> Ultimately, none of these ui api's are as 'pythonic' as I want them > >> to be, and wxPython in particular seems like a carbon copy of the C > >> api, which makes it lose points in my book. > > > > I agree with this; that API seems completely incongruous in a > > Python program. > > It has been told and written many times. If you look something "more > pythonic" yet still such powerful, you can use some wrapper on wxPython. > Wax first comes to my mind, look for it in PyPi. Also look at: wxGlade: http://wxglade.sourceforge.net/ Python Card: http://www.pythoncard.org/ They help by generating the "ugly" wxPython details for you... -- R.J. From nav+posts at bandersnatch.org Sun May 9 22:48:34 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 09 May 2004 22:48:34 -0400 Subject: Python job opening at GPO in Washington, DC References: <b16e4ef7.0403030957.21a0c216@posting.google.com> <m3pt9gmi0z.fsf@tanelorn.bandersnatch.org> <2g26l5F3ovo0U1@uni-berlin.de> Message-ID: <m3llk1m1z1.fsf@tanelorn.bandersnatch.org> William Park <opengeometry at yahoo.ca> writes: > Hmmm, you're trying to convince your boss to do with less budget. So, > he goes to his boss and says, "My IT budget was $10Million last year, > but just give me $1Million this year. I've got Python." I don't think > ANY government works this way. :-) Or any IT department, not just government, in any large organization. There's also fewer training courses to budget for, and fewer vendor-sponsored conferences to attend. Sure, we can only accept gifts under $30, but the competition is much fiercer since the stakes are so much smaller. Nonetheless, my boss is actually very interested in Python, because he's interested in building sustainable systems. He's spent enough time nursing along proprietary systems that have become both entrenched and orphaned that he's sick and tired of it. > What you should say is, "With Python (and Linux), we can outperform > other departments with only %10 of our current resource. Pretty soon, > we can take over their duties and their budgets. Our department will > grow 5 folds in 2 years." I've heard worse strategies. My immediate boss might be able to sell my efforts to _his_ boss with that kind of approach. 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 andy at andybak.net Mon May 24 08:55:57 2004 From: andy at andybak.net (Andy Baker) Date: Mon, 24 May 2004 13:55:57 +0100 Subject: MSIE6 Python Question In-Reply-To: <22b7fd40.0405240325.7b2b6376@posting.google.com> Message-ID: <mailman.104.1572213536.32708.python-list@python.org> The site might be checking your user-agent string. Urllib must allow you to choose what browser to identify itself as. Simply match the user-agent of known version of IE and see if that works. > -----Original Message----- > From: python-list-bounces+andy=andybak.net at python.org > [mailto:python-list-bounces+andy=andybak.net at python.org] On > Behalf Of Ralph A. Gable > Sent: 24 May 2004 12:25 > To: python-list at python.org > Subject: Re: MSIE6 Python Question > > "Kevin T. Ryan" <kevryan0701 at yahoo.com> wrote in message > news:<40b1697d$0$3131$61fed72c at news.rcn.com>... > > Ralph A. Gable wrote: > > > > > I'm a newbie at this but I need to control MSIE6 using Python. I > > > have read the O'Reilly win32 python books and got some > hints. But I > > > need to Navigate to a site (which I know how to do) and > then I need > > > to get at the source code for that site inside Python (as > when one > > > used the > > > View|Source drop down window). Can anyone point me to > some URLs that > > > would help out? Or just tell me how to do it? I would be very > > > grateful. > > > > I'm not sure why you need to go through IE, but maybe this will get > > you into the right direction: > > > > >>> import urllib > > >>> f = urllib.urlopen('http://www.python.org') > > >>> f.readline() > > '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n' > > >>> f.readline() > > ' "http://www.w3.org/TR/html4/loose.dtd" >\n' > > >>> > > > > You could do: > > for line in f: > > process(line) > > > > just like you can with a file. Check the urllib, urllib2, > and other > > related modules (maybe httplib). Hope that helps. > > > Sorry. I forgot to mention that I have tried that. The data I > want is being stripped out when I access the URL via urllib. > I CAN see the data when I go into IE and do view source but > when I use urllib the site intentionally blanks out the > information I want. For that reason, I would like to get it > using IE6 if I can. If there are other ways to fake out the > site, I would be interested in that also. I thought that > perhaps the site was detecting the fact that I was not > querying it using a browser. I tried putting that into into > the HTTP messages but may not have done it right. At any rate > couldn't get that to work. It may be that the site is using > cookies to be sure someone is not getting the data. I haven't > pursued that. Again that is another reason I wanted to use > IE6 (since I know it works). The data is on a site to which I > subscribe to a service. But the particular information is > available to anyone if he/she types in the url (as long as > you are using a browser). > -- > http://mail.python.org/mailman/listinfo/python-list > From gabriel.cooper at mediapulse.com Tue May 25 09:19:03 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 25 May 2004 09:19:03 -0400 Subject: Newbie question In-Reply-To: <c8vfn0+kpk0@eGroups.com> References: <c8vfn0+kpk0@eGroups.com> Message-ID: <40B347C7.7050401@mediapulse.com> mp312 wrote: >I have a script that I need to do the following: > >Taking a user id that is in the format 'userid at MACAddress', read the >userid portion (varying length) and concatenate with @honigman.com. > > > import string x = string.split('userid at macaddress','@')[0]+'@honigman.com' From SeeBelow at SeeBelow.Nut Tue May 4 22:11:28 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 05 May 2004 02:11:28 GMT Subject: question: parameters for create_polygon() method Message-ID: <40984D5A.B819BF28@shaw.ca> Tkinter's canvas object has the method create_polygon(). The docs say the parameters should be like: (x1, y1, x2, y2, x3, y3, .....) But it's often much better programming practice to have a list of tuples, each point being a tuple, like this: [(x1, y1), (x2, y2), (x3, y3),......] Is there a good way to manipulate my polygons in the latter form, but still use create_polygon() to draw them? Thanks, Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From davidf at sjsoft.com Mon May 31 13:04:21 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 31 May 2004 19:04:21 +0200 Subject: mod python confusion In-Reply-To: <153fa67.0405290250.5661432a@posting.google.com> References: <mailman.410.1085775210.6949.python-list@python.org> <153fa67.0405290250.5661432a@posting.google.com> Message-ID: <c9foib$1og$1@ctb-nnrp2.saix.net> Kylotan wrote: > "Robert Brewer" <fumanchu at amor.org> wrote in message > news:<mailman.410.1085775210.6949.python-list at python.org>... > > >>Given that webserver advocacy comes and goes, I always recommend >>abstracting the webserver interface, so rewrites like the one you're >>talking about hurt less: >> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/225299 > > > Hi Robert. You've recommended this recipe to me in the past when I asked > a similar question on this newsgroup. However, I must admit that I > really don't understand 90% of it, since there are so many layers of > abstraction and it spans several classes - and indeed, 2 recipes! > Surely there has to be something simpler? I read somewhere today that > mod_python made Python as simple to use for web apps as PHP etc, but if > this is any indication of the amount of code you need to simply redirect > execution to separate places based on the URI, then I'd have to disagree > with that! > Actually redirecting execution to separate places based on the URI is fairly easy in mod_python, I suspect you may want to use something like publisher From dmq at gain.com Thu May 20 14:49:16 2004 From: dmq at gain.com (David MacQuigg) Date: Thu, 20 May 2004 11:49:16 -0700 Subject: Unification of Methods and Functions References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> Message-ID: <uavpa017n6dpmlr9ib25rrj6mu423v6j0b@4ax.com> On 19 May 2004 22:27:05 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg <dmq at gain.com> wrote in message news:<47cna0d9cbkfr2vovdhs692cklnmu0oo6h at 4ax.com>... >> On 17 May 2004 20:11:44 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> >David MacQuigg <dmq at gain.com> wrote in message news:<4ka7a0t585802d81i417j5ufmrdjbq6hei at 4ax.com>... >> >> >> We need to make a distinction between users and programmers in our >> >> expectations of what kind of errors they will make. Users only need >> >> to *read* a class definition and understand what it does. Programmers >> >> are the group that needs to remember to add a call to the superclass >> >> when they write a new class. >> >> >> >> I am a user of the Qt Toolkit, but I would not attempt to add a class >> >> to their existing hierarchy. Nor would I expect Trolltech to provide >> >> me with some kind of robust class-generating function that was >> >> guaranteed to generate an error-free class at any point in their >> >> hierarchy I might chose to insert it. >> > >> >If you're writing code, you're writing it to be modified at some >> >point, unless it's a few lines-long script. If the modifications are >> >made by someone else then they will reasonably expect that the code >> >doesn't contain implicit deathtraps, like non-local data. >> >> The trade-off, in the case of _numAnimals is: Do we want a simple >> program with instant display of this number, or a more complex program >> that scans the entire hierarchy to re-create the total every time it >> is needed. >> >> There is an analogy in the netlisting programs used in circuit design. >> Netlisting a big design is a time-consuming operation, so each cell is >> netlisted when it is saved. When the design is simulated, there is a >> quick check of the time-stamps on the entire hierarchy, to make sure >> all of the incremental netlists are up-to-date. One could argue that >> somehow the time-stamps could get out-of-sync (incorrect clock setting >> on a client machine, etc.). Yet nobody says that not netlisting the >> entire design every time is bad programming. >> >> It's always a compromise. Robustness is never absolute. > >All true; there are certainly times when you need to store complex >calculations, otherwise we'd all be programming in Haskell. > >However, there are different ways to achieve the same result. Some >would be transparent and relatively easy to debug, like storing the >number at a container-instance level. The particular way it is done >in Animals_2 is, IMO, one of the less desirable alternatives, >especially as a pattern to teach students. I'm still waiting for that one simple example that you say will do it all, and do it right. -- Dave From me at privacy.net Fri May 7 04:21:29 2004 From: me at privacy.net (Duncan Booth) Date: 7 May 2004 08:21:29 GMT Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <lMWdncBA4LRcAgfd4p2dnA@comcast.com> Message-ID: <Xns94E25EB583B9Bduncanrcpcouk@127.0.0.1> "Larry Bates" <lbates at swamisoft.com> wrote in news:lMWdncBA4LRcAgfd4p2dnA at comcast.com: > I use: > > class foo: > _stringtype=type('') > _tupletype=type(()) > _listtype=type([]) You could just use the builtin names already supplied for these: str, tuple, and list have the same values you just assigned to _stringtype, _tupletype, and _listtype. Also, you forgot about unicode. > > def __init__(self, variable): > if type(variable) == _stringtype: > self.variable=variable # check for string type > if type(variable) in (_listtype, tupletype): > self.variable=str(variable) # check for list/tuple > . If anyone has been subclassing str, list or tuple this won't work. You may not subclass builtin types very often, but it doesn't really hurt to use isinstance instead. That's why it is better to write: if isinstance(variable, (str, unicode)): ... or: if isinstance(variable, basestring): ... as either of these will catch subclassing. From cookedm+news at physics.mcmaster.ca Thu May 13 17:08:41 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 13 May 2004 17:08:41 -0400 Subject: struct doesn't handle NaN values? References: <slrnca7k1l.an4.grante@grante.rivatek.com> Message-ID: <qnk7jvgujae.fsf@arbutus.physics.mcmaster.ca> At some point, Grant Edwards <grante at visi.com> wrote: > Perhaps I'm doing something wrong: the struct module docs say > it's IEE 754, but I can't figure out how to get it to handle > NaN values correctly (either packing or unpacking). > >>>> x = float('nan') >>>> struct.pack("<f",x) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > SystemError: frexp() result out of range Doing this with the native format is no trouble: >>> struct.pack('f', x) '\x00\x00\xc0\x7f' ...which is a NaN since the exponent part is all 1's and the significand is non-zero. >>>> struct.unpack("<f",'\xff\xff\xff\xff') > (-6.8056469327705772e+38,) Again, >>> struct.unpack('f', '\xff\xff\xff\xff') (nan,) Of course, if you want to worry about endian issues here, I think you're SOL with using struct. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From asdf at asdf.com Fri May 21 18:49:45 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 21 May 2004 22:49:45 GMT Subject: anyone using moinmoin on win2k? Message-ID: <dIvrc.52075$1G2.10483@newssvr29.news.prodigy.com> i have an install issue with moinmoin on win2k. i've tried the mailing list, but it appears to be a very low traffic, low subscriber list. can i get a reality check? is anyone using moinmoin in win2k? any issues? anyone at all? From insert at spam.here Wed May 26 19:48:21 2004 From: insert at spam.here (Doug Holton) Date: Wed, 26 May 2004 18:48:21 -0500 Subject: python programming on win32 ? Hammond book In-Reply-To: <7L9tc.57314$343.13837@newssvr29.news.prodigy.com> References: <7L9tc.57314$343.13837@newssvr29.news.prodigy.com> Message-ID: <v4WdnXO5Ca1bsSjdRVn_iw@comcast.com> asdf sdf wrote: > i'm interested in using python for win32 COM automation and sysadmin > scripts. > > many recommendations for Mark Hammond's Python Programming on Win32. > > but it was published four and half years ago. i have misgivings about > buying a book so old. COM programming hasn't changed much but Python > has. (VB and Delphi have changed quite a bit, and apparently they are > discussed also.) > > I could just download the code samples and scavenge the web as best as i > can. > > buy recommendations from anyone? any better alternatives out there? It's still a good book to buy for your purposes. And see http://www.python.org/windows/ for some online resources. But some new Python things not covered in the book include ctypes (alternative to dynwin), Pyrex (alternative to SWIG), the newer wxPython (see demos), and py2exe. From jcarlson at uci.edu Wed May 19 16:19:53 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 19 May 2004 13:19:53 -0700 Subject: Printing formatted strings from a dictionary In-Reply-To: <21064255.0405131144.160af9a8@posting.google.com> References: <b4a8ffb6.0405121230.a564636@posting.google.com> <m3r7toh75g.fsf@pc150.maths.bris.ac.uk> <21064255.0405131144.160af9a8@posting.google.com> Message-ID: <c8gfov$9j9$1@news.service.uci.edu> [snip good reply from Peter] The other thing to remember is that there are implicit quotes: >>> d = {1:2} >>> "%(1)i"%d Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 1 >>> "%(1)i"%d '2' - Josiah From eriksp at attbi.nospam.com Wed May 26 18:37:17 2004 From: eriksp at attbi.nospam.com (EAS) Date: Wed, 26 May 2004 22:37:17 GMT Subject: Current drive and directory References: <LP7tc.64476$gr.6380832@attbi_s52> <mailman.341.1085607489.6949.python-list@python.org> Message-ID: <x_8tc.29053$af3.1599546@attbi_s51> Ok, I guess that won't work without some complicated scripting, but is there a command in DOS that shows the current directory? (so i could just type it in when using the prompt.) From kveretennicov at yahoo.com Mon May 24 10:35:02 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 24 May 2004 07:35:02 -0700 Subject: r'\' - python parser bug? Message-ID: <5155aad2.0405240635.6c2915a5@posting.google.com> Hi, recently i tried this: ActivePython 2.3.2 Build 232 >>> '\\' '\\' >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning single-quoted string Is this a known issue? Should i submit a bug report to development? - kv From max at alcyone.com Fri May 7 00:18:15 2004 From: max at alcyone.com (Erik Max Francis) Date: Thu, 06 May 2004 21:18:15 -0700 Subject: VPython and 3D Visualization References: <mailman.335.1083899142.25742.python-list@python.org> Message-ID: <409B0E07.2168A2CD@alcyone.com> > "Joel C. Alcarez" wrote: > My employer Mapua (http://www.mapua.edu.ph/) has decided to support > my work and send me (Joel Alcarez) and my collaborator Prof. Joyrence > Agas to Ateneo de Davao to demonstrate the software developed using > Python and VPython to a very receptive audience composed of > distinguished Physics professors from all over the country. Congratulations! -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ To know oneself, one should assert oneself. -- Albert Camus From kirk at eyegor.jobsluder.net Tue May 11 09:12:23 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Tue, 11 May 2004 13:12:23 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> Message-ID: <slrnca1kaq.1rer.kirk@eyegor.jobsluder.net> On 2004-05-11, Daniel 'Dang' Griffith <noemail at noemail4u.com> wrote: > There's definitely a sed available, possibly even in MingW (I have it > on my system, but am not sure if it arrived with MingW or something > else I installed). It's definitely available with cygwin. One reason > to install it is that it's smaller than perl or python; another is > that it probably performs the task faster, since it isn't a general > purpose state machine; another is that it's 25% shorter to type than > perl and 50% shorter to type than python. There is also a windows-native ssed (super sed). > --dang From peter at engcorp.com Sun May 2 16:36:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 May 2004 16:36:43 -0400 Subject: Efficient string concatenation methods In-Reply-To: <b3a34c4c.0405020954.53f997c2@posting.google.com> References: <b3a34c4c.0405011643.70c163c3@posting.google.com> <s8OdnbvjBMT-ygndRVn-iQ@powergate.ca> <b3a34c4c.0405020954.53f997c2@posting.google.com> Message-ID: <lsmdnXXkzI38xgjdRVn-vw@powergate.ca> Oliver Crow wrote: > Peter Hansen <peter at engcorp.com> wrote in message news:<s8OdnbvjBMT-ygndRVn-iQ at powergate.ca>... > >>You left out the StringIO module (having done only the cStringIO >>version of that). > > I should probably add that one just for reference. I left it out > originally because my instinct was that it would perform less well > than the string += operator. I think it uses ordinary immutable > python strings for internal storage. Actually (I just checked the source) it uses a list, more like example 4, but with some automated joining to the string form at different times, depending on what's going on with reads() and seeks() and such. I didn't bother trying to understand it all, just to verify that it actually uses lists too. -Peter From greg at cosc.canterbury.ac.nz Wed May 19 21:32:14 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 20 May 2004 13:32:14 +1200 Subject: Unification of Methods and Functions In-Reply-To: <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> References: <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> Message-ID: <2h2g50F87lb9U1@uni-berlin.de> David MacQuigg wrote: > There is an analogy in the netlisting programs used in circuit design. > Netlisting a big design is a time-consuming operation, so each cell is > netlisted when it is saved. When the design is simulated, there is a > quick check of the time-stamps on the entire hierarchy, to make sure > all of the incremental netlists are up-to-date. This is a form of cacheing, which is a well-proven technique. But it's an optimisation, and as such it should be the last thing added to a design, and then only when it becomes necessary. Also, there's a difference between cacheing and maintaining redundant data representations. With a cache, if in doubt you can always throw away the cache and re-calculate. But if your design relies on incrementally keeping parallel data structures up to date, if anything gets out of whack, you're hosed, because you don't have the ability to re-calculate the redundant data from scratch. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mark at prothon.org Tue May 25 00:02:12 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 21:02:12 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> <2hd3t4Fbk8gkU2@uni-berlin.de> <1qv4b09f8sp8rtfcb0fai7u4gdecaj0as8@4ax.com> <2hftoaFch1lmU1@uni-berlin.de> Message-ID: <uwzsc.16903$bF3.16590@fed1read01> Greg Ewing wrote: > David MacQuigg wrote: >> The load method is unique to Bags, and it belongs >> in the Bag class. To me this is a more fundamental consideration >> than whether or not the method uses instance variables. > > Giving the function a name such as load_bag would be > just as good in my opinion, if you don't want to dedicate > a whole module to the Bag class. > > But then again, I don't see that dedicating a module > to it would be such a bad thing, either. > > Python has what is termed a "package", which is > a module containing other modules. You can use a > package to group together modules which encapsulate > related classes. If you have various collection > classes, e.g., you might have a hierarchy of names > like > > collections.bags.Bag # class > collections.bags.load # function > collections.sets.Set > collections.sets.load > > etc. > > By the way, when I start writing a new Python program, > often I'm tempted to put several classes in a module, only > to regret it later as those classes grow and I end up > with a huge source file that's hard to navigate around > in. I'm coming to the view that it may be better to > plan on one-class-per-module from the beginning. From fishboy at spamspamspam.com Mon May 31 04:43:34 2004 From: fishboy at spamspamspam.com (fishboy) Date: Mon, 31 May 2004 08:43:34 GMT Subject: NNTP binary attachment downloader with asyncore and generators Message-ID: <ceqlb0l7o4ngf3q0si1m6prp44smr9m05r@4ax.com> Howdy, I'm in middle of a personal project. Eventually it will download multipart binary attachments and look for missing parts on other servers. And so far I've got it to walk a newsgroup and download and decode single part binaries. I thought I'd post the code and see what people think. I'd appreciate any feedback. It's my first program with generators and I'm worried I'm making this twice and hard as it needs to be. Thanks, David Fisher Oh yeah, email is fake since I'm deathly afraid of spam. Please post replies here. Code was working when I posted it. Just change the server name, username, password, group info at the bottom to something less virtual. :) #!/usr/bin/env python2.3 # import asyncore import socket import os import uu import email # class Newser(asyncore.dispatcher): def __init__(self, host,port,user,password,group): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect( (host,port) ) self.buffer = '' self.user = user self.password = password self.group = group self.n = 0 self.head = '' self.body = '' self.inbuffer = '' self.dataline = '' self.handleline = self.handleline_gen() def handle_connect(self): pass def handle_close(self): pass def writable(self): return (len(self.buffer) > 0) def handle_write(self): print 'sending: ' + self.buffer.strip() sent = self.send(self.buffer) self.buffer = self.buffer[sent:] if self.buffer: print 'didnt send whole line' #does this ever happen? print 'didnt send whole line' #just getting my attention print 'didnt send whole line' #in case it does def handle_read(self): self.inbuffer += self.recv(8192) while 1: n = self.inbuffer.find('\r\n') if n > -1: self.dataline = self.inbuffer[:n+2] self.inbuffer = self.inbuffer[n+2:] try: result = self.handleline.next() if result == 'OK': pass # everything is groovy elif result == 'DONE': self.del_channel() # group walk is finished break else: print 'something has gone wrong!' print result print self.dataline self.del_channel() break except StopIteration: print 'should never be here' print 'why did my generator run out?' print 'why god? why?!' print self.dataline self.del_channel() break else: break def handleline_gen(self): # # handshakey stuff # welcome username password group # after this is set we'll start the message walk # if self.dataline[:3] == '200': # welcome, post ok print self.dataline.strip() self.buffer = 'authinfo user ' + self.user + '\r\n' yield 'OK' else: yield 'WTF?! fail welcome? god hates me!' # if self.dataline[:3] == '381': # more auth needed print self.dataline.strip() self.buffer = 'authinfo pass ' + self.password + '\r\n' yield 'OK' else: yield 'WTF?! fail authinfo user' # if self.dataline[:3] == '281': # auth ok, go to town! print self.dataline.strip() self.buffer = 'group ' + self.group + '\r\n' yield 'OK' else: yield 'WTF?! fail authinfo pass' # if self.dataline[:3] == '211': # group print self.dataline.strip() self.buffer = 'next\r\n' yield 'OK' else: yield 'WTF?! fail group' # # main state loop # walk from one message to the next # issuing HEAD and BODY for each # never reenter here after we receive '421', no next article # so we should never issue StopIterator # while 1: # if self.dataline[:3] == '223': # next print self.dataline.strip() self.buffer = 'head\r\n' yield 'OK' elif self.dataline[:3] == '421': # err, no next article yield 'DONE' else: yield 'WTF?! fail next' # if self.dataline[:3] == '221': # head print self.dataline.strip() self.head = '' yield 'OK' # XXX what am I going to do if the server explodes while self.dataline <> '.\r\n': self.head += self.dataline yield 'OK' # XXX parse headers here # XXX decide whether we want body self.buffer = 'body\r\n' yield 'OK' else: yield 'WTF?! fail head' # if self.dataline[:3] == '222': # body print self.dataline.strip() self.body = '' yield 'OK' # XXX what am I going to do if the server explodes while self.dataline <> '.\r\n': # XXX line-by-line decode here (someday) self.body += self.dataline yield 'OK' self.decode() self.buffer = 'next\r\n' yield 'OK' else: yield 'WTF?! fail body' def decode(self): """decode message body. try UU first, just decode body then mime, decode head+body save in tempfile if fail""" tempname = 'temp' + `self.n` + '.txt' self.n += 1 file(tempname,'wb').write(self.body) f = file(tempname) try: uu.decode(f) except Exception,v: print 'uu failed code: ',v print 'trying MIME' file(tempname,'wb').write(self.head+self.body) f = file(tempname) message = email.message_from_file(f) for part in message.walk(): print part.get_content_type() filename = part.get_filename() if filename: if not os.path.isfile(filename): file(filename,'wb').write(part.get_payload(decode=True)) print 'yay! MIME!' os.remove(tempname) else: print "oops, we've already got one" else: print 'yay! UU!' os.remove(tempname) def main(): mynews = Newser('news.server',119,'fishboy','pass','alt.binaries') try: asyncore.loop() except KeyboardInterrupt: mynews.del_channel() print 'yay! I quit!' if __name__ == '__main__': main() From heikowu at ceosg.de Mon May 3 20:48:40 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 4 May 2004 02:48:40 +0200 Subject: Strategies for backwards compatibility when using pickle? In-Reply-To: <001401c4315f$c9632a70$9601a8c0@rimmer> References: <001401c4315f$c9632a70$9601a8c0@rimmer> Message-ID: <200405040248.41009.heikowu@ceosg.de> Am Dienstag, 4. Mai 2004 00:41 schrieb duncan: > Does anyone have any advice on how to balance the conflicting interests > of the developers who want to keep evolving the object model and users > who need stable project persistance? I've written a serialization library which may be of use here. What this library does is enable you to store class instances (and inheritance trees) with userdefined __store__ and __load__ functions, which use a dict (which is further serialized) to store the data to the stream and back. It doesn't naively only call the topmost class (like Pickle does with __getstate__ and __setstate__), but rather allows each base of the serialized class to store itself. A toplevel class can even deny being serialized, this means that the pickled data will be the immediate base of this class. If that class denies to serialize itself, the immediate base of that class will be serialized, etc. Another aspect is the fact that the serialized data doesn't contain the name of the class, rather it contains a reference to a registered name (such as MyLocalHostClass), which is looked up on unserialization. This mechanism is completely transparent, but allows you to pickle data for another program which may use different class names but implements the same interfaces. This library offers several other gimmicks (it was actually designed to implement a secure Pickle which can be used over a network without fear of attacks involving unserializing classes which are not explicitly decreed as being unserializable), such as signing of portions of the data with a key (requires PyCrypto), and automated type-checking for the dictionary of data which is passed to __load__. For storing basic types and recursive structures, it can do all that Pickle can, excepting the following construction (which can be serialized, but gets unserialized wrong, but without error): x = {} y = (x,) x["hello"] = y serialize(y) If you're interested, I can send you the library, along with several example files showing how to implement user classes which correctly operate with this library. Heiko. From irmen at -nospam-remove-this-xs4all.nl Thu May 20 06:29:44 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 May 2004 12:29:44 +0200 Subject: ANN: uid.py 1.0.2 -- Configurable unique ID generation In-Reply-To: <40AC1487.EA453C74@alcyone.com> References: <40AC1487.EA453C74@alcyone.com> Message-ID: <40ac8896$0$40878$e4fe514c@news.xs4all.nl> Erik Max Francis wrote: > Summary > > Configurable unique ID generation. [...] > Requirements > > uid.py is intended to be used under UNIX and UNIX-like systems in > Python 2.x. It's not too hard to make it work on win32, although you'd probably best off to use import pywintypes; return pywintypes.CreateGuid() on win32... 158c158,159 < self.set('uname', string.join(os.uname(), ':')) --- > if sys.platform!="win32": > self.set('uname', string.join(os.uname(), ':')) 165,169c166,173 < self.set('login', os.getlogin()) < self.set('uid', os.getuid()) < self.set('gid', os.getgid()) < self.set('euid', os.geteuid()) < self.set('egid', os.getegid()) --- > if sys.platform=="win32": > self.set('login', os.environ["USERNAME"]) > else: > self.set('login', os.getlogin()) > self.set('uid', os.getuid()) > self.set('gid', os.getgid()) > self.set('euid', os.geteuid()) > self.set('egid', os.getegid()) 177c181,182 < self.set('termid', os.ctermid()) --- > if sys.platform!="win32": > self.set('termid', os.ctermid()) 183,184c188,190 < self.set('pgrp', os.getpgrp()) < self.set('ppid', os.getppid()) --- > if sys.platform!="win32": > self.set('pgrp', os.getpgrp()) > self.set('ppid', os.getppid()) --Irmen From remi at cherrypy.org Fri May 7 05:02:52 2004 From: remi at cherrypy.org (Remi Delon) Date: 7 May 2004 02:02:52 -0700 Subject: Web programming ... References: <c7b2er$1q2uv$1@ID-205437.news.uni-berlin.de> <mailman.316.1083854283.25742.python-list@python.org> Message-ID: <585c0de9.0405070102.47a481a5@posting.google.com> > If you're interested in CherryPy, you might as well have a look at CheesyPy > (http://sourceforge.net/projects/CheesyPy). Somewhat similar to CherryPy, but > different (and IMHO cleaner, but who am I to say? I developed it ;)) > implementation of the OO-framework on top of the base Web-Server. > > CheesyPy is in no way finished yet (not even documented well enough, but > browse the source luke!), but the lower-level code which is demonstrated in a > simple sample application at the root of the package works out of the box > already. > > The main difference between CherryPy and CheesyPy is the fact that CheesyPy > doesn't use a precompiler I'd like add a few comments about this: - "Cleanliness": I won't comment on the cleanliness of the "implementation" of the tools themselves because I don't think it is very relevant. What really matters is the cleanliness of the code that users write with the tools (for their web applications). Some tools will naturally encourage cleaner code than others, just like python naturally encourages cleaner code than other languages (who said "Perl" :-)). In that area, I think that CherryPy has managed to keep python's qualities. Even though it adds another layer on top of python, developping a web app with it still very much like writing regular python code and it still encourages clean code: users almost never have to write extra lines of code that don't have anything to do with the problem they're trying to solve but that are needed because of the tool itself. Also, people usually misunderstand the following two points about CherryPy: - "Text generation": I see 3 common ways of dynamically generating HTML (or any other type of text). Let's say we have a variable called "name" that contains "world". The 3 common ways are: (1) Embedding HTML in python: return "<html><body>Hello, %s</body></html" % name (2) Embedding python in HTML (templating language): <html><body>Hello, $name$</body></html> (or some other notation depending on the templating language). I would also put things like XSLT in that category. (3) The "programmatic" approach: return HTML(BODY("Hello, %s" % world)) (or some other notation) CherryPy doesn't force you to use one approach or the other because for each page (or even each bit of text) you can use whatever approach you prefer. If you want to use a templating language, CherryPy comes with a default one but you can also use another one if you want (some people use Cheetah). I usually prefer approach (1) if the page has lots of dynamic data and little static date, and approach (2) if the page has lots of static data and little dynamic data. - The "compiler" effect: A lot of people are initially put off by the fact that developing a site in CherryPy requires a compilation step (it feels like going back to the "C" age, doesn't it :-). Well, in practice, this is never a problem ... The compilation step is really fast (even for big sites) and I just have a 2-line script that compiles the site and starts it ... This compiler approach does have some benefits (otherwise it wouldn't be there :-): Of course, speed is one of them, but also, several popular CherryPy features (like aspects) couldn't be easily implemented without this approach. Remi. From theller at python.net Tue May 25 15:19:29 2004 From: theller at python.net (Thomas Heller) Date: Tue, 25 May 2004 21:19:29 +0200 Subject: py2exe setup script problem References: <2hchapFbelulU1@uni-berlin.de> <aYCdnUwEboNTiy_dRVn-vA@comcast.com> <2heo0tFbiqgvU1@uni-berlin.de> Message-ID: <brkce2m6.fsf@python.net> >> What do you expect to happen? If program creates >> output, you need a console window to display it >> (unless you use GUI interface). Without console >> output has no where to go. I actually use this >> to my advantage on some lights-out applications >> that write all their output to log files. > > I _do_ use a GUI interface. Let me be more precise as I obviously > failed to clear up some things. > > If I use the console = [] attribute, the console window is created and > the GUI is started as intended, just as when I execute the .py-File. > > However, using windows = [], doesn't show any signs of a running > programm other than the process running in the task-list which I have > to shut down manually. There's a bug when using windows=[] which may be triggered when you don't have an import sys in your main script. Reading the py2exe/boot_common.py file might give you a hint. If you can, please get the py2exe CVS version and try with this. Thomas From max at alcyone.com Mon May 24 04:41:22 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 01:41:22 -0700 Subject: iterator expression - please explain References: <2hdobkFbkjkoU1@uni-berlin.de> <40B1ABFB.B6F854BA@alcyone.com> <40B1B297.6040802@igpm.rwth-aachen.de> Message-ID: <40B1B532.D236209B@alcyone.com> Helmut Jarausch wrote: > Many thanks for pointing out that silly mistake. > But why isn't it legal? It's not legal because you typed it in, rather than cutting and pasting it. You meant: myfun([x**2 for x in xrange(10)]) -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Chastity the most unnatural of the sexual perversions. -- Aldous Huxley From vincent.salaun at zslide.com Thu May 27 11:59:23 2004 From: vincent.salaun at zslide.com (vincent Salaun) Date: Thu, 27 May 2004 17:59:23 +0200 Subject: [newbie] conditional imports In-Reply-To: <kUntc.23302$Wc.808218@twister2.libero.it> References: <mailman.361.1085666071.6949.python-list@python.org> <kUntc.23302$Wc.808218@twister2.libero.it> Message-ID: <40B6105B.9020504@zslide.com> waouh, i wasn't expected so much answers, thanks a lot everyone ! this will help me, for sure ! I think i will try Peter Otten' solution, which is what i beginned to do. I didn't think about using import exceptions, i think it's a good & simple way (in this specific case) to know from where the module is used ... thx again ! vince From michael at stroeder.com Wed May 19 07:43:57 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 19 May 2004 13:43:57 +0200 Subject: Manipulate Windows SAM Message-ID: <tstrn1-km8.ln1@nb2.stroeder.com> HI! Does anybody know some ressource (docs or samples) about how to add/remove users in the Windows SAM with Python and win32 extensions? I'd eventually also like to try out ADSI programming with Python/win32. Thanks in advance. Ciao, Michael. From just at xs4all.nl Fri May 14 10:08:40 2004 From: just at xs4all.nl (Just) Date: Fri, 14 May 2004 16:08:40 +0200 Subject: Stackless python and microthreads References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <just-AEC793.15303514052004@news1.news.xs4all.nl> <2gk1k2F3li0jU1@uni-berlin.de> Message-ID: <just-0A0302.16084014052004@news1.news.xs4all.nl> In article <2gk1k2F3li0jU1 at uni-berlin.de>, Michael Walter <cm at leetspeak.org> wrote: > Just wrote: > > In article <2gjokgF3mvvdU1 at uni-berlin.de>, > > Michael Walter <cm at leetspeak.org> wrote: > >>Would you have an idea on how a higher-level replacement for > >>continuations in web application development? I'm excited (and _not_ > >>being any sarcastic or stuff, honestely!). > > > > Co-routines. > Would you care to elaborate? Can you store the state of a coroutine and > resume it multiple times? You can resume a co-routine multiple times just like you can resume generators mutliple times, but that's something completely different from restarting a continuation multiple times. When you mentioned continuations for web programming, I assumed you meant their ability to turn flow control inside out (allowing to write event-based networking code in a more natural way). Co-routines are a much nicer abstraction for that than continuations. Just From tjreedy at udel.edu Sun May 23 04:27:40 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 May 2004 04:27:40 -0400 Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il><mailman.155.1085166502.6949.python-list@python.org> <c8o9vo$las$1@news.iucc.ac.il> Message-ID: <c8pn9u$t13$1@sea.gmane.org> "Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message news:c8o9vo$las$1 at news.iucc.ac.il... > contradicts your assumption that only 50 other people would like it. I > don't see what brings you to think that you represent 99.99 percent of > Python users. Projecting thoughts into my brain that I never had is stupid. I really don't like that. > Perhaps *you* could have been a bit more open to hear them... Making false ad hominen comments is stupid. I don't like that either. I an disappointed. Sorry I took your request for comments *on the proposal* seriously. Terry J. Reedy From snrkiwi-lists at yahoo.com Thu May 13 15:20:05 2004 From: snrkiwi-lists at yahoo.com (snrkiwi-lists) Date: Thu, 13 May 2004 15:20:05 -0400 Subject: Real-time graphs In-Reply-To: <283adf56.0405131039.10801c77@posting.google.com> References: <mailman.463.1084375754.25742.python-list@python.org> <40a35edb$0$16606$5a62ac22@freenews.iinet.net.au> <283adf56.0405131039.10801c77@posting.google.com> Message-ID: <8A535151-A512-11D8-B27E-000A95AA5CB4@yahoo.com> Thanks for the info, all. It is certainly helping! Collating it all, and given our current setup and requirements (not web based, no Java, wxPython, lots of real time graphs per screen, Mac OS X and Linux), it seems only a couple of possibilities stand out. - VPython - matplotlib Having said that, neither of these appeared to come with examples with wxPython, but I guess you can't ask for everything! :-) Does anyone have any direct experience with either of these inside of wxPython? It appears that matplotlib will directly work with wxPython, not so for VPython? If we were using Tkinter, we might have other options apparently. I also have noticed a couple of other packages that no-one noted here - DISLIN - pgplot Does anyone have any experience with these in a wxPython setting? TIA From moughanj at tcd.ie Mon May 10 19:53:06 2004 From: moughanj at tcd.ie (James Moughan) Date: 10 May 2004 16:53:06 -0700 Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405060737.bd43802@posting.google.com> <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> Message-ID: <16752bcc.0405101553.785638fd@posting.google.com> David MacQuigg <dmq at gain.com> wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... > On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: > > >David MacQuigg <dmq at gain.com> wrote in message news:<4a9o90pbu122npgf4m2hrgg04g2j0ic6ka at 4ax.com>... > >> On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: > <snip> > >> Also, if you are calling > >> a function that has an instance variable ( .length ) and no instance > >> has been set by a prior binding, you would need to set __self__ > >> manually. > >> __self__ = foo; print FooLen() > > > >???!!!??? > > > >This is what I was talking about in my first post, global variables > >which change depending on where you are in the code... as I understand > >what you're saying, __self__ will have to be set, then reset when a > >method is called from within a method and the exits. And __self__ > >could presumably be changed halfway through a method, too. I'm sorry, > >I don't see this as being more explicit or simpler. > > The setting of __self__ happens automatically, just like the setting > of the first argument in a call from an instance. The user doesn't > have to worry about it. Explicit is better than implicit, especially in getting people to understand things. :) > In fact, I can't think of a circumstance > where the user would need to explicitly set __self__. Maybe some > diagnostic code, in which case having available a system variable like > __self__ is a plus. You can, without any loss of functionality in a > normal program, never mention __self__ in an introductory course. The > user doesn't need to know what it is called. > I can think of a time where I'd both want to do it and couldn't; may(str.strip, list_of_str) See what I mean about it breaking the funtional side of things? Without some definition about what's a static method the interpreter can't resolve things like this. In practice, map and a whole bunch of functions would have to be modified to explicitly set __self__. An implicit self is what leads to the whole mem_fun(&std::vector<int>::push_back) (or whatever the exact syntax is, it's too unusable to bother learning) in c++. > My preference is to give it a name and highlight it with double > underscores. To me that makes the discussion more concrete and > explicit, and builds on concepts already understood. Don't forget, > the students already understand global variables at this point in the > course. The "magic" of setting a particular global variable to an > instance is about the same as the magic of inserting that instance as > a first argument in a function call. The problem in either syntax is > not the magic of setting 'self' or '__self__'. > > <snip> > >> >A method in a class in Python is just like a global function; for a > >> >global function to operate on an object, it must take it as an > >> >argument. The prototype syntax would appear to break the above > >> >example. > >> > >> Global functions have no instance variables, so there is no need for a > >> special first argument. A Python method requires a special first > >> argument (even if it is not used). > > > >But the first argument isn't terribly 'special'; it tells the method > >what it's working on, just like any other argument. It's only > >'special' characteristic is that there's some syntactic sugar to > >convert foo.getLength() into Foo.getLength(foo). > > The specialness of the first argument isn't much, I agree, but it is > enough to make the calling sequence different from a normal function > or a static method. It is these differences that the new syntax gets > rid of, thereby enabling the unification of all methods and functions, > and simplifying the presentation of OOP. Methods in the new syntax > are identical to functions (which the students already understand), > except for the presence of instance variables. > > Instance variables are the one fundamental difference between > functions and methods, and one that we wish to focus our entire > attention on in the presentation. Except that that distinction doesn't exist in Python, since calling an instance variable is an explicit call to a member of an instance. If you are trying to focus your presentation on something which doesn't exist in Python then things are naturally going to be awkward. I would suggest that it's not a problem with the language, though. :) > Any new and unnecessary syntactic > clutter is a distraction, particularly if the new syntax is used in > some cases (normal methods) but not others (static methods). > If you really want to get something like this accepted then the closest thing which *might* have a chance would be to redefine the calling sequence of some_class.method() so that it doesn't seek a self argument so long as ``method'' was defined without one. I don't think this would break anyone's code (I may well be wrong of course) since the sequence isn't currently valid in execution (though IIRC it will compile to bytecode). This makes the distinction between static and normal methods about as simple as it can be; methods are just class methods which operate on an instance. You can show how it works in a few lines of an example (though, currently, it should only take a few more.) > > > >Mammal.show() shows characteristics to do with Mammals, *but not > >specifically Mammal*. There really is a difference between a class > >and it's subclasses. > > The Mammal.show() function *is* specific to Mammal. I think what you > are saying is that calling Mammal.show() results in a display of > characteristics of both Mammal and its ancestor Animal. No, it's not. Let me try to be totally clear here; The numMammals data member contains data not just about Mammal, but also about instances of it's subclasses. This is the problem. The fact that it's accessed through the show method is really just a detail, though the presence of of show in other subclasses compounds the problem. >That is a > requirement of the problem we are solving, not a result of bad > programming. We want to see *all* the characteristics of Mammal, > including those it inherited from Animal. > You are not solving a problem; that's the problem. :) If there were a real programming task then it would be more trivial to show why your object model is broken. > Leave out the call to Animal.show() if you don't want to also see the > ancestor's data. > > >The general-purpose inventory solution would be a better solution. It > >doesn't require repetition, it's hard (impossible?) to break and it's > >generic, allowing it to be used beyond this single class heirarchy. > > > >If the inventory function would be best placed outside a class, why do > >you think it's a good idea to put something with exactly the same > >functionality inside your classes? > > The proposed Inventory() function is a general function that *would* > be appropriate outside a class. The exising class-specific functions > like Mammal.show() are unique to each class. I tried to make that > clear in a short example by giving each data item a different text > label. I've now added some unique data to the example just so we can > get past this stumbling block. A real program would have a multi-line > display for each class, and there would be *no way* you could come up > with some general function to produce that display for any class. > > > > >Books are always kind of strange, because a book must have a certain > >number of pages and cover a certain range of content at a certain > >technical level. For the level and range of the ORA Learning books, > >that is going to mean a bit of padding for a simple language like > >Python. If I see Learning Python in a bookshop then I'll take a look, > >though. > > > >Regardless, I stand by what I said before - students generally will > >not read 70 pages on a single topic, especially when it's a relatively > >minor part of the course. > > Learning Python, 2nd ed. would be appropriate for a one-semester > course. My problem is that I have only a fraction of a semester in a > circuit-design course. So I don't cover OOP at all. I would include > OOP if I could do it with four more hours. Currently Python is a > little over the top. I don't think it is a problem with Lutz's book. > He covers what he needs to, and at an appropriate pace. > If you can't take it below 70 pages and you only have 4 hours... maybe it's not such a great idea to try this? I can't see your students benefiting from what you're proposing to do, if you have so little time. > >> >Learning to program is about 5% how to do something, and 95% when and > >> >why you should do it. You seem to be focusing almost exclusively on > >> >how, which I suspect is why we're all so upset :) you get that way > >> >when you have to fix the code which eventually results. > >> > >> The OOP presentations I've seen that focus as much as 50% on *why* > >> generally leave me bored and frustrated. I feel like screaming -- > >> Stop talking about car parts and show me some nice code examples. If > >> it's useful, I'm motivated. Good style is a separate issue, also best > >> taught with good examples (and some bad for contrast). > >> > > > >I'm not talking about car parts. I'm talking about explaining > >modularity, complexity, side-effects, classes as data structures etc. > > These are concepts that design engineers understand very well. I > wouldn't spend any time teaching them about modularity, but I would > point out how different program structures facilitate modular design, > and how syntax can sometimes restrict your ability to modularize as > you see fit. Case in point: The need for static methods to put the > show() functions where we want them. > > >> >OK: "The whole idea of having these structures in any program is > >> >wrong." > >> > > >> >Firstly, the program uses a class hierarchy as a data structure. That > >> >isn't what class heirarchies are designed for, and not how they should > >> >be used IMO. But it's what any bright student will pick up from the > >> >example. > >> > >> The classes contain both data and functions. The data is specific to > >> each class. I even show an example of where the two-class first > >> example forced us to put some data at an inappropriate level, but with > >> a four class hierarchy, we can put each data item right where it > >> belongs. > >> > > > >The data is not specific to the class. It's specific to the class and > >it's subclasses. Subclasses should be dependent on the superclass, > >and generally not the other way around. > > What data are we talking about? numMammals is specific to Mammal. > genus is specific to Feline, but *inherited* by instances of a > subclass like Cat. The numAnimals etc... data, which is stored in Animals but gets arbitrarily altered by the actions of subclasses of Animal, and therefore is not specific to animal; it doesn't represent the state of the Animal class or of Animal objects, but of a whole bunch of subclasses of Animal. > > >> Nothing in the Bovine class can affect anything in a Cat. Feline and > >> Bovine are independent branches below Mammal. Adding a Mouse class > >> anywhere other than in the chain Cat - Feline - Mammal - Animal cannot > >> affect Cat. Could you give a specific example? > >> > > > >Say someone adds a mouse class but doesn't call the constructor for > >Mammal. The data produced by mammal and therefore cat is now > >incorrect, as instances of mouse are not included in your count. In a > >real example, anything might be hanging on that variable - so e.g. > >someone adds some mouse instances and the program crashes with an > >array index out of bounds (or whatever the Pythonic equivalent is :) ) > >, or maybe we just get bad user output. This type of behaviour is > >damn-near impossible to debug in a complex program, because you didn't > >change anything which could have caused it. It's caused by what you > >didn't do. > > These are normal programming errors that can occur in any program, no > matter how well structured. I don't see how the specific structure of > Animals.py encourages these errors. Imagine if your structure had been implemented as one of the basic structures of, say, Java. That is, some static data in the Object class stores state for all the subclasses of Object. Now, someone coming along and innocently creating a class can break Object - meaning that may break anything with a dependency on Object, which is the entire system. So I write a nice GUI widget and bang! by some bizzare twist it breaks my program somewhere else because of an error in, say, the StringBuffer class. This is analagous to what you are implementing here. While errors are always going to happen, OOP calls on some conventions to minimize them. The most absolutely vital of these is that it's clear what can break what. Generally I should never be able to break a subsystem by breaking it's wrapper; definitely I should never be able to break a superclass by breaking it's subclass; and I *certainly* shouldn't be able to break a part of the system by changing something unconnected to it. The whole of OOP derives, more or less directly, from these principles. Expressions like 'A is a part/type of B' derive from this philosophy, not the other way around. Your program breaks with this concept. It allows an event in Cat to affect data in Mammal and in Animal, which also has knock-on effects for every other subclass of these. Therefore it is bad object oriented programming. It takes us back to the days before even structured programming, when no-one ever had any idea what the effects of altering or adding a piece of code would be. It is therefore not a good teaching example. :) > > >> I'm not sure what you mean by "side effects" here. The show() > >> function at each level is completely independent of the show() > >> function at another level. > > > > >But the inventory data isn't independent. It's affected by classes > >somewhere else in the heirarchy. Worse, it's done implicitly. > > The "inventory data" actually consists of independent pieces of data > from each class. ( numCats is a piece of inventory data from the Cat > class.) I'm sorry I just can't follow this. > numMammals OTOH is not just a piece of data from one class - it's a piece of data stored in one class, but which stores data about events in many different classes, all of which are outside it's scope. > >> Chaining them together results in a > >> sequence of calls, and a sequence of outputs that is exactly what we > >> want. The nice thing about separating the total "show" functionality > >> into parts specific to each class is that when we add a class in the > >> middle, as I did with Feline, inserted between Mammal and Cat, it is > >> real easy to change the Cat class to accomodate the insertion. > >> > >> Python has a 'super' function to facilitate this kind of chaining. > >> Michele Simionato's 'prototype.py' module makes 'super' even easier to > >> use. Instead of having Cat.show() call Mammal.show() I can now just > >> say super.show() and it will automatically call the show() function > >> from whatever class is the current parent. Then when I add a Feline > >> class between Mammal and Cat, I don't even need to change the > >> internals of Cat. > > > >That's fine - providing you're not using a class heirarchy to store > >data. It's not the act of calling a method in a super-class which is > >a bad idea, it's the way you are making *the numbers outputted* from > >cat dependent of actions taken *or not taken* in another class > >*completely outside cat's scope*. > > Seems like this is the way it has to be if you want to increment the > counts for Cat and all its ancestors whenever you create a new > instance of Cat. Again, I'm not understanding the problem you are > seeing. You seem to be saying there should be only methods, not data, > stored in each class. > That's the way it has to be, if you want to write it like that. However there is nothing to say that a given problem must use a certain class structure. If you come up with a solution like this then it's near-guaranteed that there was something badly wrong with the way you modelled the domain. Either the program shouldn't need to know the number of instances which ever existed of subclasses of mammal or else your class structure is wrong. And, as general rule, you should think carefully before using classes to store data; that's typically what objects are for. I used static data in programs quite a lot before I realised that it too-often bit me later on. > >> In one syntax we need special "static methods" to handle calls where a > >> specific instance is not available, or not appropriate. In another > >> syntax we can do the same thing with one universal function form. > > To try and get to the bottom of this, I re-wrote the Animals.py > example, following what I think are your recommendations on moving the > static methods to module-level functions. I did not move the data out > of the classes, because that makes no sense to me at all. > *Sigh* No, I must say that doesn't help much. :-\ As I said, there is something wrong with the whole idea behind it; the design needs refactoring, not individual lines of code. Having said that, I'll try to redact the issues as best I can, on the basis that it may illustrate what I mean. OK: start with the basics. We need iterative counting data about the individual elements of the heirarchy. The first thing is that we need to factor out the print statements. Your back-end data manipulation modules should never have UI elements in them. So, whatever form the data manipulation comes in, it should be abstract. Secondly, we want to keep the data stored in each class local to that class. So, Mammal can store the number of Mammals, if that turns out to be a good solution, but not the number of it's subclasses. OTOH we could remove the data from the classes altogether. Thirdly, it would probably be nice if we had the ability to implement the whole thing in multiple independant systems. Currently the design only allows one of "whatever-we're-doing" at a time, which is almost certainly bad. After a bit of brainstorming this is what I came up with. It's not a specific solution to your problem; instead it's a general one. The following class may be sub-classed and an entire class-heirarchy can be placed inside it. It will then generate automatically the code to keep a track of and count the elements of the class heirarchy, returning the data you want at a method call. This is done with a standard OO tool, the Decorator pattern, but ramped up with the awesome power of the Python class system. :) class Collective: class base: pass def startup(self, coll, root): #wrapper class to count creations of classes self.root = root class wrapper: def __init__(self, name, c): self.mycount = 0 self.c = c self.name = name def __call__(self, *arg): tmp = self.c(*arg) self.mycount += 1 return self.c(*arg) self.wrapper = wrapper #replace every class derived from root with a wrapper #plus build a table of the self.wrap_list = [] for name, elem in coll.__dict__.items(): try: if issubclass(elem, self.root): tmp = wrapper(name, elem) self.__dict__[name] = tmp self.wrap_list.append(tmp) except: pass #when subclassing, override this #call startup with the class name #and the root of the class heirarchy def __init__(self): self.startup(Collective, self.base) #here's the stuff to do the counting #this could be much faster with marginally more work #exercise for the reader... ;) def get_counts(self, klass): counts = [ (x.c, (self.get_sub_count(x), x.name)) \ for x in self.super_classes(klass) ] counts.append( (klass.c, (self.get_sub_count(klass), klass.name)) ) counts.sort(lambda x, y: issubclass(x[0], y[0])) return [x[-1] for x in counts] def get_sub_count(self, klass): count = klass.mycount for sub in self.sub_classes(klass): count += sub.mycount return count def super_classes(self, klass): return [x for x in self.wrap_list if issubclass(klass.c, x.c) \ and not x.c is klass.c] def sub_classes(self, klass): return [x for x in self.wrap_list if issubclass(x.c, klass.c) \ and not x.c is klass.c] So we can now do: class animal_farm(Collective): class Animal: pass class Mammal(Animal): pass class Bovine(Mammal): pass class Feline(Mammal): pass class Cat(Feline): pass def __init__(self): self.startup(animal_farm, self.Animal) a_farm = animal_farm() cat = a_farm.Cat() feline = a_farm.Mammal() print a_farm.get_counts(a_farm.Feline) >>> [(2, 'Animal'), (2, 'Mammal'), (1, 'Feline')] The above code is 51 lines with about 10 lines of comments. For a project of any size, this is a heck of an investment; I believe it would take a fairly determined idiot to break the system, and *most importantly*, they would be able to trace back the cause from the effect fairly easily. Admittedly the solution is on the complicated side, though perhaps someone with more experience than me could simplify things. Unfortunately, a certain amount of complexity is just a reflection of the fact that your demands strain the OO paradigm right to it's limit. You could possibly implement the same thing in Java with a Factory pattern, and perhaps the reflection API. (Of course I'm none too sure I could do that after many years of hacking Java vs a few weeks of Python!) > Take a look at http://ece.arizona.edu/~edatools/Python/Exercises/ and > let me know if Animals_2b.py is what you had in mind. If not, can you > edit it to show me what you mean? > > -- Dave From glc at well.com Tue May 4 13:08:02 2004 From: glc at well.com (Greg Chapman) Date: Tue, 04 May 2004 17:08:02 GMT Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <c7467l$hg0p1$2@ID-169208.news.uni-berlin.de> <4n4d905eflq6ekrutjmrg3t6llk2b8lab7@4ax.com> Message-ID: <nvif90tkiv1i292600a18eqj18jd2to34a@4ax.com> On Mon, 03 May 2004 11:44:06 -0700, David MacQuigg <dmq at gain.com> wrote: >It seems to work in Michele Simionato's 'prototype' module. >{ comp.lang.python, 4/28/04, "Prototypes in Python"} It is global >only to the called function, but the key requirement is met -- no >alteration of the standard function calling sequence. > >Why can't it be a true global? If I understand correctly, one drawback of his approach is that methods cannot rebind globals. A STORE_GLOBAL opcode will store its value into the globs dictionary created when the method was fetched; this dictionary is not the same as the module's dictionary, so the changed global will only be visible within that method (and within that method call: the next time the method is fetched, a new globs will be created). --- Greg Chapman From steve at ferg.org Wed May 5 22:01:18 2004 From: steve at ferg.org (Stephen Ferg) Date: 5 May 2004 19:01:18 -0700 Subject: Newbe-books References: <Uldkc.29554$Qc.1128956@twister1.libero.it> Message-ID: <b16e4ef7.0405051801.712f513b@posting.google.com> "The Quick Python Book" for a very readable introduction -- a bit out of date but that's really irrelevant at the newbie level. "Python in a Nutshell" for a comprehensive reference. Each is less than $30. From fredrik at pythonware.com Wed May 26 17:37:56 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 May 2004 23:37:56 +0200 Subject: Current drive and directory References: <LP7tc.64476$gr.6380832@attbi_s52> Message-ID: <c932no$pc2$1@sea.gmane.org> "EAS" wrote: > Does anyone know how to display the current directory using DOS > and/or Python? I already tried os.pardir and os.curdir in Python, but all > they return are a couple of periods... did you read the fine documentation? look under "files and directories": http://docs.python.org/lib/os-file-dir.html os.getcwd() returns the drive/path. you can use os.path.splitdrive(os.getcwd()) to get the drive and the path as two separate strings. curdir etc is documented a little later in the same chapter: http://docs.python.org/lib/os-path.html </F> From cbearden at hal-pc.org Mon May 10 23:55:20 2004 From: cbearden at hal-pc.org (Chuck Bearden) Date: 11 May 2004 03:55:20 GMT Subject: ClientCookie/urllib2 with persistent connections? References: <409c08a1$0$129$a726171b@news.hal-pc.org> <87u0yp4z0x.fsf@pobox.com> Message-ID: <40a04ea8$0$17089$a726171b@news.hal-pc.org> On 2004-05-09, John J. Lee <jjl at pobox.com> wrote: > Chuck Bearden <cbearden at hal-pc.org> writes: > >> My impression is that if I want to make several requests over a single, >> persistent HTTP 1.1 connection, I must use httplib rather than urllib2 >> or ClientCookies. Is that correct? > > Yes. > > >> To put it another way, can I have cookie support over persistent >> connections without having to code the cookie support myself? > > Yes. You can use httplib direct, and use a couple of little functions > to link it up to ClientCookie. The request and response interfaces > required are well-documented. Here is a clumsy cobbled-together hack, > for HTTP only, which may even work ;-) No automatic redirection > handling, proxy support, etc. The cookies bit is simple (thanks to > ClientCookie :-), it's the rest that's messy. Many thanks for your response, and for the ClientCookies module! I have already put it to use through the urllib2 interface, and I will study the examples in your posting as well. Chuck From matt at pollenation.net Mon May 17 19:21:53 2004 From: matt at pollenation.net (Matt Goodall) Date: Tue, 18 May 2004 00:21:53 +0100 Subject: Web testing framework? In-Reply-To: <c8b3et$68j$2@newsmaster.cc.columbia.edu> References: <c8b3et$68j$2@newsmaster.cc.columbia.edu> Message-ID: <1084836112.5665.61.camel@debian> On Mon, 2004-05-17 at 20:23, Robb Shecter wrote: > Anybody know about a Python library for testing websites? I'm > thinking of something like a scriptable browser, where you could tell > it to browse to a certain URL, check for the existence of certain text > in a page, follow a certain link, etc. You should look at Python Browsing Probe, <http://pbp.berlios.de/>. It's a fairly new project but it sounds like it already does exactly what you want, and more. From the website: "PBP is a web test tool based on John J. Lee's mechanize. It exposes the browser functionality at the level of a shell-like interpreter so that testers can quickly write tests in a simple language designed specifically for that purpose. Anyone familiar with a command line should be able to write test scripts for even the most complex web applications with PBP." Cheers, Matt -- Matt Goodall, Pollenation Internet Ltd w: http://www.pollenation.net e: matt at pollenation.net Any views expressed are my own and do not necessarily reflect the views of my employer. From peter at engcorp.com Mon May 10 13:19:08 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 May 2004 13:19:08 -0400 Subject: polymorphism w/out signatures? In-Reply-To: <slrnc9vdkd.6tr.rmunn@rmunnlfs.dyndns.org> References: <mailman.329.1083877186.25742.python-list@python.org> <314b29e9.0405070128.28de9ff6@posting.google.com> <slrnc9vdkd.6tr.rmunn@rmunnlfs.dyndns.org> Message-ID: <fLadnYZ7Ns8RJALdRVn-jA@powergate.ca> Robin Munn wrote: > Simon Brunning <simon at brunningonline.net> wrote: > >>def setText(window, text, append=False): >> # Ensure that text is a list >> try: >> text + '' >> text = [text] >> except TypeError: >> pass >> >> ... rest of funtion, which can assume that 'text' is a list > > > That would be better with an "else:" clause: > > try: > text + '' > except TypeError: > pass > else: > test = [text] Just to verify, you think it's better solely because of the improved readability, right? Or is there some way that the following code can possibly fail with a TypeError, for any reason whatsoever? someName = [someName] -Peter From brian at sweetapp.com Tue May 18 06:05:42 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 18 May 2004 12:05:42 +0200 Subject: Python compilers? In-Reply-To: <Q3lqc.2178$eH3.47040@news4.e.nsc.no> References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <Q3lqc.2178$eH3.47040@news4.e.nsc.no> Message-ID: <40A9DFF6.5030508@sweetapp.com> Svein Ove Aas wrote: > Erk. > Seems to me that you want 'smarter', not 'worse'. I can't take a language > seriously if it says that 1/3 is 0.33333... . What is that? Are you arguing for an integer result, a fixed result or a rational result? Cheers, Brian From xaver_hinterhuber at web.de Mon May 10 05:03:03 2004 From: xaver_hinterhuber at web.de (Xaver Hinterhuber) Date: Mon, 10 May 2004 11:03:03 +0200 Subject: dynamic function Message-ID: <c7ngg7$p1$1@online.de> Hello pythonistas, I have programmed a product in Zope which allows me to source code on the web. Now I want to compile the code into a function and execute the function. The code is as follows: import new code = compile(srcString, 'getContent', 'exec') f = new.function(code, globalDict, 'getContent') If srcString contains a return statement, then python returns a CompilationError stating, that I cannot use return outside a function. How do I have to compile the sourcecode to get around this problem? -- Mit freundlichen Gr?ssen Xaver Hinterhuber From leovabgeest at netscape.org Mon May 31 12:08:26 2004 From: leovabgeest at netscape.org (Leo van Geest) Date: Mon, 31 May 2004 18:08:26 +0200 Subject: Show the review state of an item in Plone In-Reply-To: <u3c5hu5xw.fsf@broadpark.no> References: <e5f09805.0405300647.77feccf@posting.google.com> <u3c5hu5xw.fsf@broadpark.no> Message-ID: <ba6f$40bb65f6$52d92570$27634@news.multikabel.nl> Tor Iver Wilhelmsen wrote: > lf.van.geest at quicknet.nl (Leo) writes: > > >>Error Type >> NameError >>Error Value >> name 'getInfoFor' is not defined > > > Using TAL you're in Zope land AFAIK, and getInfoFor() isn't a method I > can find in that API. You need to prefix - or even import - the > package, e.g. workflow_tool.getInfoFor(...). Thank you for your answer. In fact, you pointed me to te right direction. The getInfoFor is a method defined by the portal_workflow module. A correct way to show the review state of an item in Plone is: <h2 tal:define="wtool here/portal_workflow; review_state python: wtool.getInfoFor(here, 'review_state')" tal:content=review_state> </h2> From tdelaney at avaya.com Mon May 24 04:09:10 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 24 May 2004 18:09:10 +1000 Subject: iterator expression - please explain Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0187FCCE@au3010avexu1.global.avaya.com> Helmut Jarausch wrote: > Hi, > > with Python 2.4a0 (CVS 2004/05/24) > I get > > def myfun(myarg): > for z in myarg: > print z > > myfun(x^2 for x in xrange(10)) > 2 > 3 > 0 > 1 > 6 > 7 > 4 > 5 > 10 > 11 > > I expected the sequence 0,1,4,9,.... > What am I missing and what's going on here? ^ is the bitwise exclusive or operator. You want exponentiation ... which is **. myfun(x**2 for x in xrange(10)) Tim Delaney From siona at chiark.greenend.org.uk Tue May 25 08:38:21 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 25 May 2004 13:38:21 +0100 (BST) Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> <m2k6z1ejcc.fsf@unique.phony.fqdn> <KXrsc.15274$bF3.12656@fed1read01> Message-ID: <n7i*p+mlq@news.chiark.greenend.org.uk> Mark Hahn <mark at prothon.org> wrote: >No economy is ever going to to have a gdp of 10**19 pennies. Turkey's is around 10**18 lira (obtained from 2002 GDP in $ and current exchange rate). You could argue that by the time they hit 10**19 they'll have got EU membership and gone over to the Euro.... (Japan's GDP appears to be around 10**16Y, BTW.) Given the number of times we see newbies confused by Python's handling of floating points, it strikes me that silent conversion of overflowing ints to doubles is asking for trouble somewhere down the line, and should be avoided if possible. -- \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 hungjunglu at yahoo.com Thu May 20 16:44:23 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 May 2004 13:44:23 -0700 Subject: Freeze and Resume execution References: <mailman.106.1085054124.6949.python-list@python.org> Message-ID: <8ef9bea6.0405201244.4850d450@posting.google.com> "Miki Tebeka" <miki.tebeka at zoran.com> wrote in message news:<mailman.106.1085054124.6949.python-list at python.org>... > I'm looking for a way to "yield" an exception. > ... > I'd like to use generators but can't see any "nice" way of doing it. > What I'd like it to throw an exception when the buffer is full and then > next time the generator is called to continue execution as after a > "yield". Generators are yielding in the wrong direction, though. I will assume that you do not have to roll-back changes. (When there is a roll-back requirement, things get complicated, and prototype-based languages are more suitable for that purpose.) while 1: try: write_output() break except BufferFullException: request_user_intervention() Would something like that suit your purpose? (The request_user_intervention() method could be a callback.) > Is this possible? > Can you recommend a good way of doing this? Any state machine? Yes, of course it's possible. IDEs like VB6 and Visual C++ all have edit-and-continue features. When a bug happens, the program stops. You have chance to modify some variables, then resume execution from the point of failure. Similarly, in transaction-enabled software (like databases), when failures occur, you can even rollback the whole thing as if nothing has happened. It all depends on the details of your requirements. The simplest solution is the one shown above. If that does not meet your requirements, could you please post further details? If you do require roll-back, the solution could be very different. Prototype-based languages are the natural platform for dealing with this type of problem. But if you do not use PB-OOP, you will have to create sandbox objects manually, and do the commitment/roll-back by hand. State machines are OK, too. (With a workspace object often known as REQUEST.) But the problem is how granular you want to define your states. It's a pain when the level of granularity changes. I'd try the callback approach shown above, before anything else. The approach shown above can be further refined upon usage of aspect-oriented-ish mechanics and/or codeblocks. There are many tools to attack the problem. It all depends on your specific needs. regards, Hung Jung From brian at sweetapp.com Wed May 5 14:30:47 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 05 May 2004 20:30:47 +0200 Subject: VIM and tab to space migration In-Reply-To: <40992866$0$12738$636a15ce@news.free.fr> References: <c5bg1k$25vq$1@news.wplus.net> <c5c138$i91$1@news.service.uci.edu> <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <mailman.266.1083757569.25742.python-list@python.org> <40992866$0$12738$636a15ce@news.free.fr> Message-ID: <409932D7.9030502@sweetapp.com> Christophe Cavalaria wrote: > Try adding that line at the end of each modified file : > > # vim:sw=4:softtabstop=4:expandtab > > It tells vim all the commands it should automatically run when it opens the > file and it should get you the correct behaviour for 4 spaces no tab > indentation. Thanks for the suggestion but modifying all my files is a pretty ugly solution. Not that I'm above using it if there is no better way :-) Cheers, Brian From opengeometry at yahoo.ca Mon May 10 13:22:26 2004 From: opengeometry at yahoo.ca (William Park) Date: 10 May 2004 17:22:26 GMT Subject: Python job opening at GPO in Washington, DC References: <b16e4ef7.0403030957.21a0c216@posting.google.com> <m3pt9gmi0z.fsf@tanelorn.bandersnatch.org> <2g26l5F3ovo0U1@uni-berlin.de> <m3llk1m1z1.fsf@tanelorn.bandersnatch.org> Message-ID: <2g9s2hF96nhU1@uni-berlin.de> Nick Vargish <nav+posts at bandersnatch.org> wrote: > Nonetheless, my boss is actually very interested in Python, because > he's interested in building sustainable systems. He's spent enough > time nursing along proprietary systems that have become both > entrenched and orphaned that he's sick and tired of it. Ahh, but those complaints are not really complaint. They are job security for your coworkers and the boss who manages them. Pretty soon, you would be labelled as "not a team player" by your coworkers and "trouble maker" by your union rep. :-) I wish you good luck. It's shame that they don't use LaTeX or shell scripts. -- William Park, Open Geometry Consulting, <opengeometry at yahoo.ca> Linux solution/training/migration, Thin-client From goodger at python.org Thu May 20 11:52:16 2004 From: goodger at python.org (David Goodger) Date: Thu, 20 May 2004 10:52:16 -0500 Subject: Documentation/Info on this sign In-Reply-To: <c8iims$24i$1@solaris.cc.vt.edu> References: <c8iims$24i$1@solaris.cc.vt.edu> Message-ID: <40ACD430.6060003@python.org> Bart Nessux wrote: > Could someone point me to documentation on this (and similar) > signs used in Python: > > += http://www.python.org/doc/current/ref/augassign.html > Usage would be: > > x = += len(y) No, it would be: x = len(y) or: x += len(y) You can't combine them. -- David Goodger From srumbalski at copper.net Mon May 10 22:31:21 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Mon, 10 May 2004 22:31:21 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> Message-ID: <40a03b44_3@newsfeed.slurp.net> Olivier Scalbert wrote: > Jarek Zgoda wrote: > >>Olivier Scalbert <olivier.scalbert at algosyn.com> pisze: >> >>>What is the python way of doing this : >>>perl -pi -e 's/string1/string2/' file >>> >>Use sed. >> > yes, but in python ? print 'Use sed.' -- Steven Rumbalski news|at|rumbalski|dot|com From elainejackson7355 at home.com Fri May 14 02:39:27 2004 From: elainejackson7355 at home.com (Elaine Jackson) Date: Fri, 14 May 2004 06:39:27 GMT Subject: exhaustive subsets References: <mailman.0.1084510656.27251.python-list@python.org> Message-ID: <zQZoc.474813$Ig.279550@pd7tw2no> google for Sterling numbers "Brett Calcott" <brett at coombs.anu.edu.au> wrote in message news:mailman.0.1084510656.27251.python-list at python.org... | I've found some python solutions to find the set of subsets for a given set, | but how do you find the set of the set of subsets whose union is the given | set and whose intersections is the empty set. | | ie. Given a cake divided into 6 unique pieces (0-5), how many different ways | can I distribute the cake so that there are no pieces left. eg. | | ((0), (1,2,3,4)) | or ((0),(1),(2,3,4)) | or ((0,1),(2,3),(4)) | or ((0,4),(1),(2,3)) | | Is there a name for this problem? | | Cheers, | Brett | | -- | Brett Calcott | Philosophy Program, RSSS, ANU | Canberra, ACT 0200, AUSTRALIA | | | | From peter at engcorp.com Wed May 26 07:53:14 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 07:53:14 -0400 Subject: Cleaner idiom for text processing? In-Reply-To: <Xns94F5821692826duncanrcpcouk@127.0.0.1> References: <f2403000.0405251739.2a77b11d@posting.google.com> <c91got$vpi$00$1@news.t-online.com> <Xns94F559D4C3451duncanrcpcouk@127.0.0.1> <c91pft$rl0$04$1@news.t-online.com> <Xns94F5821692826duncanrcpcouk@127.0.0.1> Message-ID: <Gv6dnYkQEKy0GCndRVn-hg@powergate.ca> Duncan Booth wrote: > What happens if someone works out that izip can be made much faster by > consuming its iterators from right to left instead of left to right? That > isn't nearly as far fetched as reading ahead. > > Passing the same iterator multiple times to izip is a pretty neat idea, but > I would still be happier if the documentation explicitly stated that it > consumes its arguments left to right. Or as an interim measure: write lots of elegant code using that technique, and then if anyone suggests changing the way it works the rest of the world will shout "no, it will break code!". ;-) -Peter From sross at connectmail.carleton.ca Fri May 14 13:24:31 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 14 May 2004 13:24:31 -0400 Subject: beginner's question References: <c82d51$78s$1@lust.ihug.co.nz> <Xs3pc.34385$dr1.943764@news20.bellglobal.com> <Ny3pc.34409$dr1.944419@news20.bellglobal.com> <c82s64$f66$1@lust.ihug.co.nz> Message-ID: <lg7pc.36078$dr1.973958@news20.bellglobal.com> "Hadi" <hadi at nojunk.com.au> wrote in message news:c82s64$f66$1 at lust.ihug.co.nz... > Sean, > > I appreciate for your help. Your script works fine. I have one last > question. > What do I have to modify on the script, so the script will work for more > than one line? > Because the file-1 has about 500 lines. > This is for my Machine Learning assignment which I use this for the Naive > Bayes classifier for the spam mail classification. > Thank you again and I would appreciate very much one more help from you. > > Regards, > Halit > [snip] Well, you have a file (file-1), which you now know how to open. src = file("file-1.txt") There are a few ways to proceed, but I'll choose one and stick with that. You'll want to go through the file, one line at a time (it's possible to read in the entire file and process it that way, but we'll skip that for now). You can go through a file one line at a time using a for loop: for line in src: ... do stuff with line ... Now, in the code I posted earlier I used a list comprehension where I read one line of the file and extracted the words (storing them in a list called words). words = [w.strip() for w in src.readline().split(',')] Using the for loop, that line has already been read so you do not need to use src.readline() any more, but you still need to do the processing on the line to extract the words. I think you should be able to figure out how to do that, so I won't show the code changes here. Once you have the list of words for that line, you need to see whether they are in your lexicon and write True or False to your output file (file-2.txt, in this case). The code I provided earlier gives an example of how to do that. If you need the output to be in a certain format, other than what the example shows, you should be able to figure out how to get that done as well. So, to recap, you'll be using a for loop to go through the input file, one line at a time. For each line, you will extract the words and store them in a list. Then, for each word in that list, you will check whether it is in your lexicon, and write either True or False to your output file. When you're done, you can close both files explicitly, or let Python take care of it for you. That should be enough to get you started. If you have more difficulties, post your code, and people will help point you in the right direction. Good luck, Sean From vbasicboy at aol.com Fri May 21 05:05:34 2004 From: vbasicboy at aol.com (Grant D. Watson) Date: 21 May 2004 09:05:34 GMT Subject: Running code on module import Message-ID: <20040521050534.21796.00001788@mb-m15.aol.com> If this has been answered before, or if my terminology is off, please bear with me; my Python experience is limited to use in one class and to personal projects. I'd like to do something rather silly: I'd like to run a particular piece of code from a given module every time that the module is imported, and not just at the time that the module is originally loaded. So, every time a module says import foo or something analogous, I want foo.doYourThing() to be invoked, in addition to the usual effects on the importing module's namespace. Now, my reaction is to create a newfangled import hook that will intercept requests to load "foo" and send back a reference to the first loaded copy, so that I only have one copy of foo at any given time, but omit (or delete, as necessary) a reference to foo from sys.modules; this way my import hook will be invoked each time someone wants to import foo (from which I can launch foo.doYourThing()). The problem is that I want to do all this without use of another module or additional code in the module that imports foo. This means that I have to install the hook from _inside_ foo. But if I do that, I can't seem to avoid leaving a reference in sys.modules; removing it prevents the initial import (the one that loads the module in the first place) from succeeding. You're probably all foo-ed out by now. Is there any way to do this? I'm not married to the import hook idea, it just seemed like the most promising to me. Is there some API I missed that would simplify things? Your help is much appreciated. Grant D. Watson grant_watson at yahoo.pleasedontspamme.com (Use this one!) From connellybarnes at yahoo.com Mon May 3 21:33:15 2004 From: connellybarnes at yahoo.com (C. Barnes) Date: Mon, 3 May 2004 18:33:15 -0700 (PDT) Subject: Kill a thread in Python Message-ID: <20040504013315.81069.qmail@web14524.mail.yahoo.com> This code module allows you to kill threads. The class KThread is a drop-in replacement for threading.Thread. It adds the kill() method, which should stop most threads in their tracks. # --------------------------------------------------------------------- # KThread.py: A killable Thread implementation. # --------------------------------------------------------------------- import sys import trace import threading class KThread(threading.Thread): """A subclass of threading.Thread, with a kill() method.""" def __init__(self, *args, **keywords): threading.Thread.__init__(self, *args, **keywords) self.killed = False def start(self): """Start the thread.""" self.__run_backup = self.run self.run = self.__run # Force the Thread to install our trace. threading.Thread.start(self) def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, why, arg): if why == 'call': return self.localtrace else: return None def localtrace(self, frame, why, arg): if self.killed: if why == 'line': raise SystemExit() return self.localtrace def kill(self): self.killed = True ------------------------------------------------------------------------ Example usage: ------------------------------------------------------------------------ This illustrates running a function in a separate thread. The thread is killed before the function finishes. from KThread import * def func(): print 'Function started' for i in xrange(1000000): pass print 'Function finished' A = KThread(target=func) A.start() for i in xrange(1000000): pass A.kill() print 'End of main program' Output: Function started End of main program ----------------------------------------------------------------------- How It Works: ----------------------------------------------------------------------- The KThread class works by installing a trace in the thread. The trace checks at every line of execution whether it should terminate itself. So it's possible to instantly kill any actively executing Python code. However, if your code hangs at a lower level than Python, then the thread will not actually be killed until the next Python statement is executed. ----------------------------------------------------------------------- Considerations: ----------------------------------------------------------------------- Certain IDEs may install their own threading trace code, for debugging purposes. This module is incompatible with those IDEs. Consider bugging the Python folks, until they give us a thread kill method. The code has already been written: http://mail.python.org/pipermail/python-list/2003-February/148999.html Regards, Connelly Barnes __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From notarangelotonio at tiscali.it Fri May 7 16:12:06 2004 From: notarangelotonio at tiscali.it (Tonio) Date: Fri, 07 May 2004 20:12:06 GMT Subject: Embedded comments in Python? References: <5b42ae4.0405030330.5bba90f5@posting.google.com> Message-ID: <q4Smc.42988$Qc.1695191@twister1.libero.it> "Ernie" <eadorio at yahoo.com> ha scritto nel messaggio news:5b42ae4.0405030330.5bba90f5 at posting.google.com... > Hi, > Whats the legal way in Python to embed comments in Python code? > Example: > > def foo(a <:int>, b <:float>): <:array> > return [a, b] > > Want the CPython interpreter to ignore the <:int>, <:float> and > <:array>(this one can be written as #array). Using triple quoted > strings would be longer and is invalid syntax. This would be > extremely useful for those who write tools for processing Python > scripts. In C/C++, this would be no problem with /* */. > > Regards, > > Ernie Thanks Arkon, i'm a italian student and i need your tutorial. If you have a example, can you send me in my email? Thanks. From j_mckitrick at bigfoot.com Tue May 25 09:47:11 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 25 May 2004 06:47:11 -0700 Subject: Can I use Tkinter and PyGtk in the same project, different dialogs? Message-ID: <ec6dce8b.0405250547.6e49c36e@posting.google.com> I'm considering phasing out tkinter and moving to pygtk, but I can't rewrite the entire app. Can I just rewrite one dialog at a time? jonathon From SeeBelow at SeeBelow.Nut Tue May 25 21:34:36 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 26 May 2004 01:34:36 GMT Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <roy-5EFE18.21121225052004@reader2.panix.com> Message-ID: <40B3F448.EB711333@shaw.ca> Roy Smith wrote: > > In article <40B3E861.29B033D5 at shaw.ca>, SeeBelow at SeeBelow.Nut wrote: > > > I see the value of a class when two or more instances will be created, > > but Python programmers regularly use a class when there will only be one > > instance. > > What is the benefit of this? It has a disadvantage of a whole lot of > > "self." > > being required everywhere, making the code less readable. Also, since a > > strength of Python is rapid application development, it slows one down > > to have to put in all those self.'s. The code seems much cleaner to me > > without classes that have only one instance. Oh, also, all the methods > > of this class will have to have the instance name prepended to them. > > > > I would appreciate it if someone could explain the advantages of doing > > this, or at least the sociological reasons why it occurs. > > > > Mitchell Timin > > Typing "self" is a mechanical process which adds very little to the > development cost. Deciding which things to make classes and which not > to requires significant mental effort and does add cost. It's just > easier to make everything a class. Even easier is not to make anything a class unless there will be two or more instances of it. I still don't get what advantage making a class buys for you. > > More than that, most times I've decided to not bother making something a > class because it was too simple, I've eventually added enough > functionality to it to change my mind and have to re-do things. That's > real cost. Much simplier and cheaper to just make it a class from the > get-go. Why does greater functionality make a class desireable, if there won't be multiple instances created? Other people have mentioned "code reuse". Again I don't see how a class helps to make code reusable. I find methods in a class more difficult to reuse than simple function definitions. (unless there are multiple instances.) Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From Moiz.Golawala at ge.com Thu May 6 10:33:23 2004 From: Moiz.Golawala at ge.com (Golawala, Moiz M (GE Infrastructure)) Date: Thu, 6 May 2004 09:33:23 -0500 Subject: How to get Hostname using SimpleXMLRPCServer Message-ID: <F0C893FC2E24F946A250F440BF21EA9905D2EE4A@FTWMLVEM01.e2k.ad.ge.com> Thank you, Brian for the reply. I figured it out. I realized that in the SimpleXMLRPCRequestHandler there is a doPost method which is inherited from BaseHTTPRequestHandler. In the doPost method you can simply ask the self.header for the host variable (clientName = self.host["host"]) and you get the client that is invoking the call to the server. In using the address_string() method I had some problem, I would get exceptions that the address_string method needs an instance of the SimpleXMLRPCRequestHandler as an argument. When I over-rode the address_string method in the SimpleXMLRPCRequestHandler class and passed in self as an argument I got the exception that an SimpleXMLRPCRequestHandler instance is required and instead it got a class. I could not figure out what that meant. class SimpleXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def address_string(self): return BaseHTTPServer.BaseHTTPRequestHandler.address_string(self) calling the address_string method from the SimpleXMLRPCServer will throw an exception saying that the a SimpleXMLRPCRequestHandler instance was expected, but got a class instead. so the work around to this was what I mentioned in the first paragraph. I will simply create an instance variable to store the host name and have a getter to get the variable from the SimpleXMLRPCRequestHandler class. Thanks Moiz -----Original Message----- From: Brian Quinlan [mailto:brian at sweetapp.com] Sent: Thursday, May 06, 2004 9:45 AM To: Golawala, Moiz M (GE Infrastructure); python-list at python.org Subject: Re: How to get Hostname using SimpleXMLRPCServer Golawala, Moiz M (GE Infrastructure) wrote: > I have multiple xmlrpc clients talking to my SimpleXMLRPCServer. When a method > on my server is invoked, I would like to know the hostname of the client that > has invoked the method. Does anybody know how to get the client host name from > the xmlrpc request call to the SimpleXMLRPCServer. Any help is > appreciated. Sorry I don't have time to actually write any example code for you, but you might want to look at the BaseHTTPServer documentation. SimpleXMLRPCRequestHandler is a subclass of BaseHTTPServer.BaseHTTPRequestHandler, which has a client_address instance variable and an address_string() method. Let me know if you need any other help (and sorry for ignoring your post yesterday). Cheers, Brian From eurleif at ecritters.biz Wed May 19 11:35:16 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 19 May 2004 15:35:16 GMT Subject: alternatives to making blocks like { } or other ?? In-Reply-To: <faf44c99.0405190420.3619b943@posting.google.com> References: <c8do0u$9fb$1@news.atman.pl> <jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com> <c8e5sh$109b$1@news.atman.pl> <slrncalqqf.8f2.grante@grante.rivatek.com> <sjDqc.108220$NR5.92596@fe1.texas.rr.com> <faf44c99.0405190420.3619b943@posting.google.com> Message-ID: <U8Lqc.2248$Hf.1317579@newshog.newsread.com> Tim Williams wrote: > I have to put my 2 cents in here. I love Python, but the one thing I > miss is using {} or something to enclose blocks. I edit in emacs > python-mode, and believe in indentation, but sometimes I'll > inadvertently change a line of code's indentation and it throws the > logic off. I found a bug in one of my programs recently where a line > of code should have been outside of an 'if', but wasn't because I hit > TAB one too many times. A {} block would've caught that. I know that's > just being careless, but I need all the help I can get! And if you came back a few months later, wouldn't you have been confused about what your code was doing? The beauty of Python's indentation is that the code does what you'll expect from looking at it. From greg at cosc.canterbury.ac.nz Sun May 2 21:11:17 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 03 May 2004 13:11:17 +1200 Subject: Unification of Methods and Functions In-Reply-To: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> Message-ID: <c7467l$hg0p1$2@ID-169208.news.uni-berlin.de> David MacQuigg wrote: > The concept of using a > global variable __self__ is no surprise at all. Except that __self__ can't be a global variable. Implementing it that way would be a disaster. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pcarter at uk.ibm.com Mon May 17 10:40:25 2004 From: pcarter at uk.ibm.com (Philip Carter) Date: Mon, 17 May 2004 15:40:25 +0100 Subject: program works as a script, not interactively Message-ID: <40A8CED9.2AA19629@uk.ibm.com> Hello there, I am using: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 on a win2k box. I have the following piece of python code: inputTmpFileOnSTAXServer='c:/temp/phil.txt' outputTmpFileOnSTAXServer='c:/temp/philOut.txt' import re # import regular expression module regExp=re.compile('(\[.+\]) Tests run: (\d+), Failures: (\d+)') # compile the regular expression inFile=open(inputTmpFileOnSTAXServer) # open the input file for reading outFile=open(outputTmpFileOnSTAXServer,'w') # open the output file for writing aLine=inFile.readline() # read a line while aLine != "": # loop round until EOF match=regExp.search(aLine) # search for regExp in aLine if match: # if there is a match aDir = match.group(1) # store the dir section of the line attempted = match.group(2) # store the number of tests attempted attemptedInt = int(attempted) # convert it into an int failed = match.group(3) # store number of failures failedInt = int(failed) passedInt = attemptedInt - failedInt # calculate the number passed passedStr = str(passedInt) # convert it into a string outLine=aDir+'\n'+attempted+' tests were attempted\n'+passedStr+' test(s) passed\n' # create summary line in correct format outFile.write(outLine) # write out the summary line aLine=inFile.readline() # read a line outFile.close() # close the output file inFile.close() When I save in a file - terry.py and run it: python terry.py it works fine. However, if I try and paste it into an interactive python window, I get the following error: ... outFile.close() # close the output file File "<stdin>", line 14 outFile.close() # close the output file ^ SyntaxError: invalid syntax Any idea why this is? Thanks, Phil -- pcarter at uk.ibm.com From sean_berry at cox.net Wed May 12 16:51:49 2004 From: sean_berry at cox.net (Sean Berry) Date: Wed, 12 May 2004 13:51:49 -0700 Subject: Printing formatted strings from a dictionary References: <b4a8ffb6.0405121230.a564636@posting.google.com> Message-ID: <F7woc.4020$2c7.308@fed1read07> >>> d={'n1':1, 's1':'spam', 'n2':4} >>> x = "%s %s %s you" %(d['n1'], d['s1'], d['n2']) >>> x '1 spam 4 you' >>> "Thomas Philips" <tkpmep at hotmail.com> wrote in message news:b4a8ffb6.0405121230.a564636 at posting.google.com... > I want to print "1 spam 4 you" using a formatted string that gets its > inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, > I write > > >>> x="%('n1')d %('s1')s %('n2')d you" > >>> x % d > > Traceback (most recent call last): > File "<pyshell#22>", line 1, in -toplevel- > x % d > KeyError: "'n1'" > >>> > > However, I get what I want if I edit x to remove the quotes around n1, > s1 and n2 and write > >>> x="%(n1)d %(s1)s %(n2)d you" > >>> x % d > '1 spam 4 you' > > The syntax that works seems to run counter to the way dictionaries > work: > >>> d['n1'] > 1 > >>> d[n1] > > Traceback (most recent call last): > File "<pyshell#18>", line 1, in -toplevel- > d[n1] > NameError: name 'n1' is not defined > > What is the error in my logic? > > Thomas Philips From bdesth.quelquechose at free.quelquepart.fr Sat May 1 06:24:11 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 01 May 2004 12:24:11 +0200 Subject: IDE for Python In-Reply-To: <mailman.164.1083359859.25742.python-list@python.org> References: <mailman.164.1083359859.25742.python-list@python.org> Message-ID: <40937444$0$20745$626a14ce@news.free.fr> dont bother wrote: > Hi Guys: > Is there any good IDE for Python. I checked on > www.python.org and found some. Installed bluefish but > to my surprise its just an editor. I guess it cannot > even compile my code in python or maybe I am wrong. > Any ideas/recommendations for a free IDE for Python > Thanks > Dont > emacs + python-mode + (ECB / speedbar/ whatever you like) is a perfect solution - <troll>as usual, should I say</troll> Bruno From peter at engcorp.com Wed May 26 09:37:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 09:37:54 -0400 Subject: modifying mutable list elements in a for loop In-Reply-To: <9d5509fa.0405260439.175797e@posting.google.com> References: <9d5509fa.0405260439.175797e@posting.google.com> Message-ID: <KcednfNM-cYsACndRVn-gQ@powergate.ca> Peter Ballard wrote: > The python tutorial tells me "It is not safe to modify the sequence > being iterated over in the loop". But what if my list elements are > mutable, such as lists or objects, e.g. Treat that as "not safe if you don't know what you are doing". David's answer is on the mark, but furthermore you *can* modify the sequence being iterated over, if that's really what you want to do. Some algorithms can probably even benefit from the technique, though I can't think of anything off-hand. As with many things in Python, consenting adults can do what they want, and the tutorial is just giving a necessary warning since many beginners, and even non-beginners from time to time, will be caught by this problem otherwise. > [It seems to me that the list elements are pointers (in C-speak), so I > can safely modify the data they are pointing to, because I am not > modifying the list elements themselves. Or is that an implementation > detail (i.e. not safe)?] It's safe. And around here they're usually called "references" instead of "pointers". > But that phrase "It is not safe to modify the sequence being iterated > over in the loop" in the tutorial has me slightly worried. Good. ;-) Then you'll have to pause and think about it from time to time as you learn, until you've integrated the knowledge so deeply that you automatically do the right thing when iterating over lists. That's the goal of that warning in the tutorial (if I may channel the author for a moment :-). -Peter From paul at prescod.net Wed May 26 06:44:55 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 26 May 2004 03:44:55 -0700 Subject: Prothon should not borrow Python strings! In-Reply-To: <7xMsc.17901$bF3.7334@fed1read01> References: <mailman.230.1085420869.6949.python-list@python.org><2hfv4nFch1lmU3@uni-berlin.de> <mailman.271.1085494900.6949.python-list@python.org> <7xMsc.17901$bF3.7334@fed1read01> Message-ID: <40B47527.8060206@prescod.net> Mark Hahn wrote: > "Paul Prescod" <paul at prescod.net> wrote > > Paul et al: I have a number of wild ideas and questions about text and > binary strings and also a few things to discuss about the long integers you > brought up, but the Python list is not the proper place to drag these > discussions out. > > Is there any chance I can get you (and hopefully others participating here) > to join the prothon-user mailing list for a week or two to discuss these > issues? The traffic is only one tenth the traffic here on c.l.p. so it > won't be much burdon. Our discussions are interesting. (We have no pesky > users yet :-) I'll join, but I don't know when I'll find time to contribute...long weekend coming up etc. Paul Prescod From godoy at ieee.org Fri May 21 18:40:15 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri, 21 May 2004 19:40:15 -0300 Subject: Python Newbie References: <3c0a04e4.0405211434.6667f727@posting.google.com> Message-ID: <e3d2o1-e6k.ln1@wintermute.g2ctech> On Sex 21 Mai 2004 19:34, Brian wrote: > #Limiting password atempts to three > > password = raw_input("Enter your Password: ") > count = 0 > > > while password != "secret": > print password = raw-input("Enter your Password: ") > count += 1 > > if password == "secret": > print "Welcome in." > > > elif count > 3: > print "Please come back when you remember your Password." > > else: > raw_input("Press enter to exit.") > > Ok, I know I may be way off course here but any help would be greatly > appreciated. I dont want to get frustrated and say the heck with it, > especially if it is something minor. Thanks in advance. I won't end your fun giving you the answer, but remember that in Python indentation matters, i.e., your lines alignment matters. Read the program above and remember that when you go further on indentation, you just come back when the block is ended. Got it? -- Godoy. <godoy at ieee.org> From PeterAbel at gmx.net Mon May 24 16:43:36 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 24 May 2004 13:43:36 -0700 Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il> Message-ID: <21064255.0405241243.6f3f1170@posting.google.com> Noam Raphael <noamr at correctme.users.sourcephorge.net> wrote in message news:<c8l3s3$27o$1 at news.iucc.ac.il>... > Hello, > Many times I find myself asking for a slice of a specific length, and > writing something like l[12345:12345+10]. > This happens both in interactive use and when writing Python programs, > where I have to write an expression twice (or use a temporary variable). > > Wouldn't it be nice if the Python grammar had supported this frequent > use? My idea is that the expression above might be expressed as > l[12345:>10]. > > This change, as far as I can see, is quite small: it affects only the > grammar and byte-compiling, and has no side effects. > > The only change in syntax is that short_slice would be changed from > [lower_bound] ":" [upper_bound] > to > ([lower_bound] ":" [upper_bound]) | ([lower_bound] ":>" [slice_length]) > > Just to show what will happen to the byte code: l[12345:12345+10] is > compiled to: > LOAD_GLOBAL 0 (l) > LOAD_CONST 1 (12345) > LOAD_CONST 1 (12345) > LOAD_CONST 2 (10) > BINARY_ADD > SLICE+3 > > I suggest that l[12345:>10] would be compiled to: > LOAD_GLOBAL 0 (l) > LOAD_CONST 1 (12345) > DUP_TOP > LOAD_CONST 2 (10) > BINARY_ADD > SLICE+3 > > Well, what do you think? I would like to hear your comments. > > Have a good day (or night), > Noam Raphael Python has ready a workaround for nearly ervery problem. What about the following? >>> # iNCREMENTALslICE >>> isl=lambda l,start,increment:l.__getslice__(start,start+increment) >>> l='zero one two three four five six'.split() >>> l ['zero', 'one', 'two', 'three', 'four', 'five', 'six'] >>> isl(l,3,3) ['three', 'four', 'five'] >>> Regards Peter From greg at cosc.canterbury.ac.nz Mon May 24 23:57:53 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 May 2004 15:57:53 +1200 Subject: GTK or TKinter (or what else?) In-Reply-To: <J5isc.8231$be.5948@newsread2.news.pas.earthlink.net> References: <SxZqc.10613$Wc.388888@twister2.libero.it> <J5isc.8231$be.5948@newsread2.news.pas.earthlink.net> Message-ID: <2hfui1Fch1lmU2@uni-berlin.de> Greg Krohn wrote: > You can do this: > >>> button = wx.Button(parent, -1, "Search") > >>> button.Bind(EVT_BUTTON, searchFunction) It would be nice if the need to pass all those -1s could be eliminated as well... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From nid_oizo at yahoo.com_remove_the_ Tue May 25 10:05:25 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 25 May 2004 10:05:25 -0400 Subject: Update with pickle Message-ID: <AoIsc.27189$tb4.933533@news20.bellglobal.com> Is it possible to use the pickle module to update an object instead of creating a new instance? Thx Nicolas From admin at na.org Wed May 5 03:33:48 2004 From: admin at na.org (admin at na.org) Date: Wed, 5 May 2004 00:33:48 -0700 Subject: Symantec Mail Security detected a virus based on a message you sent (SYM:38457866663665239367) Message-ID: <029c01c43273$4e533400$b0a8a8c0@na.org> Subject of the message: read it immediately Recipient of the message: Eileen Perez-Evans From paul at prescod.net Wed May 12 09:21:16 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 12 May 2004 06:21:16 -0700 Subject: sending out XML from python. In-Reply-To: <c7t82f$23h$1@sea.gmane.org> References: <03foc.111778$Jy3.44600@fed1read03> <3o2dnQnr_4xJDDzdRVn_iw@powergate.ca> <c7t82f$23h$1@sea.gmane.org> Message-ID: <40A224CC.8040406@prescod.net> Brad Clements wrote: > Also consider elementtree > > http://effbot.org/zone/element-index.htm > And pygenx, which is specifically designed for this task: http://software.translucentcode.org/pygenx/ And it wouldn't hurt to spend 20 minutes poking around Uche's treatises on the topic: http://www.xml.com/pub/a/2003/10/15/py-xml.html Paul Prescod From ville at spammers.com Wed May 12 02:20:09 2004 From: ville at spammers.com (Ville Vainio) Date: 12 May 2004 09:20:09 +0300 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> Message-ID: <du7hdum415y.fsf@amadeus.cc.tut.fi> >>>>> "Kirk" == Kirk Job-Sluder <kirk at eyegor.jobsluder.net> writes: Kirk> I've not found this to be the case due to Python's emphasis Kirk> on being explicit rather than implicit. My emulation of Kirk> "perl -pi -e" was about 24 lines in length. Even with the Kirk> improvement there is still 10 times as many statements where Kirk> things can go wrong. That's when you create a module which does the implicit looping. Or a python script that evals the passed expression string in the loop. Kirk> It is really hard to be more trivial than a complete program in one Kirk> command line. As has been stated elsewhere, you can do the trick on the command line. The effort to create the required tools only needs to be paid once. However, many times it won't matter whether the whole program fits on the command line. I always do a script into a file and then execute it. I just prefer a real editor to command history editing if something goes wrong. Kirk> It's a matter of task efficiency. Why should I spend a half Kirk> hour doing in python something that takes 1 minute if you Kirk> know the right sed, awk or perl one-liner? There is a level Kirk> of complexity where you are better off using python. But Kirk> why not use a one-liner when it is available? I think one should just analyze the need, implement the requisite module(s) and the script to invoke the stuff in modules. The needs have the habit of repeating themselves, and having a bit more structure in the solution will pay off. Kirk> Write me a two-line script in python that reads a character Kirk> delimited file, and printf pretty-prints all of the records Kirk> in a different order. (Already done) Kirk> Sometimes, a utility that uses an implicit loop over every line of a Kirk> file is useful. That's not emotional attachment, it's plain common Kirk> sense. The virtual of the implicitness is still arguable. -- Ville Vainio http://tinyurl.com/2prnb From darkbard at extending-php.net Tue May 11 14:48:22 2004 From: darkbard at extending-php.net (Gabriele Farina *DarkBard*) Date: Tue, 11 May 2004 18:48:22 GMT Subject: [wxPython] handling images Message-ID: <Wd9oc.175595$hc5.7592750@news3.tin.it> Hi, there is a way to handle images directly from wxPython? I'd like to manage simple image handling, like drawing only a portion of an image, switching between two colors or drawing only some pixels. there's a way to do it? bye From me at privacy.net Tue May 4 06:41:37 2004 From: me at privacy.net (Heather Coppersmith) Date: 04 May 2004 06:41:37 -0400 Subject: Question about glob.glob <--newbie References: <oKBlc.59079$Jy3.28147@fed1read03> <qnk1xm0evmg.fsf@arbutus.physics.mcmaster.ca> Message-ID: <m28yg8iie6.fsf@unique.phony.fqdn> On Mon, 03 May 2004 23:09:27 -0400, cookedm+news at physics.mcmaster.ca (David M. Cooke) wrote: > At some point, "Sean Berry" <sean_berry at cox.net> wrote: >>>>> r = glob.glob('/*') >>>>> r >> ['/dev', '/usr', '/stand', '/etc', '/cdrom', '/proc', '/bin', '/boot', >> '/mnt', '/modules', '/root', '/sbin', '/tmp', '/var', '/sys', '/COPYRIGHT', >> '/kernel.GENERIC', '/kernel', '/compat', '/home', '/kernel.old', >> '/modules.old'] >>>>> >>>>> r = glob.glob('/usr/websites/*') >>>>> r >> [] >> >> I can do a >>>>> import os >>>>> dirs = os.system('ls /usr/websites') >> >> and that works. Why doesn't glob.glob work on /usr/websites? > Somehow, I doubt that actually works. I'll bet that dirs == 0 -- os.system > returns the status code of the command, not the output. You'll want > commands.getoutput. > What are the permissions on /usr/websites? What does 'ls -l > /usr/websites' and 'ls -ld /usr/websites' give? Possibly picking a nit, but is there a difference between 'ls /usr/websites' (without the trailing slash) and 'ls /usr/websites/' (with the trailing slash)? Some OS's do strange things with some symbolic links and/or mount points based on the presence/absence of that slash. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From imbosol at aerojockey.invalid Thu May 20 02:21:51 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Thu, 20 May 2004 06:21:51 GMT Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <tyfu0yem07c.fsf@pcepsft001.cern.ch> <mailman.49.1084890435.6949.python-list@python.org> <HEyqc.132$Uq1.127@fe2.columbus.rr.com> <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> <7xfz9vamfh.fsf@ruckus.brouhaha.com> Message-ID: <38Yqc.166$eO6.128@fe2.columbus.rr.com> Paul Rubin wrote: > > > imbosol at aerojockey.com (Carl Banks) writes: >> > >>> a.bar = lambda x: x*x*x >> > >>> a.bar(3) >> > 27 >> >> Well, come on, of course there's going to be some things here and >> there you can do in one and not the other. In wat is Python dynamic >> that Lisp isn't to such an extent that it would cripple any attempts >> to compile it? > > The example above kills any attempt to turn a.bar() into a static > procedure call. Of course it does--but it's one method. A compiler, if it's good, would only make the optization on methods named "bar", and it could probably pare the number of possible classes it could happen to down to only a few. I mean you could have a Turing nightmare on your hands, with all kinds of crazy setattrs and execs and stuff, in both Python and Lisp, and then there's not much a compiler could do but emit totally general code. I assume Lisp compilers do this sometimes. > There's more like it, e.g. the existence of the > locals() dictionary and the ability to modify it. New feature? I didn't think modifying the dict returned by locals affected the variables. > However, it should > be possible to define a reasonable subset of Python that can compile > into good code. The stuff that makes compilation difficult makes the > code unmaintainable too. True, but even if you didn't do that, I think a compiler could do a decent job with reasonable code. > I do think that Python's designers should wait til PyPy with > native-code backends has been deployed for a while before defining too > much of Python 3.0, so we can first gain some experience with compiled > Python. Python should evolve towards being compiled most of the time. Agreed -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From no.mail at available.net Thu May 20 22:13:09 2004 From: no.mail at available.net (Georgy) Date: Fri, 21 May 2004 02:13:09 GMT Subject: Confused about while statement References: <dHcrc.86491$536.14466932@attbi_s03> Message-ID: <VAdrc.29500$zq4.2113760@twister.southeast.rr.com> h != "hello" or "goodbye" is (h != "hello") or "goodbye" It's always true because even if (h != "hello") evaluates to False, then "goodbye" is 'tested' and considered to be true. You probably meant: h != "hello" and h != "goodbye" that can be written even better as: h not in ("hello", "goodbye") Georgy "EAS" <eriksp at attbi.nospam.com> wrote in message news:dHcrc.86491$536.14466932 at attbi_s03... | In theory, the following code should ask for the user to enter a value for h | until he/she enters hello or goodbye. | | h = "hi" | while h != "hello" or "goodbye": | h = raw_input("Value for h:") | | But the program keeps asking for a value no matter what I enter. Why doesn't | it work? From mwh at python.net Tue May 18 07:13:31 2004 From: mwh at python.net (Michael Hudson) Date: Tue, 18 May 2004 11:13:31 GMT Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <Q3lqc.2178$eH3.47040@news4.e.nsc.no> Message-ID: <m37jvaf0o5.fsf@pc150.maths.bris.ac.uk> Svein Ove Aas <svein+usenet01 at brage.info> writes: > Leif K-Brooks wrote: > > > Svein Ove Aas wrote: > >> Is anyone working on a python-to-native compiler? > >> I'd be interested in taking a look. > > > > What are you trying to achieve? > > > > If it's faster code execution, the primary slowdown with a very > > high-level language like Python is caused by high-level data structures > > (introspection, everything being an object, etc.), not the code itself. > > A native compiler would still have to use high-level data structures to > > work with all Python code, so the speed increase wouldn't be very much. > > I'd like to point out the usual suspects: Lisp compilers. > *They* somehow manage to get within 2x of C++ speed, so why can't Python? Type declarations. Lots of effort by seriously smart cookies. We're working on the latter :-) Cheers, mwh -- > say-hi-to-the-flying-pink-elephants-for-me-ly y'rs, No way, the flying pink elephants are carrying MACHINE GUNS! Aiiee!! Time for a kinder, gentler hallucinogen... -- Barry Warsaw & Greg Ward, python-dev From greg at invalid.invalid Wed May 5 01:18:01 2004 From: greg at invalid.invalid (Greg Krohn) Date: Wed, 05 May 2004 05:18:01 GMT Subject: question: parameters for create_polygon() method In-Reply-To: <40986DD6.F06FF651@shaw.ca> References: <40984D5A.B819BF28@shaw.ca> <mailman.254.1083723811.25742.python-list@python.org> <40986DD6.F06FF651@shaw.ca> Message-ID: <dO_lc.7623$V97.1951@newsread1.news.pas.earthlink.net> SeeBelow at SeeBelow.Nut wrote: > Andrew Bennetts wrote: >>create_polygon(*list_of_points) >>-Andrew. > Thanks Andrew, but I don't understand it. What's that * thing? > Is there a * operator that converts a list of tuples into one big tuple? > > Mitchell Timin It treats the list (i.e. list_of_points) as if each element was passed as an argument to the function. In other words: l = [1, 2, 3] create_polygon(*l) is the same as create_polygon(1, 2, 3) greg From __peter__ at web.de Thu May 20 12:04:29 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 May 2004 18:04:29 +0200 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: <c8ikud$kgb$05$1@news.t-online.com> Jim Hefferon wrote: > I'm getting an error join-ing strings and wonder if someone can > explain why the function is behaving this way? If I .join in a string > that contains a high character then I get an ascii codec decoding > error. (The code below illustrates.) Why doesn't it just > concatenate? Let's reduce the problem to its simplest case: >>> unichr(174) + chr(174) Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position 0: ordinal not in range(128) So why doesn't it just concatenate? Because there is no way of knowing how to properly decode chr(174) or any other non-ascii character to unicode: >>> chr(174).decode("latin1") u'\xae' >>> chr(174).decode("latin2") u'\u017d' >>> Use either unicode or str, but don't mix them. That should keep you out of trouble. Peter From rowen at cesmail.net Thu May 13 19:26:22 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 13 May 2004 16:26:22 -0700 Subject: urllib hanging in thread References: <rowen-AB8751.13133104052004@nntp1.u.washington.edu> Message-ID: <rowen-344A91.16262213052004@nntp3.u.washington.edu> In article <rowen-AB8751.13133104052004 at nntp1.u.washington.edu>, "Russell E. Owen" <rowen at cesmail.net> wrote: >I am having trouble with some ftp code. On some platforms it works fine >and on others it reliably hangs.... After some experimentation, I found the hanging was occurring in ftplib. It delays importing re and compiling two regular expressions until they are needed, and the thread hangs both on the import and (if I modify ftplib to import re in advance) on the compilation. Modifying ftplib to do both jobs in advance (when first imported) fixes the problem. It seems strange to me that a thread could hang indefinitely trying to perform these two tasks when the rest of the app seems to be running fine. Perhaps the thread is simply being starved of cpu cycles, but then it seems odd that the thread has enough cycles to print diagnostics and do network communication. Anyway, I can work around the problem by using ftplib directly instead of using urllib, and importing my own patched ftplib. But I'm wondering if anyone has any better suggestions. -- Russell From aahz at pythoncraft.com Tue May 11 10:23:32 2004 From: aahz at pythoncraft.com (Aahz) Date: 11 May 2004 10:23:32 -0400 Subject: General Ledger/Accounting Libraries References: <mailman.422.1084270942.25742.python-list@python.org> Message-ID: <c7qnl4$f9p$1@panix2.panix.com> In article <mailman.422.1084270942.25742.python-list at python.org>, Andreas Pauley <python-list at qbcon.com> wrote: > >Our company is currently evaluating Python as a language for writing >financial/accounting type software (among others). > >What libraries or packages are available in this domain for use? The most important library is the new Decimal package, which hasn't been released for production yet. You could start by using FixedPoint instead until Python 2.4. Unfortunately, neither includes support for some of the more complicated calculations you want to do; the Python community will welcome your assistance on this (there are other people who also want to use Python for financial calculations, and Decimal is the first step). >On Sourceforge there's a PHP-based application called "Open Accounting" >with all the relevant buzzwords in our domain. Something similar in Python >would be of great help: >""" >An easy-to-use, web-based Accounting and Inventory system that features >Sales, Purchasing, Manufaturing, General Ledger, Accounts Receivable, >Accounts Payable. Additionally, has multi-currency, advanced tax >manipulation and multi-language support >""" They probably use binary floating point, which means that it doesn't work. :-( -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From slawek at cs.lth.se Wed May 19 17:59:33 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Wed, 19 May 2004 23:59:33 +0200 Subject: comparing strings and integers In-Reply-To: <3064b51d.0405191326.124a3ab3@posting.google.com> References: <3064b51d.0405191326.124a3ab3@posting.google.com> Message-ID: <20040519235515.0C6B.SLAWEK@cs.lth.se> On 19 May 2004 14:26:59 -0700 beliavsky at aol.com wrote: #> By mistake I coded something like #> print ("1" > 1) #> and got the result "True". Comparing an integer and a string seems #> meaningless to me, and I would prefer to have an exception thrown. #> Can someone explain why Python allows comparisons between integers #> and strings, and how it handles those cases? Why is "1" > 1? From the Python Reference Manual, chapter 5.9 Comparisons: """ 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.) """ #> Pychecker does not warn about the line of code above -- I wish it #> did. Good point - it probably would be nice if it did. I don't know if it is possible to check for such things in the general case, though. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Never argue with an idiot: first he will drag you down to his level, then he will beat you with experience. From jacek.generowicz at cern.ch Thu May 13 04:40:10 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 May 2004 10:40:10 +0200 Subject: __dir__ Message-ID: <tyffza4pvo5.fsf@pcepsft001.cern.ch> Is there some way of affecting the way dir finds the information it presents? For example, supposing a hypothetical __dir__ magic method: class collection: def __init__(self, myname, names): self.names = names self.myname = myname def __dir__(self): return ['%s(%s)' % (self.myname,n) for n in self.names] class thingy: def __init__(self, *names): self.it = collection('it', names) thing = thingy('this', 'that', 'theother') dir(thing) ['__doc__', '__init__', '__module__', 'it(this)', 'it(that)', 'it(theother)'] In other words, I would like some attributes of an instance to inject some information into the output of dir ... to change the way their names are perceived by dir. Any ideas ? From simonb at NOTTHISBIT.webone.com.au Sat May 15 04:14:18 2004 From: simonb at NOTTHISBIT.webone.com.au (Simon Burton) Date: Sat, 15 May 2004 09:14:18 +0100 Subject: pexpect module References: <mailman.17.1084557068.4157.python-list@python.org> Message-ID: <pan.2004.05.15.08.14.17.993257@NOTTHISBIT.webone.com.au> On Fri, 14 May 2004 19:50:54 +0200, Gianluca Trombetta wrote: > Someone know pexpect module? > I've a problem working with it... > > I need to run some commands on remote hosts, like ls, df -k etc..All > right. Although, when i launch a command that have a "more" inside, i > don't know what i must expect! Why don't you use a local more ? Or write your own "more" in python. Simon. From dyzma at mat.uni.torun.pl Mon May 17 09:56:02 2004 From: dyzma at mat.uni.torun.pl (Lukasz Indyk) Date: Mon, 17 May 2004 15:56:02 +0200 Subject: html to image or html to postcript to image Message-ID: <c8agcb$ihd$1@atlantis.news.tpi.pl> i want to convert html to image (format of the image does not matter). is it possible in python? or mayby it is possible to convert html first to the postscript, and then postscript to image? From kveretennicov at yahoo.com Fri May 28 02:46:07 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 27 May 2004 23:46:07 -0700 Subject: r'\' - python parser bug? References: <5155aad2.0405250137.1cd7c53e@posting.google.com> <LNBBLJKPBEHFEDALKOLCOEDLLEAB.tim.one@comcast.net><mailman.274.1085497902.6949.python-list@python.org> <8089854e.0405252339.18e0c59d@posting.google.com> <mailman.309.1085570754.6949.python-list@python.org> Message-ID: <5155aad2.0405272246.436235c4@posting.google.com> Many thanks to everyone for enlightening. Now i can see the reasons behind "no odd number of trailing backslashes" decision. Maybe they deserve to be appended to FAQ section on raw strings? Interestingly, C# did it the other way. Trailing backslashes in verbatim (raw) strings are allowed, but quotes are not: @"\" // ok @"\"" // error, unterminated string literal For me, personally, trailing backslashes aren't as important as quotes. Python wins again :) - kv From ocrow at skymind.com Sun May 2 13:35:00 2004 From: ocrow at skymind.com (Oliver Crow) Date: 2 May 2004 10:35:00 -0700 Subject: Efficient string concatenation methods References: <b3a34c4c.0405011643.70c163c3@posting.google.com> <Mc4lc.93415$K%2.5677129@phobos.telenet-ops.be> Message-ID: <b3a34c4c.0405020935.18962a86@posting.google.com> Roel Schroeven <rschroev_nospam_ml at fastmail.fm> wrote in message news:<Mc4lc.93415$K%2.5677129 at phobos.telenet-ops.be>... > > I'd like to try out another variant, but I'm unable to run your > script... Where does that timing module come from? I can't find it anywhere. It's George Neville-Neil's timing module. It looks like it used to be part of the python library, but has been removed in recent versions. I'm not sure why. Perhaps timeit is the new preferred module. > The method I propose is simply > > def method7(): > return ''.join(map(str, xrange(loop_count))) > > I ran my own little test and it seems to be faster than method6, but I'd > like to run it in your script for more reliable results. Also, I haven't > done any memory measurement, only a timing. I'll add that test and rerun the results. Thanks for the suggestion! Oliver From phrogeeb at hotmail.com Mon May 10 19:03:42 2004 From: phrogeeb at hotmail.com (Uri) Date: 10 May 2004 16:03:42 -0700 Subject: Writing Formatted txt to a file (xtreme newbie q) Message-ID: <8a0bb987.0405101503.2656788a@posting.google.com> I am working on a program that reads (through Tkinter and a form of text boxes, checkboxes, radio switches, sliders, etc) a set of values, saves them to a file, and is also capable of loading from the file so that the sliders switches checkboxes etc will have the paramaters defined in the text file (that last part is peripheral, eventual, but if there's something i have to do to set that up immediately I'd like to do that.) Right now, I'm basicly doing this in simple question-answer text no-GUI format. I've managed to set up the q&a scenario, and using a print statement set it up like I'd like it to go into the file (space-dileneated) However, I'm lost as far as writing it to the file in a formatted form. I've looked around, and I'm pretty sure I can rule out pickle as not what i want, but I'm having trouble figuring out what i do want. The data is in the format of a list right now (maybe a dictionary at some point) and there is one question and one answer per column. I would like to set it up as "Question: Answer" in side-by-side formatted columns, or perhaps "Question" over "Answer" in two rows, answers on bottom. Thanks in advance! (Also, is there a pretty popular web-based forum for python or no?) From r.gable at mchsi.com Mon May 24 20:22:02 2004 From: r.gable at mchsi.com (Ralph A. Gable) Date: 24 May 2004 17:22:02 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> <22b7fd40.0405240325.7b2b6376@posting.google.com> <10b4bgsimk120ce@corp.supernews.com> Message-ID: <22b7fd40.0405241622.2bbe748c@posting.google.com> Mike, Thanks ever so much. That worked and helps tremendously. Ralph A. Gable "Michael Geary" <Mike at DeleteThis.Geary.com> wrote in message news:<10b4bgsimk120ce at corp.supernews.com>... > Ralph A. Gable wrote: > > The data I want is being stripped out when I access the URL > > via urllib. I CAN see the data when I go into IE and do view > > source but when I use urllib the site intentionally blanks out > > the information I want. For that reason, I would like to get it > > using IE6 if I can. If there are other ways to fake out the site, > > I would be interested in that also. > > You may be able to get urllib or urllib2 to work using some of the other > tips in this thread, such as the user agent string. Or it may have to do > with cookies, in which case the ClientCookie module may be useful: > > http://wwwsearch.sourceforge.net/ClientCookie/ > > If you do want to use IE, it's really easy. Let's assume you have an ie > object that you've gotten with: > > ie = win32com.client.Dispatch( 'InternetExplorer.Application' ) > > and you've navigated to your URL using ie.Navigate( url ), and you've waited > for Navigate to finish. Then, you can get the document with: > > doc = ie.Document > > From there, you can get to anything. If you want the entire HTML source, > it's: > > doc.documentElement.outerHTML > > Or better yet, you can use the IE object model to let IE do the work of > parsing the HTML for you. For example, suppose the document contains a form > named 'loginForm' with 'username' and 'password' fields, and you want to > fill in those two fields and submit the form. You could do it with: > > form = doc.forms.loginForm > form.username = 'myname' > form.password = 'mypassword' > form.submit() > > Basically, you can use about the same code you'd use in JavaScript or Visual > Basic inside the web page. > > Here's the MSDN reference for the InternetExplorer object: > > http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/internetexplorer.asp > > And here's the reference for the document object: > > http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_document.asp > > (Sorry about the long URLs; you know what to do.) > > One other note: You probably already know about this, but after you do do > the Navigate, you need to wait until IE has loaded the page. You can either > use the NavigateComplete2 event, or it may be easier to cheat a bit and use > a loop with time.sleep() and test the ie.Busy property. I like to wait until > ie.Busy is false and remains false for a couple of seconds, to avoid being > tripped up by redirects where Busy may go false momentarily and then become > true again during the redirect. > > -Mike From m.boeren at guidance.nl Tue May 18 09:20:15 2004 From: m.boeren at guidance.nl (Marc Boeren) Date: Tue, 18 May 2004 15:20:15 +0200 Subject: gdesklets ? Message-ID: <0C77C7530EA52A4EBD1C47C80D1D291E07F8EF@sbs.GuidanceBV.local> Hi, > why I should write : > self.__percent = int((float(self.__diff) / float(self.__max)) * 100) > > instead of just : > > self.__percent = int((self.__diff / self.__max) * 100) look at this trick (multiply first, divide later): >>> diff = 10 >>> max = 100 >>> diff/max * 100 // your approach without casts 0 >>> diff*100/max // trick approach without cast 10 >>> diff = 10.1 >>> diff/max * 100 10.1 >>> diff*100/max 10.1 >>> Both aproaches work if either diff or max is a float already, except for making the final value an integer again. (btw, I shouldn't have used max as a variable name, but then again, it's just an example :) Cheerio, Marc. From do at linux.darktower.net Sat May 29 14:09:56 2004 From: do at linux.darktower.net (Dominique Orban) Date: Sat, 29 May 2004 18:09:56 GMT Subject: Sqlite syntax References: <mailman.17.1084816067.6949.python-list@python.org> <c96v2t$f3p$1@newstree.wise.edt.ericsson.se> Message-ID: <slrncbhobh.4cc.do@linux.darktower.net> On 2004-05-28, Frithiof Andreas Jensen <frithiof.jensen at die_spammer_die.ericsson.com> wrote: > > "firephreek" <firephreek at earthlink.net> wrote in message > news:mailman.17.1084816067.6949.python-list at python.org... > >> Is there some documentation out there that actually lists the Sqlite >> syntax? > > http://sqlite.org/lang.html > >> Or even better, one that crosses over and talks about how it works with >> python? > > That be mainly here: http://www.python.org/topics/database/ under > http://www.python.org/peps/pep-0249.html See also http://pysqlite.sf.net Their website in a bit on the brief side as the documentation is being updated, but check out the mailing list for examples on how to use it. It is a most convenient and powerful interface with intuitive commands. You ought to check it out! >> And since the databases aren't 'centralized' there's no way of knowing >> what databases I have floating around is there? > > It is "lite" - which means that you have to remember where you put stuff ;-) > A ConfigParser object is a good place to keep track of that sort of thing. > > From jepler at unpythonic.net Sat May 15 19:28:21 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 18:28:21 -0500 Subject: tkinter button widget In-Reply-To: <Ygxpc.492595$Ig.75690@pd7tw2no> References: <Ygxpc.492595$Ig.75690@pd7tw2no> Message-ID: <20040515232821.GG2832@unpythonic.net> PS To indicate to the user that hitting the Enter key will invoke a particular button, create the widget with default="active". Jeff From cm at leetspeak.org Fri May 14 07:25:22 2004 From: cm at leetspeak.org (Michael Walter) Date: Fri, 14 May 2004 13:25:22 +0200 Subject: Stackless python and microthreads In-Reply-To: <95aa1afa.0405140121.52a6d8e0@posting.google.com> References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> Message-ID: <2gjokgF3mvvdU1@uni-berlin.de> > My experience with continuations (in Scheme) is limited, but I really > wonder if continuations have a place in a high level programming language. > I mean, continuations are basic building blocks: you can build on top > of them exception systems, generators, coroutines, microthreads, etc, > and it is an interesting learning experience to understand how this is > done. Yeah exactly, they are one reason which allows Scheme to be really high-level. They're pretty useful for web applications, too -- the difference to above-mentioned examples would be that IMHO there is no adequate alternative to them in current Python. > However, to pass from continuations to something useful takes a > LONG way. Continuations are a too low level concept. That probably depends on the point of view. I don't think it matters much whether a specific feature is built-in into the language as such or part of the/a standard library. > A high level language should already provide the right high level tools. I mean, > the language designer should implement generators, exception systems, microthreads, etc. > not the application programmer. When you have the high level concepts written > down by others, you don't need continuations. Would you have an idea on how a higher-level replacement for continuations in web application development? I'm excited (and _not_ being any sarcastic or stuff, honestely!). > Speaking in general, generators and the current exception system are more > than enough for my typical needs in Python: which kind of applications do > you have in mind where you would like to have continuations? (a part from > microthreads and things like changing the language introducing new > control structures, etc, all stuff than should not be left to the > application programmer, IMHO). Web application development involving Continuations (such as in Seaside, the PST web server etc.). Cheers, Michael From tzot at sil-tec.gr Tue May 11 14:36:19 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 11 May 2004 21:36:19 +0300 Subject: OT: Idea for Python T-shirt References: <ppj1a09ee7766t94o439qd2bgbc18resg1@4ax.com> <JpqdnYIeR4GMRT3dRVn-gg@powergate.ca> <mailman.433.1084291533.25742.python-list@python.org> Message-ID: <5872a0p7abq8gikvng22q1gqpo2orhnuld@4ax.com> On Tue, 11 May 2004 17:07:04 +0100, rumours say that Richie Hindle <richie at entrian.com> might have written: > >[Christos] >> "With Python your nibbles explode with desire" > >[Peter] >> Also, I don't get it... > >Both you and Christos need to brush up on your Monty Python: > >http://www.intriguing.com/mp/_scripts/phrasebk.txt (about halfway down) Right! It was "delight", not "desire"! Thank you Richie... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From rogerb at rogerbinns.com Sat May 8 00:36:45 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 7 May 2004 21:36:45 -0700 Subject: Multi-threaded printing and IOErrors in Windows (py2exe) References: <10nll1-rt5.ln1@home.rogerbinns.com><c6acl7$7u8$1@ctb-nnrp2.saix.net><ri4nl1-n9d.ln1@home.rogerbinns.com> <mailman.968.1082739673.20120.python-list@python.org> Message-ID: <qn4um1-iq1.ln1@home.rogerbinns.com> Thomas Heller wrote: > "Roger Binns" <rogerb at rogerbinns.com> writes: > > The bizarre thing is that the IOError is very infrequent, > > but very annoying when it happens. > > If you have a small program which allows to reproduce this, I'll look > into it. I cannot get it to repeat with test programs I have written (and boy have I tried). Not very many users reported the problem. It is probably some sort of race condition somewhere, and possibly only occurs on slower machines. My real program has many wxPython OnIdle handlers which is predominantly where the error shows up combined with a background thread doing heavy serial port activity to a cell phone, also doing prints. Is it possible for py2exe to replace stdout with something that just ignores all writes, as opposed to None (or is that what is already happening). Roger From lbates at swamisoft.com Thu May 6 16:03:45 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 6 May 2004 15:03:45 -0500 Subject: classes vs dicts References: <be05f1d.0405060212.43929fe1@posting.google.com> Message-ID: <V_idnQ4n1IviAQfdRVn-ig@comcast.com> You will probably want a dictionary with keys to find people with classes stored to hold the information about the people. That way you can extend the class easily without disrupting your data structures. class person: def __init__(self, lastname, firstname, initial): self.lastname=lastname self.firstname=firstname self.initial=initial return # # Main Program # all_people={} all_people['LarryABates']=person('Larry','Bates','A') all_people['SomeOPerson']=person('Some','Person','O') Then you can do things like: all_people['LarryABates'].telephone="2055551234" all_people['LarryABates'].faxphone="2055551235" or entry=all_people['LarryABates'] print entry.lastname print entry.firstname print entry.initial print entry.telephone entry.emailaddress="name at domain.com" I was new to OOP and it took me the longest to understand that I can store classes just like any other data value. HTH, Larry Bates Syscon, Inc. "Charlie" <charlvj at yahoo.com> wrote in message news:be05f1d.0405060212.43929fe1 at posting.google.com... > Greetings, > > I am pretty new to Python and like it very much, but there is one > thing I can't figure out and I couldn't really find anything in the > docs that addresses this. > > Say I want to write an address book program, what is the best way to > define a person (and the like): create a class (as I would do in Java) > or use a dictionary? > I guess using dictionaries is fastest and easiest, but is this > recommended? > > Thanx for any help. From Mike at DeleteThis.Geary.com Wed May 26 18:58:02 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 26 May 2004 15:58:02 -0700 Subject: Current drive and directory References: <LP7tc.64476$gr.6380832@attbi_s52> <mailman.341.1085607489.6949.python-list@python.org> <x_8tc.29053$af3.1599546@attbi_s51> Message-ID: <10ba87rk2bjhb89@corp.supernews.com> > print """MS-DOS Prompt > 'Q' to Quit""" > > import os > command = "" > > while command.lower() != "q": > directory = os.getcwd() > print "\n", directory, "\b>", > command = raw_input("\b") > os.system(command) > And also, when I actually run the program, I have trouble using > notepad on files: > > MS-DOS Prompt > 'Q' to Quit > > C:\Documents and Settings\Erik\Desktop>cd \windows\system32 > > C:\Documents and Settings\Erik\Desktop>notepad calc.py > > It opens up notepad, but syas that it can't find the file. I know it's in > there, and I know that's the exact name. > Ok, I guess that won't work without some complicated scripting, but > is there a command in DOS that shows the current directory? (so i > could just type it in when using the prompt.) The CD command with no arguments does that. Same as pwd in Unix. In this case, it should print the same thing as your prompt: C:\Documents and Settings\Erik\Desktop. BTW, you're not running MS-DOS at all. It appears that you are on Windows 2000 or XP, so when you call os.system() you are calling cmd.exe, which is a 32-bit console application, not a DOS application. And you're starting a new, temporary instance of cmd.exe for each command, which is why your CD command isn't having any effect. What directory is calc.py in? \windows\system32 or your desktop? When you do the "notepad calc.py" it is looking for calc.py in C:\Documents and Settings\Erik\Desktop (your desktop), because that is your current directory. If you do a File/Save... in Notepad you can confirm what Notepad is using for the current directory. What is it you are trying to do here? Maybe there is another way to approach it that will work better. -Mike From kr9999 at sinamail.com Tue May 25 17:18:18 2004 From: kr9999 at sinamail.com (kr) Date: Wed, 26 May 2004 05:18:18 +0800 Subject: Help:What does this mean? Message-ID: <c90d6k$c0h$1@wisteria.csv.warwick.ac.uk> Hello, I am new to PytonWin. I have a simple script, just one line-- print "hello". It runs OK when I use File/Run But in command line >> Script1.py I got the error msg: Traceback (most recent call last): File "<interactive input>", line 1, in ? NameError: name 'Script1' is not defined What's wrong with it? How can I fix it? THKS kr From tkpmep at hotmail.com Mon May 24 11:57:20 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 24 May 2004 08:57:20 -0700 Subject: Passing parameters to functions Message-ID: <b4a8ffb6.0405240757.2e0c5ef@posting.google.com> The following program passes parameters (inluding another function) into a function. def f(myfunc,m=3,*numbers): sumSquares=myfunc(*numbers[:m]) print sumSquares def sumofsquares(*args): total = 0 for i in args: total += i**2 return total f(sumofsquares,m=2,1,2,3,4,5) I have two questions: 1. When I run it, Python gives me the following error message: Syntax error. There's an error in your program: *** non-keyword arg after keyword arg I get exactly the same error message if I edit the code and put the keyword argument first, i.e. def f(m=3,myfunc,*arguments): It, however, works correcly if I rip "m=2" out of the function call and write f(sumofsquares,2,1,2,3,4,5). The error message is not very helpful - surely everything after the m=2 should be swept into *arguments. What's the error in my logic? 2. f passes *arguments[:m] into sumofsquares. It appears to be passing a pointer. But Python doesn't have pointers (except perhaps in its implentation), so what is it really doing? Is it just sheer dumb luck that makes my code work? I could logically define sumfsquares via def sumofsquares(args): . and call it with sumSquares=myfunc(arguments[:m]) but I am curious as to why my original form worked at all. Thomas Philips From seefeld at sympatico.ca Wed May 19 10:54:49 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 19 May 2004 10:54:49 -0400 Subject: embedded python - mpatrol output In-Reply-To: <dbeccbeb.0405190633.67817664@posting.google.com> References: <dbeccbeb.0405190633.67817664@posting.google.com> Message-ID: <VCKqc.52028$325.1227778@news20.bellglobal.com> temp1111 wrote: > Hi > > Further to my earlier post we're getting the following output when > embedding a python application > in C++ > > If there is any obvious cause please let us know. > > The version of python is 2.2.1 > > Regards > > > > ERROR: [RNGOVF]: memcpy: range [0x017B8540,0x017B8AA7] overflows > [0x017B8540,0x017B8A18] > 0x017B8540 (1241 bytes) {malloc:222432:0} [9|-|-|-] > 0xFE7CF8D0 __builtin_new+224 > 0xFE7CF9C4 __builtin_vec_new+12 > 0xF1AB6B3C ??? > 0xF1AB8868 ??? > 0xFE8FD4D4 PyCFunction_Call+372 Is that a call into a function of yours ? I.e. one that you could set a breakpoint into with your debugger ? This looks like (builtin) 'new' calling 'malloc' calling 'memcpy', which complains because it tries to copy a large block into a small one. If that's from a memory corruption error, the cause could be anywhere in your program. Regards, Stefan From uche at ogbuji.net Mon May 10 12:38:31 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 10 May 2004 09:38:31 -0700 Subject: Problem with xml.dom parser and xmlns attribute References: <c682uu$sco$1@swifty.westend.com> Message-ID: <d116fbae.0405100838.3d001aed@posting.google.com> Peter Maas <peter.maas at mplusr.de> wrote in message news:<c682uu$sco$1 at swifty.westend.com>... > Hi, > > I have a problem parsing html text with xmldom. The following code > runs well: > > -------------------------------------------- > from xml.dom.ext.reader import HtmlLib > from xml.dom.ext import PrettyPrint > > r = HtmlLib.Reader() > doc = r.fromString( > ''' > <html> > <head> > </head> > <body> > <p>hallo welt > </body> > </html> > ''') > PrettyPrint(doc) > -------------------------------------------- > > but if I replace <html> by <html xmlns="http://www.w3.org/1999/xhtml"> > I get the error > > Traceback (most recent call last): > File "xhtml.py", line 5, in ? > doc = r.fromString( > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 69, in fromString > return self.fromStream(stream, ownerDoc, charset) > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 27, in fromStream > self.parser.parse(stream) > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\Sgmlop.py", line 57, in parse > self._parser.parse(stream.read()) > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\ext\reader\Sgmlop.py", line 160, in finish_starttag > unicode(value, self._charset)) > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\Element.py", line 177, in setAttributeNS > attr = self.ownerDocument.createAttributeNS(namespaceURI, qualifiedName) > File "C:\PROGRA~1\Python23\lib\site-packages\_xmlplus\dom\Document.py", line 139, in createAttributeNS > raise NamespaceErr() > xml.dom.NamespaceErr: Invalid or illegal namespace operation > >Exit code: 1 > > A lot of HTML documents on Internet have this xmlns=.... Are > they wrong or is this a PyXML bug? This looks like a 4DOM bug. What are you hoping to do once you've parsed these documents? If we know we can either suggest an alternative tool to use or perhaps a workaround. --Uche From jfabiani at yolo.com Tue May 18 10:10:45 2004 From: jfabiani at yolo.com (john fabiani) Date: Tue, 18 May 2004 14:10:45 GMT Subject: module for working with the result set In-Reply-To: <2gu341F67e61U1@uni-berlin.de> References: <EO4qc.276$gK2.225@newssvr27.news.prodigy.com> <c8ao3c$mh5$03$1@news.t-online.com> <Dl6qc.300$y13.206@newssvr27.news.prodigy.com> <c8aus7$8ch$01$1@news.t-online.com> <_wbqc.68175$eT6.35900@newssvr25.news.prodigy.com> <c8blsm$cp4$05$1@news.t-online.com> <0hdqc.50042$lI4.2638@newssvr29.news.prodigy.com> <2gu341F67e61U1@uni-berlin.de> Message-ID: <FPoqc.50393$Le3.30349@newssvr29.news.prodigy.com> Diez B. Roggisch wrote: >>OK thats great! I did the following and it works. >>for field in range(0,len(mydata[0])): >> print mydata[0][field] >>following your thoughts on the keys and my mistake - can you tell me how >>to get into a dict format? > > > Its a one-liner: If fnames is the list of column names (remember you can get > these from the cursor) and row is your data, this will create a dict out of > them: > > d = dict(zip(fnames, row)) > > Thats all. > > I'm missing something very important about list and dict because your one liner does not work. This is what I did: myfields=mycur.description #since I already had the data I used it. d = dict(zip(myfields,mydata[0])) Traceback (most recent call last): File "<input>", line 1, in ? TypeError: list objects are unhashable So "myfields" is a list within a list. I'm able to list the fields with the following: for count in range(0,len(myfields)): print myfields[count][0] The above will print the fields name - which is what I want to become my keys. So now I have to make what is printed into a list. mylist=[] for count in range(0,len(myfields)): mylist.append(myfields[count][0]) now I have a single list. ['csono', 'crevision',............] then I'd expect your code to work but I get a list of tuples [('csono', '5992 '), ('crevision', 'A') ......] What I expected to see was {'csono': '5992 '...} So now I'm completely confused.... But I guess I'm learning.... John From sean_berry at cox.net Thu May 27 17:31:11 2004 From: sean_berry at cox.net (Sean Berry) Date: Thu, 27 May 2004 14:31:11 -0700 Subject: CGI newb... redirect page References: <Ayqtc.49$VI2.1@fed1read02> <mailman.377.1085690181.6949.python-list@python.org> Message-ID: <B6ttc.497$VI2.37@fed1read02> "Phil Frost" <indigo at bitglue.com> wrote in message news:mailman.377.1085690181.6949.python-list at python.org... > To do a redirect, you can simply do something such as: > > print 'Location: http://new.absloute/url\r\n\r\n' > print ''' > This is some html that people will never see, but generally it should > include a link to the target url''' > sys.exit() > > Note that to be RFC compliant, you must give an absloute URL, although > relative ones work usually. > > Furthermore, there is no reason you should have to write a script to do > redirects for error pages. See the documentation on apache.org: > > http://httpd.apache.org/docs-2.0/mod/core.html#errordocument > > You can have apache use any local file, or even redirect to another > server. > > On Thu, May 27, 2004 at 11:36:17AM -0700, Sean Berry wrote: > > Hi there. I am relativly new to Python CGI and need a question answered. > > > > I have made custom 404 error pages and have them in various web directories. > > > > I have not been able to figure out a way to have apache use a file not > > within it's own > > home directory, so I was going to have a .py file in cgi-bin forward the > > user on to the > > correct error page. > > > > So I have say, > > /usr/www/client1/not-found.shtml > > and... > > /usr/www/client2/not-found.shtml > > > > I found that cgi.print_environ() gave me the SERVER_NAME, which is what I > > want. > > But, this is part of a long html formatted string that cgi.print_environ() > > returns. > > > > Is there something builtin to deal with these name, value pairs as a > > dictionary? > > I looked throught the docs, but did not see this functionality. > > > > Also, when I do extract this info... how do I actually do a redirect to a > > certain page > > > > Example. > > User goes to www.client1.com/page_not_on_server.html > > The apache conf file sends the redirect to /cgi-bin/redirect.py > > Redirect.py extracts the requesting server, client1.com, then > > redirects them to www.client1.com/not-found.shtml. > > > > Thanks for your help. > Thanks very much for your response. The reason that I am using a script is because I tried the line: ErrorDocument 404 not-found.shtml ... and ... ErrorDocument 404 /not-found.shtml There is a not-found.shtml file in each domains home web directory. This, however, did not work. It reverted to the generic version of a 404 error page. I figured that it was trying to look in the apache root directory for the file, not the root of the domains web directory. So, using this script, it will forward the user to the correct not-found.shtml page. I tried looking through the apache docs, but did not see anything limiting what type of alternate could be used. Anything you can think of that I may be overlooking? Thanks for your response. From tjreedy at udel.edu Mon May 10 12:20:12 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 May 2004 12:20:12 -0400 Subject: function causing core dump References: <c7o6al$i1j$1@online.de> Message-ID: <c7oa3u$ut$1@sea.gmane.org> "Xaver Hinterhuber" <xaver_hinterhuber at web.de> wrote in message news:c7o6al$i1j$1 at online.de... > codeObject = new.code( > 0, # argcount > 0, # nlocals > 0, # stacksize > 0, # flags > codeString, # code > (), # consts > (), # names > (), # varnames > 'content', # filename > 'content', # name > 3, # first line number > codeString # lnotab > ) > f = new.function(codeObject, dict, 'f') > f() > > Everything runs fine, until the function is called with f(). > When python tries to execute f(), the core dump happens. > I don't have any clue why python core dumps. > The codeString is nothing complex, its a one-liner. From sympa at ens.fr Tue May 25 03:41:00 2004 From: sympa at ens.fr (SYMPA) Date: Tue, 25 May 2004 09:41:00 +0200 (CEST) Subject: Results of your commands Message-ID: <200405250741.i4P7f0qk066928@nef.ens.fr> > here is the document. Command not understood: ignoring end of message. No command found in message From sross at connectmail.carleton.ca Sat May 8 09:56:26 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 8 May 2004 09:56:26 -0400 Subject: Help me. How to open a new IE window? References: <c7iaqu$2400$1@news.f.de.plusline.net> Message-ID: <9L5nc.100567$ZJ5.2249286@news20.bellglobal.com> "angel" <dai4happy at yahoo.com> wrote in message news:c7iaqu$2400$1 at news.f.de.plusline.net... > Hi > > I want python(win32com) to open a new IE window. > Source is: > /******/ > import win32com.client > msie = win32com.client.Dispatch("InternetExplorer.Application") > msie.Visible = 1 > msie.Naviagte(http://www.python.org) > /******/ > The problem is the program always grabs a existed IExplorer window or > Explorer window. It never opens a new window. > > Please help me. Thanx > Victor > Hi. Perhaps you may want to check out the webbrowser module: >>> import webbrowser as browser >>> browser.open("www.python.org", new=True) OR >>> browser.open_new(url) OR >>> IE = browser.WindowsDefault() >>> IE.open_new(url) HTH, Sean From peter at engcorp.com Thu May 20 11:48:39 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 11:48:39 -0400 Subject: Documentation/Info on this sign In-Reply-To: <c8iims$24i$1@solaris.cc.vt.edu> References: <c8iims$24i$1@solaris.cc.vt.edu> Message-ID: <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> Bart Nessux wrote: > Could someone point me to documentation on this (and similar) signs used > in Python: > > += http://docs.python.org/ref/augassign.html > Usage would be: > > x = += len(y) What do you mean by this? "Usage would be"... ? > Literally, that's "variable x equals > 'funky-symbol-that-I-want-to-learn-about' the length of variable y" Huh? This doesn't have meaning... both = and += are assignment statements, so you can't put one right after the other. What are you trying to do? -Peter From theller at python.net Fri May 14 15:23:18 2004 From: theller at python.net (Thomas Heller) Date: Fri, 14 May 2004 21:23:18 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 References: <ABADC7F2A1794A4C94657344DC1050930648BB5B@BRDEL-EXCH02.na.blkint.com> Message-ID: <u0yi7qzd.fsf@python.net> >> >>WINDOWS >>... Windows users may also be >>interested in Mark Hammond's win32all, a collection of >>Windows-specific extensions including COM support and Pythonwin, an >>IDE built using Windows components. >> "Hornberger, Chris" <Chris.Hornberger at blackrock.com> writes: > PS... I have moral and ethical arguments against this. I believe it's > just plain WRONG to use a language like Python or Java or even C#/.NET > and RELY on platform specific "extensions". > > If it ain't cross platform, then it's VB. What gives you the right to say this? *I'm offended.* Speaking of moral and ethics, there seem to be other things to care about, especially these days. Thomas From davidf at sjsoft.com Mon May 24 10:38:02 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 24 May 2004 16:38:02 +0200 Subject: how to terminate a process on win32? In-Reply-To: <mailman.164.1085188722.6949.python-list@python.org> References: <mailman.164.1085188722.6949.python-list@python.org> Message-ID: <c8t0va$cfh$1@ctb-nnrp2.saix.net> Joe Wong wrote: > Hi, > > I am developing two app on Windows, one is a GUI using wxPython and the > other is like a daemon process. The GUI app will have a start/stop > button to control the excution of the daemon. While I know how to use > os.popen2() to start my daemon, I can't figure out a way to stop it > 'nicely'... Is there anything that I can do? > > Regards, > > -- Wong > You can use the win32process.TerminateProcess function to kill a process... see the win32 docs David From brian at sweetapp.com Tue May 25 13:53:48 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 25 May 2004 19:53:48 +0200 Subject: Vancouver Python User's Group meeting Tuesday, June 1 In-Reply-To: <mailman.1083681542.24520.clpa-moderators@python.org> References: <mailman.1083681542.24520.clpa-moderators@python.org> Message-ID: <40B3882C.6010406@sweetapp.com> This meeting: ============= The long-awaited, many times delayed talk by our own Andy McKay: what is Plone and why is it taking over the world? Afterwards we'll retire to a nearby pub for the usual informal discussion of Andy's presentation and the upcoming Vancouver Python Workshop. Time: Tuesday, June 1 at 7:00pm Location: ActiveState (580 Granville St., Vancouver) The group: ========== The Vancouver Python and Zope User's Group is a group of Python enthusiasts who meet once a month to discuss various Python and Zope technologies and projects. For more information about the Vancouver Python and Zope User's Group, see: http://www.vanpyz.org/ For information about the upcoming Vancouver Python Workshop, see: http://www.vanpyz.org/conference/ Cheers, Brian From grante at visi.com Mon May 10 15:41:18 2004 From: grante at visi.com (Grant Edwards) Date: 10 May 2004 19:41:18 GMT Subject: What I don't like about wxPython References: <ec6dce8b.0405081140.16b8143d@posting.google.com> <e-qdnaru-auezgDdRVn-jA@powergate.ca> <oyfnc.2626$GL4.1289@fe2.columbus.rr.com> Message-ID: <slrnc9vmmu.7kl.grante@grante.rivatek.com> On 2004-05-09, Carl Banks <imbosol at aerojockey.invalid> wrote: >>> Just thought I'd play devil's advocate... >>> >>> I tried wxPython briefly, and it had some nice features. >>> >>> It has a huge list of dependencies. >> >> 1. Python. >> 2. Windows. > > The Unix version requires at least Python, gtk, and wxlib. Gtk is > technically three libraries: gtk, gdk, and glib. gdk depends on > libpng, probably also libjpeg. The latest version has all kinds of > i18n dependencies. Yup. Trying to get wxPython installed can be a pretty frustrating experience. After spending a couple hours trying to get a 2.5 version of wxPython installed on Mandrake 9.2, I finally gave up, wiped my disk, and installed Mandrake 10.0. It still doesn't come with wxPython 2.5, but it has enough of the required stuff that I don't have to build 10-15 new packages to get there... -- Grant Edwards grante Yow! .. I have a at VISION! It's a RANCID visi.com double-FISHWICH on an ENRICHED BUN!! From ml at dynkin.com Tue May 4 17:49:05 2004 From: ml at dynkin.com (George Yoshida) Date: Wed, 05 May 2004 06:49:05 +0900 Subject: Python sets. In-Reply-To: <Pine.LNX.4.44.0405041335170.29617-100000@e5-05.ee.ualberta.ca> References: <Pine.LNX.4.44.0405041335170.29617-100000@e5-05.ee.ualberta.ca> Message-ID: <c7934h$26d7$1@dojima-n0.hi-ho.ne.jp> Grzegorz Dostatni wrote: > I've got a problem. > > Some time ago (I'm a bit fuzzy about the date) I read about sets in > python. I even tried the code. I remember it was something fairly simple - > just a base data type (like list or dictionary). I vaguely remember it > had a syntax similar to creating dictionaries. > > Problem is I can't find it anymore. I've searched around, but it doesn't > seem to exist. I know of "import sets" and creating classes like that, but > I'm sure it was a base data type. No import necessary. There were > operators for basic set operations like set difference, division, etc. > I guess you're talking about built-in set type. But be warned that it will be introduced in Python 2.4, so if you want to try it right now, you need to compile it with yourself from the CVS source tree. Following links might help: * PEP : Adding a Built-In Set Object Type http://www.python.org/peps/pep-0218.html * What's New in Python 2.4 : Built-In Set Objects http://www.python.org/dev/doc/devel/whatsnew/node2.html -- George From fumanchu at amor.org Wed May 26 19:35:17 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 26 May 2004 16:35:17 -0700 Subject: Some Newbie Questions - Runtime import declarations Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E562133@opus.amorhq.net> Leopold Schwinger wrote: > (2) Is there any way to dynamically import modules, where the name > of the module is not known during implementation but can be defined > during scipt execution? Not just modules, but classes, functions, and module atributes can be loaded with my xray module: http://www.aminus.org/rbre/python Hope that helps, Robert Brewer MIS Amor Ministries fumanchu at amor.org From BruceWhoHKL at gawab.com Thu May 20 21:57:50 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Fri, 21 May 2004 09:57:50 +0800 Subject: Freeze and Resume execution Message-ID: <mailman.108.1572213697.32708.python-list@python.org> I come across the same problem. What I want to do is to write a vim script to debug python script. Bdb(exactly, a derived class of Bdb) will be called, and when it break at some breakpoints, it must freeze, and come back to vim, then later, user will call 'step' or 'trace' or 'continue', then Bdb will be called again and resume. Just last week I posted a mail to ask, but it seems that it's impossible to do it. >Hello All, > >I'm looking for a way to "yield" an exception. > >Background: I'm writing a hardware simulator. I have an output buffer >and need to freeze when it's full and then when called again to resume >execution from the point where it stopped. > >Currently all I can think of is to use a class and save the state when >throwing an exception. However this required manual book keeping of the >current state (and it is complicated). > >I'd like to use generators but can't see any "nice" way of doing it. >What I'd like it to throw an exception when the buffer is full and then >next time the generator is called to continue execution as after a >"yield". > >Is this possible? >Can you recommend a good way of doing this? Any state machine? > >Thanks. >Bye. >-- >------------------------------------------------------------------------- >Miki Tebeka <miki.tebeka at zoran.com> >http://www.cs.bgu.ac.il/~tebeka >The only difference between children and adults is the price of the toys. > > >-- >http://mail.python.org/mailman/listinfo/python-list > = = = = = = = = = = = = = = = = = = = = ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-21 From frnknstn at iafrica.com Wed May 5 17:19:08 2004 From: frnknstn at iafrica.com (Peter Finlayson) Date: Wed, 05 May 2004 23:19:08 +0200 Subject: question: parameters for create_polygon() method In-Reply-To: <20040505074742.GF20777@frobozz> References: <40984D5A.B819BF28@shaw.ca> <mailman.254.1083723811.25742.python-list@python.org> <40986DD6.F06FF651@shaw.ca> <mailman.259.1083733896.25742.python-list@python.org> <c7a2rg$nlq$01$1@news.t-online.com> <20040505074742.GF20777@frobozz> Message-ID: <40995A4C.8030705@iafrica.com> Andrew Bennetts wrote: > Odd, though -- I thought that calls that put non-keyword args after > keyword args were a syntax error I thing that is because the standard form for the calls are: def mydef(arg1, arg2, *args, **keywords) ie with the arbitrary argument lists after the formal args. Peter Finlayson From ajsiegel at optonline.com Mon May 24 03:35:05 2004 From: ajsiegel at optonline.com (Arthur) Date: Mon, 24 May 2004 07:35:05 GMT Subject: terminological obscurity References: <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> <1085378050.309299@yasure> Message-ID: <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> On Mon, 24 May 2004 05:54:11 -0000, "Donn Cave" <donn at drizzle.com> wrote: > >It's too bad if he said that. I think it has not led to mass confusion >because if one interpretation of that 10 word summary makes it an utterly >absurd proposition, most people are inclined to give him enough credit >to look for another interpretation. We agree as to the dynamics at work. But seem to have different feelings about it. I honestly don't know what he meant here, or how seriously he meant it. But there have been other instances, on other issues, where it has been clearer to me what he meant. Some of those issues were of more significance, to me, than this. And guess what, it was my conclusion that he was simply and utterly wrong. And felt myself to be arguing within a community that seemed to find it necessary to find him right, by any means necessary. Even where it took the form, in my eyes, of bizarre contortions and the defiance of common sense It - as I had said at the time - gave me the willies. Art From miki.tebeka at zoran.com Sun May 9 07:01:02 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 09 May 2004 13:01:02 +0200 Subject: Several questions about embedding Python In-Reply-To: <409AA071.2041F54E@free.fr> References: <c79ucp$4i6$1@news2.netvision.net.il> <409AA071.2041F54E@free.fr> Message-ID: <409E0F6E.9080006@zoran.com> Emmanuel wrote: >>1. Is there a way (using SWIG/Boost.Python ...) to export existing C/C++ >>functions other than hand writing the wrapper functions. >>Something like: py_export(a_c_function) >>Since the Python module need to get information from the simulator I >>can't just write pure SWIG wrapper (or can I?) > > > ? I don't understand... > Just have a header file with the function you want to call from Python, and > let SWIG parse it. That's what I'm doing... Yes. But the Python code is on the DLL generated by SWIG and the functions it needs to call are part of the main executable. >>2. How do I debug the Python code? Since the interpreter is called from >>the simulator application I can't run `pdb' on it. > > > I used HAP editor/debugger, that can be quite simply included in a embedded > app. > But I must admit there are still some bugs in it, and I'm not sure it's > still actively developped... Thanks! I'll check it out. >>3. Why on does pyconfig.h decides that `python23_d.lib' should be used >>when _DEBUG is on (IMO is should use Py_DEBUG)? I'm debugging *my* >>application not Python. > You should use : > #ifdef _DEBUG > #undef _DEBUG > #include "python.h" > #define _DEBUG > #else > #include "python.h" > #endif > > instead of the main > #include "python.h" Yeah. I just make sure the last #include lines are #undef _DEBUG and #include <Python.h> Thanks. Miki From insert at spam.here Tue May 25 17:51:47 2004 From: insert at spam.here (Doug Holton) Date: Tue, 25 May 2004 16:51:47 -0500 Subject: programming video manipulation In-Reply-To: <mailman.282.1085512578.6949.python-list@python.org> References: <mailman.282.1085512578.6949.python-list@python.org> Message-ID: <LOidnbG8BchuIi7dRVn-sA@comcast.com> Olivia Robinson wrote: > Hi, > I am an artist who creates interactive video installations that are > controlled using a set of sensors, a microcontroller, computer and video > projector. Currently I am using MAX/MSP and Jitter to program how > information collected from the sensors then is used to manipulate > pre-recorded video footage. > > I have been investigating Python as an alternative to using > MAX/MSP/Jitter to program the collection of information from the sensors > and the resulting video manipulation. I have not been able to find > information about manipulating video with Python, or collecting > information from a microcontroller. Hi, here's my best guess at some tips for doing this, but it would be nowhere as easy as using Jitter I bet (but free instead of $850). First, see this related project that used sensors to create music, and is programmed with Python. Simon Burton could give you some advice. http://www.pcworld.idg.com.au/index.php?id=716362867 http://arrowtheory.com/hypersense/ The most difficult thing to program on your own may be reading the sensor data from the computer. It used to be simple using serial ports, but now we use USB. There are no solutions here, just some pointers to related resources: http://developers.coedit.net/UsbProgramming http://developers.coedit.net/AudioProgramming For the video and real-time video transformations, you would likely want to use OpenGL from Python (pyopengl). It is possible to load a frame from a video file as a texture in OpenGL. And you can manipulate it just like any other texture or surface. Here are demos of this below. The code can be adapted to pyopengl, but there is also some Windows-specific and Mac-specific code to read the video format. http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=35 http://developer.apple.com/samplecode/OpenGL_Movie/OpenGL_Movie.html From __peter__ at web.de Thu May 6 02:42:52 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 May 2004 08:42:52 +0200 Subject: Where is IDLE? References: <mailman.293.1083822310.25742.python-list@python.org> Message-ID: <c7cmpc$9g8$01$1@news.t-online.com> Bobby Mozumder wrote: > I can't find it in the 2.3.3 source tarkit. Shouldn't it be in the > Tools directory? $ find . -name idle ./Lib/idlelib/idle ./Tools/scripts/idle ./build/scripts-2.3/idle Peter From apardon at forel.vub.ac.be Mon May 24 10:53:56 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 May 2004 14:53:56 GMT Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il> <mailman.155.1085166502.6949.python-list@python.org> Message-ID: <slrncb4345.o6k.apardon@trout.vub.ac.be> Op 2004-05-21, Terry Reedy schreef <tjreedy at udel.edu>: > > "Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message > news:c8l3s3$27o$1 at news.iucc.ac.il... > >> Many times I find myself asking for a slice of a specific length, and >> writing something like l[12345:12345+10]. >> This happens both in interactive use and when writing Python programs, >> where I have to write an expression twice (or use a temporary variable). > > With an expression, I'd go for the temp var. > >> Wouldn't it be nice if the Python grammar had supported this frequent >> use? > > I take this as 'directly support' versus the current indirect support via > start+len. > My answer: superficially (in isolation) yes, but overall, in the context of > Python's somewhat minimalistic grammar/syntax, no. Two ways to slice might > easily be seen as one too many. In addition, the rationale for this, your > favorite little addition, would admit perhaps 50 others like it. > >> My idea is that the expression above might be expressed as l[12345:>10]. > > Sorry, this strike me as ugly, too much like and easily confused with > l[12345:-10], and too much looking like a syntax error. > > Given that some other languages slice with (start,len) arguments (but not > then, that I remember or know of, also with a start,stop option), I am > *sure* that Guido thought carefully about the issue. A plus with his > choice is ability to offset (index) from the end *without* calling the len > function. Well I hate his choice. It is inconsistent with the fact that generally l[a:b] produces the empty list when a > b. It is only inconsistent with the Zen of python which says there should be only way to do something. -- Antoon Pardon From collin_sq2003 at yahoo.com Mon May 17 04:02:17 2004 From: collin_sq2003 at yahoo.com (xunil) Date: 17 May 2004 01:02:17 -0700 Subject: need help running python script in linux Message-ID: <81dff960.0405170002.5621ec20@posting.google.com> hi, could any one please help show me how to run a python script in linux ? when i try "python script.py" it just does nothing this is the script iam trying to run #!/usr/bin/env python "USAGE: echoserver.py <port>" from SocketServer import BaseRequestHandler, TCPServer import sys, socket class EchoHandler(BaseRequestHandler): def handle(self): print "Client connected:", self.client_address self.request.sendall(self.request.recv(2**16)) self.request.close() if len(sys.argv) != 2: print __doc__ else: TCPServer(('',int(sys.argv[1])), EchoHandler).serve_forever() this is code for a server socket , iam supposed to see some messages when i run the script but nothing shows completely even the client script reacts the same way below is the client code #!/usr/bin/env python "USAGE: echoclient.py <server> <word> <port>" from socket import * # import *, but we'll avoid name conflict import sys if len(sys.argv) != 4: print __doc__ sys.exit(0) sock = socket(AF_INET, SOCK_STREAM) sock.connect((sys.argv[1], int(sys.argv[3]))) message = sys.argv[2] messlen, received = sock.send(message), 0 if messlen != len(message): print "Failed to send complete message" print "Received: ", while received < messlen: data = sock.recv(32) sys.stdout.write(data) received += len(data) print sock.close() i have the python interpreter installed already but i don't know why these failed to run. could some one please come to my rescue From gsakkis at rutgers.edu Tue May 25 12:36:51 2004 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 25 May 2004 12:36:51 -0400 Subject: Python find Message-ID: <40b37623@rutgers.edu> Hi all, I started writing a module to reproduce Gnu-find functionality in python (as far as I know, there's not one available; pyfind (http://www.anti-particle.com/pyfind.shtml) seems a bit relevant from it's webpage, though most links there are broken - also it's more of a standalone GUI tool than a reusable module). Some questions I have for now: - How can one get the filesystem name from python (e.g. for testing 'find -fstype nfs') ? - Does os.readlink perform a call to os.stat or os.lstat (or the equivalent C system calls) ? If yes, I would like to rewrite it for the case the stat info for a file has already been cached. - Before I write it from scratch, is there a converter for Unix permission strings (like "+go=rw") to numeric modes ? Thanks, George From ssk at chol.nospam.net Sat May 22 19:54:32 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Sat, 22 May 2004 23:54:32 GMT Subject: urllib.urlretrieve error Message-ID: <YKRrc.2684$V74.336@newssvr27.news.prodigy.com> Hello! I'm trying to download PDF files from web to my computer using urllib. Some pdf files are fine but other files are downloaded only 6kB which is wrong. It didn't show any error message. I use urllib.urlretrieve(url, fn). So I tried to download with Internet Explorer and it worked fine. Anyone knows why? My another question is how I can retrieve "mms:..." files. urllib.urlretrieve doesn't work with that protocol. Thanks. Sam From pe at ono.es Mon May 17 08:03:18 2004 From: pe at ono.es (Derfel) Date: 17 May 2004 12:03:18 GMT Subject: Binary handling Message-ID: <2gro06F5ti55U1@uni-berlin.de> Hello all, I have a file of binary data. I want to read this file and parse the data in it. The format of the file is: 8 bits number of data pakets 6 bits offset 20 bits time 8 states How can I read this fields in binary? I see the struct module and the binascii, but I can't split the diferent fiels. Thanks in advance Regards -- Defel From corey.coughlin at attbi.com Thu May 13 17:25:20 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 13 May 2004 14:25:20 -0700 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> <du7hdum415y.fsf@amadeus.cc.tut.fi> <slrnca3t0e.2asc.kirk@eyegor.jobsluder.net> Message-ID: <a8623416.0405131325.435b2087@posting.google.com> I do a lot of unix hacking type stuff here at work, and I understand the wish to use the right tool for the right job and all that, and awk, sed and perl can let you do all that quick command line stuff. My problem with that approach is that after I do some knock-off hack for something, the boss will come by and say, "That's nice, but can you do it with this tweak?" or something, and soon it has snowballed into a full blown script. So why bother with the one-off hacks, when I can just write a function or something, put it in my utility object, and it's done? I can use it again if I need to, use it in other scripts, call it from the python interpreter, whatever I need. And if (or when) I have to expand it for a more complicated purpose, nothing could be easier. If I stick to the traditional unix approach, I'd probably have tools piping into tools piping into shell scripts piping into whatever to get things done, and I'll have to check the man page to make sure the non-standard options for the rarely used tool work, it just winds up being a pain. Here's an example from today, for instance. There's a scratch area we have here where files that are more than a month old are summarily deleted. I don't often use the area for larger projects, but I had to for my last one, which is now getting to be around a month old. I still want to keep the files, so I wrote a little python script to start from an initial directory, check the date on all the files, and update them if necessary. Now sure, I could have done this with some combination of 'find', 'touch' and whatever, but then again, I have all the function blocks I need in my python utility library, so I just import that and it's a snap. So I mention it to one of my co-workers, and he now wants to use it for one of his projects, except it's using a make-like system that will regenerate files if the dates on them get changed relative to each other, so he wants it to take the times and readjust them by an amount relative to the dates on each. That's just the kind of thing (heavy conditionals) that little unix chain commands as solution get really ugly with, but with my script, it shouldn't be a problem. In fact, he's never written a script to do this because he typically relies on the unix tool approach, and he figured it would be too much trouble. But now, he'll have a solution, I'll still have mine, and if needs change in the future, it's easy to evolve. Seems like the right way to go to me. Kirk Job-Sluder <kirk at eyegor.jobsluder.net> wrote in message news:<slrnca3t0e.2asc.kirk at eyegor.jobsluder.net>... > On 2004-05-12, Ville Vainio <ville at spammers.com> wrote: > >>>>>> "Kirk" == Kirk Job-Sluder <kirk at eyegor.jobsluder.net> writes: > > > > Kirk> I've not found this to be the case due to Python's emphasis > > Kirk> on being explicit rather than implicit. My emulation of > > Kirk> "perl -pi -e" was about 24 lines in length. Even with the > > Kirk> improvement there is still 10 times as many statements where > > Kirk> things can go wrong. > > > > That's when you create a module which does the implicit looping. Or a > > python script that evals the passed expression string in the loop. > > Except now you've just eliminated portability, one of the main arguments > for using python in the first place. > > And here is the fundamental question. Why should I spend my time > writing a module in python to emulate another tool, when I can simply > use that other tool? Why should I, as a resarcher who must process > large quantities of data, spend my time and my employer's money > reinventing the wheel? > > > > Kirk> It is really hard to be more trivial than a complete program in one > > Kirk> command line. > > > > As has been stated elsewhere, you can do the trick on the command > > line. The effort to create the required tools only needs to be paid > > once. > > One can do the trick one one command line in python. However that > command line is an ugly inelegant hack that eliminates the most > important advantage of python: clear, easy to understand code. In > addition, that example still required 8 python statements compared to > two in awk. > > > However, many times it won't matter whether the whole program fits on > > the command line. I always do a script into a file and then execute > > it. I just prefer a real editor to command history editing if > > something goes wrong. > > Which is what I do as well. The question is, why should I write 8 > python statements to perform a task that I can do in two using awk, or > sed? Why should I spend 30 minutes writing, testing and debugging a > python script that takes 5 minutes to write in awk, or sed taking > advantage of the implicit loops and record splitting. > > > I think one should just analyze the need, implement the requisite > > module(s) and the script to invoke the stuff in modules. The needs > > have the habit of repeating themselves, and having a bit more > > structure in the solution will pay off. > > I think you are missing a key step. You are starting off with a > solution (python scripts and modules) and letting it drive your > needs analysis. I don't get paid enough money to write pythonic > solutions to problems that have already been fixed using other tools. > > > The virtual of the implicitness is still arguable. > > I'll be more specific about the challenge. Using only stock python with > no added modules, give me a script that pretty-prints a > character-delimted file using one variable assignment, and one function. > > Here is the solution in awk: > BEGIN { FS="\t" } > {printf("%s %s %s %s", $4, $3, $2, $1)} From newsgroups at jhrothjr.com Mon May 3 21:13:51 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 May 2004 21:13:51 -0400 Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> Message-ID: <109drk3erp8cm8c@news.supernews.com> <SeeBelow at SeeBelow.Nut> wrote in message news:4096E9F8.38ABF26D at shaw.ca... > Must function defs appear earlier in a file than use of their name? No. Function definitions must be executed before they are called, but they don't have to be before their calls. The reason for this is that it's the execution of the function definition at run time that binds the function to the name in the dictionary, and that's where it has to be to be executed. > If so, is there some way around this? It's creating a puzzle for me. Possibly you could say a bit more about what you're trying to do that's causing some perplexity? John Roth > > Mitchell Timin From Laura.McCord at doucet-austin.com Fri May 21 11:28:06 2004 From: Laura.McCord at doucet-austin.com (Laura McCord) Date: Fri, 21 May 2004 10:28:06 -0500 Subject: Deleting Directories Message-ID: <573C3D25471BAE4DB0CDA25B1FE6C3832E3432@aa16exc.int.doucetandassociates.com> Yes, I just found out about shutil() which was the key element that I needed. I just didn't see it in the library reference. Thanks, Laura -----Original Message----- From: python-list-bounces+laura.mccord=doucet-austin.com at python.org [mailto:python-list-bounces+laura.mccord=doucet-austin.com at python.org] On Behalf Of Rico Huijbers Sent: Friday, May 21, 2004 10:22 AM To: python-list at python.org Subject: Re: Deleting Directories Laura McCord wrote: > This is probably a very basic question but I started learning python. > I am almost done writing my delete directory script but I am at a > stand still right now. I want to delete folders in my > "/var/www/html/da" directory that are over 1 day old. > > But, when I find the folder a simple rmdir() command does not work > because the directory is not empty. What else do I need to do to > delete a directory that contains content? Assuming you already figured out how to check the directories' timestamps, shutil.rmtree() will do what you want. -- http://mail.python.org/mailman/listinfo/python-list From richie at entrian.com Thu May 27 05:27:28 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 27 May 2004 10:27:28 +0100 Subject: wxpython moved? In-Reply-To: <e305e171.0405270115.37357254@posting.google.com> References: <e305e171.0405270115.37357254@posting.google.com> Message-ID: <n1dbb0hvcetiote3gdvjgh72kucbrfc05j@4ax.com> [Arsenal] > its official site www.wxpython.org has been dead for some time... was it moved? It's working fine for me - could it be a problem at your end? DNS trouble? -- Richie Hindle richie at entrian.com From me at privacy.net Fri May 28 04:10:46 2004 From: me at privacy.net (Duncan Booth) Date: 28 May 2004 08:10:46 GMT Subject: Unification of Methods and Functions References: <mailman.256.1085484069.6949.python-list@python.org> <2hic07Fd9q7fU1@uni-berlin.de> <eu9cb0tkf674ob8u595sqk9kncs8nvm8k9@4ax.com> Message-ID: <Xns94F75CFE55574duncanrcpcouk@127.0.0.1> David MacQuigg <dmq at gain.com> wrote in news:eu9cb0tkf674ob8u595sqk9kncs8nvm8k9 at 4ax.com: > To summarize our discussion on static methods, we have four ways to > accomplish the purpose of making a method callable without an > instance. > > 1) Add the staticmethod wrapper. > 2) Create a dummy instance, and use it to call the method. > 3) Move the method outside of the class, and if that disturbs the > modular structure of the program, make the class and its external > function a new module with its own namespace. > 4) Move the method outside of the class, but make sure it is still > "associated" with the class by giving it a special name. > > Is there any reason we *should not* use solution #1? You missed 5) Use a classmethod wrapper. The commonest reason I know of for wanting to a method callable without an instance is to provide the class with factory functions, and in that case you definitely don't want to use solution #1 as solution #5 gives you support for subclassing at no extra charge. From davidf at sjsoft.com Mon May 31 05:55:57 2004 From: davidf at sjsoft.com (David Fraser) Date: Mon, 31 May 2004 11:55:57 +0200 Subject: ANN: PyObjC 1.1 In-Reply-To: <mailman.446.1085993480.6949.python-list@python.org> References: <mailman.446.1085993480.6949.python-list@python.org> Message-ID: <c9evf3$ifn$1@ctb-nnrp2.saix.net> Ronald Oussoren wrote: > PyObjC is released with an open source license. > > That is, the MIT license... would be great to include this explictly somehwere on the web page and in the announcement :-) David From dieter at handshake.de Sun May 23 01:52:21 2004 From: dieter at handshake.de (Dieter Maurer) Date: 23 May 2004 07:52:21 +0200 Subject: Python 2.3.4c1 -- nasty threading bug (Linux) References: <mailman.151.1085163442.6949.python-list@python.org> Message-ID: <x7u0y7bsh6.fsf@handshake.de> "Tim Peters" <tim.one at comcast.net> writes on Fri, 21 May 2004 14:17:15 -0400: > [Dieter Maurer] > > Python apparently contains a long lasting threading bug on Linux > > with LinuxThreads. > ... > > This problem causes multi-threaded applications such > > as Zope to enter a funny state when one of the threads crashes. > > Some of the threads die but others remain and can only be killed > > with "kill -9". Normal restart logic fails for Zope because of these > > remaining threads. > > > > <mailto:alangmead at boston.com> submitted a patch > > > > <http://sourceforge.net/tracker/index.php?func=detail&aid=949332&group_id= > > 5470&atid=305470> > > ... > The patch wasn't applied, and the 2.3.4 release manager doesn't want to risk > it for 2.3.4. Do read the bug report! There are 36 comments attached (so > far) because it's a complex problem to solve it correctly. Andrew Langmead > (whose patch you referenced) is continuing to participate in finding a > correct solution. See his comment there dated 2004-05-04 10:00 for the > relevant respect in which LinuxThreads is buggy but NPTL is not. I verified that the patch mentioned above indeed fixes the problem. It might introduce other subtle problems but at least none that are revealed by Python's regression test suite... Moreover, I doubt that such problems will be significant in practise: The patch prevents blocking of signals that should (as specified by the pthreads standard) not be blocked -- as the operating system uses these signals to report serious problems. No application should use these threads for application specific communication. Therefore, a violation of Python's principle to only deliver signals to the main thread seems appropriate for these signals. It would be great, when the Python developers could come up with an even better patch. However, those who run "productive" multithreaded Python based applications, especially Zope 2, on Linux with LinuxThreads (rather than native PosixThreads) may consider to use the patch which is available *now*. We will do so. I will report back should we see more serious problems than we have now. -- Dieter From has.temp2 at virgin.net Sun May 2 14:21:47 2004 From: has.temp2 at virgin.net (has) Date: 2 May 2004 11:21:47 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <sue79090tf0ja6rp63hsuj851l3dad0l44@4ax.com> Message-ID: <69cbbef2.0405021021.5f285ad5@posting.google.com> David MacQuigg <dmq at gain.com> wrote in message news:<sue79090tf0ja6rp63hsuj851l3dad0l44 at 4ax.com>... > This is amazing! I don't understand how it works, but it does provide > what I think the "classless" advocates are looking for, an ability to > "clone" one object from another, and avoid any "two-tier" organization > of instances and classes. I posted an incomplete implementation of a simple proto-OO model built on top of Python the other day. (As opposed to trying to mix it into Python's existing class-based object system, which doesn't really gel so well.) Here's the link: > It is a shame that the discussion has degenerated to the point where > most people are ignoring threads relating to prototypes. Well, it has little direct bearing on Python discussions so most folk probably aren't interested anyway. > I have tried > repeatedly to get a simple requirements statement or use case, and get > nothing but sarcastic remarks. I have no experience with prototype > languages either, That would probably be your problem then. I think you need to knuckle down and do some self-motivated research before trying to wade in at the deep end. I mean, if a forty-watter like me can manage to digest it, a smart person like yourself shouldn't have any trouble [as long as you go into it with a completely open mind]. > except a little with Prothon. Pick a language that's a bit more established and mature (and isn't currently right in the middle of a great philosophical war;). > I started to read a paper, but fell asleep after a discussion on the "theory of > knowledge". Well, you still got further than me. Reading/writing papers is definitely _not_ one of my strong points; I'm much more the hands-on "give it a go and see what happens" type. I'm not averse to lightly skimming the odd bit of high-falutin' academic papery, however, and even when I really don't understand what it's about at least I come away with the vague notion that there are Other Ideas that exist out there, rather than hiding in my own self-imposed box pretending that's really all there is. Better to serve [fries] in heaven than rule in [cobol] hell, I say. > In spite of all this, there are some nuggets along the way. The > unification of methods and functions is the one I am most interested > in. This is not a proto-OO issue. BTW, if you want to see _really_ interesting things done with methods and functions, go check out, say, Dylan. Multimethods are one of those things that can sound really complex and intimidating at first encounter - especially if you're only ever thought of OOP in terms of how Java, Python, etc. do it - but are actually _incredibly_simple_, not to mention rather beautiful. Go grok 'em; it'll really broaden your mind. > I agree with you that Python has the capability to implement > prototypes. Perhaps we can do that using metaclasses for some initial > experiments. Then if we get some constructive feedback, we can put > together a PEP to make prototypes part of the core language, add > better syntax, and fix whatever might not work quite right using > metaclasses. Wrong strategy. You cannot simplify an already complex thing by adding even more stuff to it. I for one am already absolutely convinced that proto-OO is ultimately the right way forward for the future of OOP on dynamic languages, and that all the stuff we see and hear about Next Big Things in [traditional] OOP, such as metaclasses and aspects, is all just an almighty cloud of smoke generated by faddish, under-read folk who have failed/refused to see/acknowledge that the problems they are currently trying to solve now were/are A. already solved years ago, but ignored then as now because they didn't fit neatly with the then/current orthodoxy and would require significant backtracking to adopt; and B. mostly generated by the various Really Bright Ideas To Solve Our Problems they cooked up the last time round. Of course, the longer that invested parties refuse to acknowledge the fundamental flaws and mis-features in the foundation of their great and grandiose sand castles in the sky and persist in pretending that the solution is slopping even more flaws and mis-features on top, the worse it's going to be for everybody when the whole lot _finally_ collapses under its own weight. So when that day comes, expect to see me standing well to the side laughing my ass off.;) has From greg at cosc.canterbury.ac.nz Sun May 9 23:16:16 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 10 May 2004 15:16:16 +1200 Subject: Scope rule pecularities In-Reply-To: <slrnc9mjds.5fa.apardon@trout.vub.ac.be> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> Message-ID: <2g8ag2F4re0lU1@uni-berlin.de> Antoon Pardon wrote: > IMO having operators that should work in place for object that > are immutable, sound contradictory. Having the following code: But restricting += etc. to work only on mutables would mean you wouldn't be able to do things like x = 42 x += 1 which is a very handy thing to be able to do. The current semantics are a pragmatic compromise which seems to work fairly well in most situations. I suggested once that the assignment could perhaps be skipped if the __iadd__ method returned the original object. That would allow a_tuple[i] += something to work in the case where the object is in-place modifiable. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ralf at tecont.de Wed May 12 07:54:01 2004 From: ralf at tecont.de (Ralf Muschall) Date: Wed, 12 May 2004 13:54:01 +0200 Subject: Integer division, surprising results References: <mailman.395.1084200180.25742.python-list@python.org> Message-ID: <84k6zhsvxi.fsf@tecont.de> "Tim Peters" <tim.one at comcast.net> writes: > It's primarily driven by the desire that i%j have the same sign as j. If That's the side effect, not the desire (AFAIK). > you want that, and also want > > i == (i/j)*j + (i%j) > > then integer division has to return the floor. C also requres that identity AFAIK the history is the other way around: The Unix+C-philosophy was essentially the "don't care"-approach, i.e. '/' does just what the CPU happens to do if it sees a divide instruction. Most machines seem to truncate here, therefore '%' can give negative results. This rarely disturbs anyone, since most people don't divide negative numbers. Those who do (e.g. mathematicians) fall outside the "good for 90% is good enough"-attitude and have to help themselves. Scheme and Lisp *do* care (offering both "remainder" (the easily implemented thing) and "modulo" (the real thing)), as does Python with its '%'[1]. (Called "rem" and "mod" in Lisp). [1] I don't know whether it also offers a shortcut for sign(x)*mod(abs(x),y) for people who insist on the bad result. Ralf -- GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V- PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv b+++ DI+++ D? G+ e++++ h+ r? y? From miki.tebeka at zoran.com Tue May 25 02:24:02 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 25 May 2004 08:24:02 +0200 Subject: par files? In-Reply-To: <Khzsc.9321$be.5366@newsread2.news.pas.earthlink.net> References: <Khzsc.9321$be.5366@newsread2.news.pas.earthlink.net> Message-ID: <20040525062402.GC2208@zoran.com> Hello Russell, > In java there are .jar files so I'm wondering if Python has anything similar > - .par files perhaps? Python (since 2.2 I think) can import from zip files (jar files are zip files). Just add the zip file name to sys.path and you're done. Bye. -- ------------------------------------------------------------------------- Miki Tebeka <miki.tebeka at zoran.com> http://tebeka.web1000.com The only difference between children and adults is the price of the toys. From peter at engcorp.com Thu May 13 09:26:31 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 May 2004 09:26:31 -0400 Subject: Python - open forever ? In-Reply-To: <mailman.511.1084452958.25742.python-list@python.org> References: <mailman.511.1084452958.25742.python-list@python.org> Message-ID: <hs-dnQR_3_kU6j7dRVn-vw@powergate.ca> Romans Krjukovs wrote: > To make this reality we have to include Python in our strategy > plans for at least 3 nearest years. > This would be a green light to our developers to start new projects on > Python. > > At the presentation of Python and its usage posiibilities in our > home environment to the members of the project managers board, > we got such questions: > - There is a risk that Python can become closed and unsupported in the > future. > (Remember RedHat ?) I remember RedHat. In fact, I can still download it, and install and use it. For free. And get the source code. And get support (if I'm willing to pay, of course, but it would be ludicrous for a company to insist that free support is a necessity for a given technology). What is "closed and unsupported" about it? > - Who can guarantee that Python will be usable and available to us if > it is develeped and maintained by the hackers from all over the world > without any obligations and guarantees ? Python has been usable and available for the last thirteen years, but perhaps the last thirteen years have been atypical... > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) You can read the Python license and, if you really insist, consult with your lawyers, whom you pay to give legal and strategic advice of this nature. Then you will understand that the nature of the Python license is such that these silly unreliable hackers, who won't guarantee anything, cannot prevent you from using Python and taking the source code and doing what you will with it, for the most part. But I'm not a lawyer... Note that if you have money to spend, you can certainly pay various companies for Python support. Of course, that won't provide you with any guarantees either, but perhaps it will be costly enough to make your management believe so.... If you don't want to spend the money, it's a little unclear why you would whine about obligations and guarantees... the economy doesn't really work that way, even in the Open Source movement. > Python is very fast in development, stable and fast code, easy to learn, > but never the less big and business critical project can't be started > without mentioned risk analyses. > It would be nice to know what Python society members think about this. Basically this: if you are going to use Python in "big and business critical projects", you want stability. To achieve stability, among other things you want to chose one version of Python and stick with it for a very long time, rather than consantly upgrading with each new release (IMHO). Given that strategy, you need only assure yourself that the license on the version of Python that you adopt, and on any third- party modules you use, allows you to use it in the ways you want to use it, including getting the source code and even redistributing it if you wish. At my previous employer, a 100+ employee telecom in Toronto, we chose Linux (RedHat, even) and Python as the basis for a range of products. The extent of the risk assessment required was to verify that the licenses allowed us to do the development without the risk that someone (other than SCO, say) would constrain us from continuing to use it. We didn't expect, or look for, any guarantees that all future versions would forever be completely free and unconstrained. Again, pointing to SCO, there _are_ no guarantees... -Peter From aahz at pythoncraft.com Wed May 26 13:34:52 2004 From: aahz at pythoncraft.com (Aahz) Date: 26 May 2004 13:34:52 -0400 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <pan.2004.05.26.01.02.00.429236@sbcglobal.net> <roy-574BDD.21200225052004@reader2.panix.com> Message-ID: <c92kfs$8i3$1@panix3.panix.com> In article <roy-574BDD.21200225052004 at reader2.panix.com>, Roy Smith <roy at panix.com> wrote: > >Typing is cheap. Thinking is expensive. And, yes Aahz, you can quote >me on that :-) Heh. It's in my database now. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "He's Quebecois. He puts mayonnaise on *everything*." --siobhan at virulent.org From NAIGIMSESRIMAIL at gims.com Sun May 16 12:02:07 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sun, 16 May 2004 18:02:07 +0200 Subject: ALERT - GroupShield ticket number OB24_1084723314_ESRIMAIL_3 was generated Message-ID: <B06B8FEF47ACD7119E720040F42845910322A336@ESRIMAIL> Action Taken: The message was blocked because of its subject. To: python-list at python.org <python-list at python.org> From: bhoel at web.de <bhoel at web.de> Sent: 478851584,29637471 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1813 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040516/12604fcb/attachment.bin> From tjreedy at udel.edu Fri May 21 14:23:58 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 14:23:58 -0400 Subject: Printing formatted strings from a dictionary References: <b4a8ffb6.0405121230.a564636@posting.google.com><m3r7toh75g.fsf@pc150.maths.bris.ac.uk><21064255.0405131144.160af9a8@posting.google.com><c8gfov$9j9$1@news.service.uci.edu> <21064255.0405201224.77a7574f@posting.google.com> Message-ID: <c8lhg0$7mj$1@sea.gmane.org> "Peter Abel" <PeterAbel at gmx.net> wrote in message news:21064255.0405201224.77a7574f at posting.google.com... > >>> d={'1':2} # Remark the quotmarks '1' > >>> '%(1)i'%d > '2' > I even would not have believed that this kind of formatting would work. > But the more I think about it the more it becomes consequential and logical. >From Lib Ref 2.3.6.2. String Formatting ... Mapping key (optional), consisting of a parenthesised sequence of characters (for example, somename)). Examples generally use names for the char sequence, but restricting the sequence to a name would require more work for less functionality. Since % works with unicode as well as byte strings, one can, I presume, interpolate with unicode keys as well. Terry J. Reedy From jeffbarish at starband.net Fri May 21 18:30:54 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Fri, 21 May 2004 16:30:54 -0600 Subject: Tkinter: update_idletasks References: <mailman.110.1085067858.6949.python-list@python.org> <c8kd79$vkt$1@news-reader4.wanadoo.fr> Message-ID: <c8lvv4$su$1@sea.gmane.org> Eric Brunel wrote: > Jeffrey Barish wrote: >> I'm confused about how to use the update_idletasks method. In my >> program, I have a handler for a button in which execution will >> linger. During that time, I would like for the GUI to continue to >> show signs of >> life. I have a Pmw MessageBar in which I display a status message. >> I figured out that if I run update_idletasks on that MessageBar, then >> the >> MessageBar will update the display as I update the message. However, >> if I cover the GUI with some other window and then expose it again, >> the GUI does not refresh until the handler finishes (except for the >> MessageBar). Do I have to run the update_idletasks method for every >> widget in the GUI? for all the frames? for just the root frame? Or >> is it impossible to get the GUI to refresh in this situation? > > At tcl level, update_idletasks isn't a "method", i.e. the tcl command > doesn't take any parameter telling which widget to refresh. So calling > the Tkinter update_idletasks method on any widget has exactly the same > effect, which is to refresh the whole GUI. > > There are some issues on Windows however, where the newly created > toplevel's may not refresh until full control is returned to the GUI. > To work around this problem, use the wait_visibility method to wait > until the newly created window is displayed. But be careful: > wait_visibility processes events, unlike update_idletasks that does > just a GUI refresh. There is apparently no simple way of updating the > display of newly created toplevel's on Windows without returning full > control to the GUI (at least with tk/Tkinter) > > I never saw the problem you describe (some windows refreshing, some > not), but I mainly develop on Linux, which may show a different > behaviour than the platform you're working on (which BTW you don't > mention...). Maybe you can post a small piece of code showing the > problem? > > HTH Ah. I had a hunch that might be the case. However, that is not the behavior that I am seeing. First, in response to your questions: (1) I am on Linux (there are other platforms?); (2) I am using Python 2.3; (3) it is difficult to extract a piece of the code, but I will attempt to describe more clearly what I am doing. There is a button with a handler. In the handler I use popen3 to launch a program that takes a long time to execute. I monitor its progress in a while loop by reading a status line that it produces on stderr. The status line provides information about percentage complete; I use that information to update the MessageBar in my GUI. When the status line indicates that the process is done, I exit the while loop and return from the button handler. I tried running update_idletasks on the MessageBar in the while loop. I tried running it on the root window, even though the information you provided indicated that it doesn't matter what class owns the method -- and my experience certainly does not contradict that statement. In every case, only the MessageBar updates. Well, that's not entirely true. I also move a tag in a text widget; the previously and newly tagged text redraws. The only technique I have found that permits the main window to update is to run most of the handler in a separate thread. The problem I am having with that approach is that the MessageBar then flashes in an annoying way (the background seems to go to white at every update and then gets redrawn to gray -- which happens only when the while loop is in its own thread). Any other thoughts would be much appreciated. -- Jeffrey Barish From greg at cosc.canterbury.ac.nz Wed May 12 23:02:37 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 13 May 2004 15:02:37 +1200 Subject: Scope rule pecularities In-Reply-To: <slrnca428q.1i9.apardon@trout.vub.ac.be> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <2g8ag2F4re0lU1@uni-berlin.de> <slrnca428q.1i9.apardon@trout.vub.ac.be> Message-ID: <2gg6qfF2hi98U1@uni-berlin.de> Antoon Pardon wrote: >> x = 42 >> x += 1 >> >>which is a very handy thing to be able to do. > > But it creates confusions because the semantics > is not consistent. Practicality beats purity, though, and this does seem to be very practical. Besides, the semantics are as consistent as anything else in Python, where the objects being operated on get to determine the meaning of just about everything. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From goodger at python.org Fri May 21 13:21:56 2004 From: goodger at python.org (David Goodger) Date: Fri, 21 May 2004 12:21:56 -0500 Subject: Passing options between modules In-Reply-To: <939f49f8.0405210907.4f12a613@posting.google.com> References: <939f49f8.0405210907.4f12a613@posting.google.com> Message-ID: <40AE3AB4.3010704@python.org> Chris wrote: > I'm trying to come up with a not-so-ugly manner of passing many > command-line options between modules. Use optparse.py. It's standard in Python 2.3, or get it from http://optik.sf.net for older versions of Python. The result of parsing command-line options is a "Values" object, with standard dotted-attribute access. For example, for "--an-option", you'd say "options.an_option". It's easy to pass the single Values object around. -- David Goodger From robin at SPAMREMOVEjessikat.fsnet.co.uk Tue May 25 14:48:18 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Tue, 25 May 2004 19:48:18 +0100 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <tyf7jv0n7dt.fsf@pcepsft001.cern.ch> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> <tyf7jv0n7dt.fsf@pcepsft001.cern.ch> Message-ID: <40B394F2.8020807@jessikat.fsnet.co.uk> Jacek Generowicz wrote: ........ > > Looks like compiling this partucular high-level dynamically typed > language makes it run considerably faster. Let's repeat the exercise > for 3 more implementations of this particular language I just happen > to have lying around on my machine, and compare it to Python's > performance on the equivalent program: > > >>>>def fib(n): > > ... if n<2: return 1 > ... return fib(n-1) + fib(n-2) > ... > >>>>import time >>>>a=time.time(); fib(35); time.time() - a > > 14930352 > 20.425565958023071 > > > Here are the results gathered in a table: > > > Name Interpreted Compiled > > LispWorks 66 1.0 s > Clisp 41 9.5 s > CMUCL Got bored waiting 1.5 s > SBCL Compiles everything 1.6 s > Python Compiles everything 20 s > > > So, we have times of 1.0s, 1.5s, 1.6s, 9.5s and 20s. Now one of those > Common Lisp implementations does NOT compile to native; it compiles to > bytecode. Can you guess which one it is, by looking at the timings ? I tried a modification in prothon and was suprised at how bad it was. My windows box started to thrash with fib(35) so I reduced it to fib(25) #fib.py def fib(n): if n<2: return 1 return fib(n-1) + fib(n-2) print fib(25) C:\Prothon\pr\test>timethis \Prothon\prothon fib.py TimeThis : Command Line : \Prothon\prothon fib.py TimeThis : Start Time : Tue May 25 19:41:32 2004 121393 TimeThis : Command Line : \Prothon\prothon fib.py TimeThis : Start Time : Tue May 25 19:41:32 2004 TimeThis : End Time : Tue May 25 19:42:24 2004 TimeThis : Elapsed Time : 00:00:52.235 compare with C:\Prothon\pr\test>timethis python fib.py TimeThis : Command Line : python fib.py TimeThis : Start Time : Tue May 25 19:43:02 2004 121393 TimeThis : Command Line : python fib.py TimeThis : Start Time : Tue May 25 19:43:02 2004 TimeThis : End Time : Tue May 25 19:43:05 2004 TimeThis : Elapsed Time : 00:00:02.673 In fact the python time for fib(35) was about 31.1 seconds (ie less than prothon for fib(25)) so something is spectacularly amiss with prothon. -- Robin Becker From thorsten at thorstenkampe.de Sat May 1 19:43:24 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 2 May 2004 01:43:24 +0200 Subject: except AttributeError, TypeError: Message-ID: <19zy0i7gw5uym.dlg@thorstenkampe.de> What is the best way to except two errors, when the except handling in both cases is the same? "except:" would just except every error and not just those I want. except Attribute error: do_much_stuff except TypeError: do_the_same_stuff is bad because of the duplication and def do_it(): do_much_stuff except Attribute error: do_it() except TypeError: do_it() would work but is rather unelegant? What is the best way to except to errors with the same exception handling? Thorsten From greg at cosc.canterbury.ac.nz Tue May 25 22:59:43 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 26 May 2004 14:59:43 +1200 Subject: Prothon vs. Python integers In-Reply-To: <40b3111d$0$7727$afc38c87@news.easynet.co.uk> References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> <40b3111d$0$7727$afc38c87@news.easynet.co.uk> Message-ID: <2hifh1Fdk1c3U1@uni-berlin.de> Mark Hahn wrote: > > Surely > once you get to 3.7e19 you are in floating point territory. Incorrect. You're only ever in floating point territory if you can tolerate inexact results. Some applications can't. Even if you don't support arbitrary-size integers, you should *not* automatically overflow from ints to floats. You should raise an exception instead. That way, people won't be bitten by unexpected loss of precision. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From greg at cosc.canterbury.ac.nz Wed May 5 21:38:51 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 06 May 2004 13:38:51 +1200 Subject: question: parameters for create_polygon() method In-Reply-To: <mailman.285.1083792427.25742.python-list@python.org> References: <40984D5A.B819BF28@shaw.ca> <mailman.254.1083723811.25742.python-list@python.org> <40986DD6.F06FF651@shaw.ca> <mailman.259.1083733896.25742.python-list@python.org> <c7a2rg$nlq$01$1@news.t-online.com> <20040505074742.GF20777@frobozz> <mailman.285.1083792427.25742.python-list@python.org> Message-ID: <c7c4vc$27hmk$1@ID-169208.news.uni-berlin.de> Peter Finlayson wrote: > Andrew Bennetts wrote: > > Odd, though -- I thought that calls that put non-keyword args after > > keyword args were a syntax error > > I thing that is because the standard form for the calls are: > def mydef(arg1, arg2, *args, **keywords) > ie with the arbitrary argument lists after the formal args. Yes. Syntactically, the * args don't count as positional args; they're in a category of their own. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From grante at visi.com Mon May 17 10:41:49 2004 From: grante at visi.com (Grant Edwards) Date: 17 May 2004 14:41:49 GMT Subject: book on wxPython? References: <slrncab3p3.ou5.grante@grante.rivatek.com> <pan.2004.05.15.03.52.15.667940@sbcglobal.net> <40a5a851$0$8512$a18e6209@newsreader.visi.com> <js4hn1-mo7.ln1@home.rogerbinns.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> <cfcjn1-6ue.ln1@home.rogerbinns.com> <40a7a324$0$8513$a18e6209@newsreader.visi.com> <sskln1-j5v.ln1@home.rogerbinns.com> Message-ID: <slrncahjp0.s69.grante@grante.rivatek.com> On 2004-05-17, Roger Binns <rogerb at rogerbinns.com> wrote: >> I'm definitely going to stick with it. I blundered my way >> though writing and shipping one small wxWindows app a while >> back. Now that I've figured out the two-tree thing, it should >> be easier. > > The best advice I can give you is to seriously examine the XRC > stuff. The XRC editor even comes with wxPython. That will > let you abstract out your user interface code (especially the > issues to do with layouts and parent relationships). I just > wish I had done it. Thanks. I'll take a look at it. Right now I'm still trying out Wax. For what I'm working on right now it seems like a good solution. -- Grant Edwards grante Yow! Hmmm... an arrogant at bouquet with a subtle visi.com suggestion of POLYVINYL CHLORIDE... From tim.one at comcast.net Fri May 21 14:17:15 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 21 May 2004 14:17:15 -0400 Subject: Python 2.3.4c1 -- nasty threading bug (Linux) In-Reply-To: <x7pt8xoo5f.fsf@handshake.de> Message-ID: <mailman.110.1572213750.32708.python-list@python.org> [Dieter Maurer] > Python apparently contains a long lasting threading bug on Linux > with LinuxThreads. Yes, although note that LinuxThreads is an incorrect implementation of the phtreads standard in a relevant respect, so you should also say that LinuxThreads has a longstanding bug here. > SIGSEGV causes hung threads (Linux) > http://www.python.org/sf/756924 ... > This problem causes multi-threaded applications such > as Zope to enter a funny state when one of the threads crashes. > Some of the threads die but others remain and can only be killed > with "kill -9". Normal restart logic fails for Zope because of these > remaining threads. > > <mailto:alangmead at boston.com> submitted a patch > > <http://sourceforge.net/tracker/index.php?func=detail&aid=949332&group_id= > 5470&atid=305470> > > Nevertheless, the problem still exists in Python 2.3.4c1. > Either the patch was not applied or it does not fix the problem. The patch wasn't applied, and the 2.3.4 release manager doesn't want to risk it for 2.3.4. Do read the bug report! There are 36 comments attached (so far) because it's a complex problem to solve it correctly. Andrew Langmead (whose patch you referenced) is continuing to participate in finding a correct solution. See his comment there dated 2004-05-04 10:00 for the relevant respect in which LinuxThreads is buggy but NPTL is not. From peter at semantico.com Tue May 25 05:25:49 2004 From: peter at semantico.com (Peter Hickman) Date: Tue, 25 May 2004 10:25:49 +0100 Subject: Prothon vs. Python integers In-Reply-To: <Mbrsc.15253$bF3.12865@fed1read01> References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> Message-ID: <40b3111d$0$7727$afc38c87@news.easynet.co.uk> Mark Hahn wrote: > Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely > once you get to 3.7e19 you are in floating point territory. I can't imagine > counting anything up to 10**19. Except all those sad people doing that thing called 'maths'. Sorry but one of my requirements for a language is that is can handle integers of any size quickly and easily (and a good integer square root would be nice). However I always seem to end up coding with C and GMP. From martin at v.loewis.de Thu May 13 14:20:46 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 13 May 2004 20:20:46 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> References: <mailman.513.1084456098.25742.python-list@python.org> <40a39511$0$560$e4fe514c@news.xs4all.nl> <c80800$ok9$1@panix1.panix.com> <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> Message-ID: <40A3BC7E.1010200@v.loewis.de> Irmen de Jong wrote: > P.S. I don't really see why you mentioned python-dev, are you saying > that bugs and patches have more chance of being included in a new > Python version if the submitter is subscribed to python-dev and also > announces the bugs/patches there? Patches have a larger chance to get included if they are reviewed. For the last few years, we have been short of reviewers, so patches have little chance to get included, period. People submitting patches might consider helping the process beyond submitting patches, e.g. by reviewing patches of other people. E.g. review 10 or so patches, put your comments into them, and then suggest approval or rejection on python-dev. Then, somebody (perhaps yours truly) might check bulk-close patches if he agrees with the review. If any submitter of a patch would review 10 other patches, there would be no backlog. Regards, Martin From j_mckitrick at bigfoot.com Sun May 23 21:27:11 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 23 May 2004 18:27:11 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> Message-ID: <ec6dce8b.0405231727.bd428da@posting.google.com> > check out ruby. It is very similar to python, but one of the many benefits > it has over python, is ability to distinguish 'real' private, public, and > protected variables/methods. Ruby does not allow multiple inheritance, and > it supports a very powerful mixin system- it's OO mechanisms and syntax > generally seem better than pythons. But I don't like anything about the syntax of Ruby. Python is so much more natural to read. From ak at silmarill.org Wed May 26 11:01:24 2004 From: ak at silmarill.org (AK) Date: 26 May 2004 08:01:24 -0700 Subject: Problem with curses: screen is blanked on second refresh Message-ID: <7fdc73c1.0405260701.6979c8f5@posting.google.com> Hi, I have a medium sized app that I'm transferring to use curses. What happens is very very strange.. I am at my wits' ends. I worked with it all day yesterday and couldn't figure it out. Today morning I thought about it and still nothing. I hope that some curses expert can figure out what's wrong from my description. I'm very new to curses so I am not sure I know which details are crucial, so please answer me if you need more details. I have a function that uses win.addnstr() calls to add strings to the win (which is passed by curses.wrapper). First time the function is called, it works just fine. Second time it makes the screen blank and the only things that show up are single digits that are updated by another thread. The x coord given to the addnstr() is always 0. That thread should print a line with elapsed time, full time, and a short string of text; it should print on the bottom line on screen. First time it's called it does just that; all other times it prints only the digits of the elapsed time that are different from what was already there, and it blanks the rest of the line; and it prints it on *top* line of screen. If I call win.clear() at the top of the main redraw function, it works fine. Full screen is updated and shown. The only problem is that it flickers while updating. It flickers once but it's annoying enough - I hope to only update spots on screen that really changed. If I call win.redrawwin() instead of win.clear(), the lines that changed are updated and shown, but *all other lines are blanked*. And if I call neither win.clear() nor redrawwin(), the whole screen is blanked on second redraw, and as I said only single digits changing show up at the top of screen instead of bottom. Things I tried: I passed the same string 'TEST', to all lines. They show up fine on first refresh, then disappear. So this is not about the strings I pass. I have other threads updating the screen, but even if I disable all of them, I get the same strange behaviour. Hope you can advise me.. thanks From peter at engcorp.com Thu May 20 10:23:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 10:23:02 -0400 Subject: alternatives to making blocks like { } or other ?? In-Reply-To: <9ace45f.0405200616.7e5110ba@posting.google.com> References: <c8do0u$9fb$1@news.atman.pl> <jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com> <c8e5sh$109b$1@news.atman.pl> <slrncalqqf.8f2.grante@grante.rivatek.com> <sjDqc.108220$NR5.92596@fe1.texas.rr.com> <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: <rfqdnYe2EsXaIjHdRVn-ig@powergate.ca> Andrei Smirnov wrote: > i do really suffer. i have to use Perl and i know that i have no chance > to convince my new boss (very smart guy) to switch to Python because of > braces. Clearly your new boss is *not* very smart, or is insane. No sane, intelligent person would reject Python *solely* because it doesn't use braces. Maybe that plus some other reasons, but not as the *only* reason... -Peter From brian at sweetapp.com Mon May 31 14:43:26 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 31 May 2004 20:43:26 +0200 Subject: SimpleXMLRPCServer performance issue in MSWin In-Reply-To: <20040531143422.33891.qmail@web60610.mail.yahoo.com> References: <20040531143422.33891.qmail@web60610.mail.yahoo.com> Message-ID: <40BB7CCE.1070808@sweetapp.com> danu kusmana wrote: > When I ran the server script on Windows platform is > running very slow. The log printed automatically by > the SimpleXMLRPCServer class; I assumed, is processing > every 5 second each process if 1 client connected. If > 1 more client accessed the time is decreasing half of > the first. But compared when the server script running > on Linux is much to slow. Can't you post some code with timings so we can see what data types you are using and what the performance difference is? > Maybe I also forgot mention before that if the script > running on Windows its only processing 1 thread/Main > thread are being processed, even when 2 or more > clients are connected. SimpleXMLRPCServer is single threaded. If you want to create a multi-threaded version then create a subclass like this: class ThreadedServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer): pass > Is it the class it self or something else I should > have know? You really aren't providing very much information here, so it's hard to saw. Trying doing this in Python on your Linux machine and on Windows: import sgmlop What did that do on each? Cheers, Brian From kirk at strauser.com Tue May 11 16:00:06 2004 From: kirk at strauser.com (Kirk Strauser) Date: Tue, 11 May 2004 20:00:06 GMT Subject: Cash Register References: <d1bd056c.0405111032.3b2c411f@posting.google.com> Message-ID: <871xlq4tyf.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-05-11T18:32:33Z, RQuinn15 at optonline.net (Ryan Q.) writes: > It works, i'm just posting it hoping someone could do better. Of that I'm sure. :-) > while b != 0: b never goes to 0. Your variables have meaningless names. You misspelled 'SALES'. I would not give that a high grade. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAoTBY5sRg+Y0CpvERAtA1AJ43lt8H7JpoZu0snjAM299mn1CIiwCeIhd3 uCTxtus9K7uemQ9/4xozk30= =OJ21 -----END PGP SIGNATURE----- From nid_oizo at yahoo.com_remove_the_ Wed May 26 09:35:30 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 26 May 2004 09:35:30 -0400 Subject: Update with pickle In-Reply-To: <ljWsc.39527$tb4.1256693@news20.bellglobal.com> References: <AoIsc.27189$tb4.933533@news20.bellglobal.com> <GYJsc.72376$Qc.2938525@twister1.libero.it> <LoKsc.27890$tb4.968272@news20.bellglobal.com> <aSMsc.42$Rp4.28350@monger.newsread.com> <gaPsc.29315$tb4.1059921@news20.bellglobal.com> <OpUsc.2509$Hf.1455264@newshog.newsread.com> <ljWsc.39527$tb4.1256693@news20.bellglobal.com> Message-ID: <y21tc.41582$tb4.1325901@news20.bellglobal.com> Stefan Seefeld wrote: > Hi there (,hi Nicolas !), > ...I'm still lost: how is this interface-enriched declaration helping > in the task to retrieve ('internalize') an object's state from a pickle ? Hi Stefan, You're right, the example shows how to copy and it creates a new reference, so it doesn't help in the problem (I realized it when going back home yesterday). > Looking again into the docs for the pickle protocol, I wonder whether there > isn't any place in the __init__/__reduce__/__setstate__ magic to throw in > some meta-programming (i.e. an intelligent metaclass doing the job), or > providing > a clever __new__ operator that doesn't return a new object but an > existing one, > etc., etc. I just added a feature request on sf to have an updating load function in pickle. My preferred solution for now might still be the copy of __dict__ (I could copy slots also), it's simple and not intrusive (using proxies is, even if less a hack). However, the cleanest solution would be to implement your solution, but I have no idea how to do it for now. Regards, Nicolas From klapotec at chello.at Tue May 18 17:31:10 2004 From: klapotec at chello.at (Christopher Koppler) Date: Tue, 18 May 2004 21:31:10 GMT Subject: alternatives to making blocks like { } or other ?? References: <c8do0u$9fb$1@news.atman.pl> Message-ID: <jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com> On Tue, 18 May 2004 21:27:17 +0200, CYBER <usenet at zly_adres.com> wrote: >Hello > >Is there any other way under python to create blocks ?? > >instead of > >def sth(x): > return x > > > >could i use something else like > >def sth(x): >{ > return x >} > > >??? Of course there is another way! Just use # in front of your favourite block separator. I'm too lazy now to search the archives on who first suggested this, but it works: def something(x): #{ return x #} However, as with any and all block separators, this can lead to holy wars - is the above the 'one true way', or is it one of the following? All are valid Python... def something_else(x): #{ return x #} def something_or_other(x): #{ return x #} def something_completely_different(x): #( return x #} -- Christopher From milas_gi at hotmail.com Thu May 27 12:18:22 2004 From: milas_gi at hotmail.com (tutu) Date: 27 May 2004 09:18:22 -0700 Subject: MSIE6 Python Question References: <22b7fd40.0405231744.50d125f1@posting.google.com> <40b1697d$0$3131$61fed72c@news.rcn.com> <22b7fd40.0405240325.7b2b6376@posting.google.com> Message-ID: <5d1dd116.0405270818.46f43d5b@posting.google.com> > > I'm not sure why you need to go through IE, but maybe this will get you into > > the right direction: > > > > >>> import urllib > > >>> f = urllib.urlopen('http://www.python.org') > > > Sorry. I forgot to mention that I have tried that. The data I want is > being stripped out when I access the URL via urllib. Try something like this: It may be the site does not like urllib agent so try to pretend you are using IE. class URLHandler(urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler): pass agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)" request = urllib2.Request(url) request.add_header("User-Agent", agent) opener = urllib2.build_opener(URLHandler()) opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent htm = opener.open(request) opener.close() htm.read() Good Look From jfabiani at yolo.com Fri May 14 00:20:35 2004 From: jfabiani at yolo.com (john fabiani) Date: Fri, 14 May 2004 04:20:35 GMT Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: <dOGdnYnubp_LyD7dRVn-sw@powergate.ca> References: <mailman.457.1084369988.25742.python-list@python.org> <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <u_roc.7515$ft5.2134@newssvr27.news.prodigy.com> <87pt99tmyl.fsf@pobox.com> <jMxoc.47714$762.6724@newssvr29.news.prodigy.com> <SIqdnQilMuuDcD_dRVn-hA@powergate.ca> <0ADoc.47917$ef5.5210@newssvr29.news.prodigy.com> <dOGdnYnubp_LyD7dRVn-sw@powergate.ca> Message-ID: <nOXoc.8182$E_5.8143@newssvr27.news.prodigy.com> Peter Hansen wrote: > john fabiani wrote: > >> Peter Hansen wrote: >> >>> john fabiani wrote: >>> >>>> I'm guessing but I bet that simple text can be sent to a printer >>>> using Python (looping of course). But in today's world most users >>>> want graphics along with the data. Like an invoice with a logo, >>>> boxes around the bill to and ship to, along with column lines. So >>>> I'm hoping that someone has at least started a project to print >>>> reports. >>> >>> >>> >>> >>> That would be "ReportLab", I would think... Google for it. >>> >>> -Peter >> >> >> I book marked it - but it looks like a web solution?????? > > > I don't know quite what you mean by that, but it generates > PDF files, so I suppose it's at least broader than what > "web solution" implies to me. > > -Peter I answered to quickly. After review I'm sure that reportlab will work. John From andrew-pythonlist at puzzling.org Mon May 3 21:38:13 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 4 May 2004 11:38:13 +1000 Subject: Strategies for backwards compatibility when using pickle? In-Reply-To: <001401c4315f$c9632a70$9601a8c0@rimmer> References: <001401c4315f$c9632a70$9601a8c0@rimmer> Message-ID: <20040504013813.GB20102@frobozz> On Mon, May 03, 2004 at 05:41:34PM -0500, duncan wrote: [...] > > Does anyone have any advice on how to balance the conflicting interests > of the developers who want to keep evolving the object model and users > who need stable project persistance? > > It has been suggested that there may be a way to override pickle to deal > with an evolving object model but it would be nice to hear from others > who have tried to handle this problem. Twisted has a class in it for this, twisted.persisted.styles.Versioned, that seems to work well. You could possibly reuse it, or take a similar approach. There's a brief description of it in the API docs: http://twistedmatrix.com/documents/current/api/twisted.persisted.styles.Versioned.html -Andrew. From cs993442 at cs.yorku.ca Tue May 4 14:04:57 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Tue, 04 May 2004 14:04:57 -0400 Subject: Zero-fill shift Message-ID: <4097DB49.5010905@cs.yorku.ca> Hey all, I'm trying to port a (relatively) simple encryption algorithm from Java code (mainly because the algorithm will be used identically in both contexts). However, the code makes extensive use of Java's >>> operator, which shifts right and fills in the leftmost bits with zeroes. I've been unable to duplicate that effect in Python. Apparently, a >>> b is equal to the following: if a >= 0: return a >> b else: return (a>>b)+(2<<~b) However, Python complains when I try to do the left-shift, because ~b is often a negative number. Does anyone have a better idea about how I should go about doing this? Thanks! --Daniel From bart_nessux at hotmail.com Thu May 27 16:14:46 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 27 May 2004 16:14:46 -0400 Subject: remove item from list based on name In-Reply-To: <c95hr0$ein$03$1@news.t-online.com> References: <c95e2g$nm2$1@solaris.cc.vt.edu> <c95hr0$ein$03$1@news.t-online.com> Message-ID: <40B64C36.5030600@hotmail.com> Thanks Peter & Larry, Both of the examples work (lists and sets). I had forgotten that I had done something similar in the past with both functions. I find the set approach cleaner, but both approaches get the job done. Thanks Again! Peter Otten wrote: > Bart Nessux wrote: > > >>I am generating a list of file names... some of the files are locked by >>the OS (Windows XP) and I know the names of these files (NTUSER.DAT, >>ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is >>there a way that I can delete these items from the list based on their >>names? > > >>>>from sets import Set >>>>list(Set(["a", "b", "c"]) - Set(["c", "d"])) > > ['a', 'b'] > > Remember to pass all filenames through os.path.normcase() before trying the > above. > > Peter From gb at cs.unc.edu Mon May 24 09:56:40 2004 From: gb at cs.unc.edu (Gary Bishop) Date: 24 May 2004 09:56:40 -0400 Subject: ANN: Pyrex wrapper for the Aspell API Message-ID: <40b1ff18_3@news.unc.edu> http://prdownloads.sourceforge.net/uncpythontools/aspell-1.0.zip?download """A Pyrex wrapper for the aspell api. Pyrex is ****SO**** great! I wrote this in about 1 hour from the Aspell doc. I spent most of that hour figuring out that I needed to set the Aspell prefix to get it to work! Intended usage is: 1) create a spell_checker object for each document. 2) check a word by calling the check method 3) if you get 0 back indicating a misspelling, use the suggest method to get a list of possible correct spellings. 4) tell aspell about the correct choice so it can learn from your errors using the store_replacement method 5) add words to either the session dictionary or to your personal dictionary using the add_to_session or add_to_personal methods. import aspell sc = aspell.spell_checker() word = 'flarg' if not sc.check(word): print word, 'is incorrect' print 'suggestions include:', sc.suggest(word) To get this to build and work on Windows I downloaded the Windows version of aspell from http://aspell.net/win32/. I got the Full Installer, a dictionary, and the libraries for MS VisualC++ as separate downloads. I let the first two go to their default locations and I unpacked the zip file for the last into the C:\Program Files\Aspell top directory. Then I copied the aspell-15.dll from C:\Program Files\Aspell\bin to a folder on my path. You will also, of course, need Pyrex from http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/. With the above completed the standard 'python setup.py install' should build and install the extension. 23 May 2004 Gary Bishop """ From bart_nessux at hotmail.com Thu May 27 15:03:44 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 27 May 2004 15:03:44 -0400 Subject: remove item from list based on name Message-ID: <c95e2g$nm2$1@solaris.cc.vt.edu> Hi, I am generating a list of file names... some of the files are locked by the OS (Windows XP) and I know the names of these files (NTUSER.DAT, ntuser.dat.LOG, etc.) But, I don't know their position in the list. Is there a way that I can delete these items from the list based on their names? Thanks, Bart From tim.one at comcast.net Wed May 19 16:21:37 2004 From: tim.one at comcast.net (Tim Peters) Date: Wed, 19 May 2004 16:21:37 -0400 Subject: What's the meaning of Dutch in "The Zen of Python" In-Reply-To: <c8fkbn$1844$1@mail.cn99.com> Message-ID: <LNBBLJKPBEHFEDALKOLCIENMLBAB.tim.one@comcast.net> [Li Daobing] > Does anyone know what's the meaning of Dutch in "The Zen of Python"? > Thanks in advance In context, "Dutch" means a person from the Netherlands, or one imbued with Dutch culture (begging forgiveness for that abuse of the word). I would have said French, except that every French person I asked "how do you make a shallow copy of a list?" failed to answer alist[:] so I guess that's not obvious to them. It must be obvious to the Dutch, though, since it's obvious to Guido van Rossum (Python's creator, who is Dutch), and a persistent rumor maintains that everyone who posts to comp.lang.python is in fact also Dutch. The French people I asked about copying a list weren't Python users, which is even more proof (as if it needed more). Or, in other words, "obvious" is in part a learned, cultural judgment. There's really nothing universally obvious about any computer language, deluded proponents notwithstanding. Nevertheless, most of Python is obvious to the Dutch. Others sometimes have to work a bit at *learning* the one obvious way in Python, just as they have to work a bit at learning to appreciate tulips, and Woody Woodpecker impersonations. From chrish at cryptocard.com Fri May 28 10:24:13 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Fri, 28 May 2004 10:24:13 -0400 Subject: How to I print without newline ? In-Reply-To: <mailman.364.1085670411.6949.python-list@python.org> References: <mailman.364.1085670411.6949.python-list@python.org> Message-ID: <cYHtc.54800$tb4.2050060@news20.bellglobal.com> fowlertrainer at anonym.hu wrote: > I want to print, but without newline. I want to create a progress for > ftp, but the print is drop a newline for every percent. > I want like this: > > 0% 25% 50% 75% 100% > > But this happening: > 0% > 25% > 50% > 75% > 100% > > How to I prevent the newlines ? One option: s = [ 0, 25, 50, 75, 100 ] for p in s: percent = "%d%%" % ( p, ) print percent, Another option: from sys import stdout s = [ 0, 25, 50, 75, 100 ] for p in s: stdout.write( "%d%% " % ( p, ) ) stdout.write( "\n" ) -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. From dmq at gain.com Sat May 22 15:02:06 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 22 May 2004 12:02:06 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> Message-ID: <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> On Sat, 22 May 2004 18:28:33 -0000, "Donn Cave" <donn at drizzle.com> wrote: >Quoth David MacQuigg <dmq at gain.com>: >| import math >| >| def mypow(x, y): >| return x**y >| >| class MathA: >| pow = math.pow >| >| class MathB: >| pow = mypow >| >| ma = MathA() >| mb = MathB() >| >| print ma.pow(2,4) #=> >| 16.0 >| print mb.pow(2,4) #=> >| # TypeError: mypow() takes exactly 2 arguments (3 given) >| >| How would you explain this to non-CIS students in a class on circuit >| design, where there is very little time to discuss programming? > >I wouldn't. I would say > > "Classes allow you to create objects with their own functions, > called methods, that you write. Each function takes `self' > as its first parameter." > > "Here's a class:" > class A: > def __init__(self): > self.data = 'spud' > def hello(self): > print 'Hello, I am a class A', self.data > > "Classes can inherit functions from other classes:" > class B(A): > def __init__(self): > self.data = 'gerbil' > > "The actual object - a class `instance' - is created by invoking > the class name, applying arguments which will be passed to __init__." This is OK for the first example. I would leave the __init__ methods to the second example, but either way it will take about 8 pages to comfortably explain OOP ( maybe ten if I include the "robust programming" examples that JM says I must ). I would like students to understand Python at the level they can follow what is going on in a real program, and maybe write a few classes themselves. >Then I would go over that, showing what happens and why, until the >concepts introduced above seem to be clear for everyone. That would >conclude my treatment of classes. As an elementary language, there >are some slightly hard things to learn about Python, but this isn't >going to be one of them unless you make it hard. If you are saying we can totally ignore the different method forms, I think you are wrong. Bound and unbound methods, for example, will be needed in almost any sizable program. The need for static methods will arise when the student first writes a method that needs to work without a current instance. The example I showed is not intended to explain method binding, and I would not use it in an introduction to OOP. It probably won't even be "stumbled upon" in a normal program. I posted it only to show that even experts can get confused by Python's binding syntax. Are you not confused by this example? -- Dave From chuck.amadi at ntlworld.com Mon May 3 20:54:36 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Tue, 04 May 2004 01:54:36 +0100 Subject: PyXml - Processing xml and python Message-ID: <4096E9CC.1020308@ntlworld.com> Hi me again I realized I havent been passing the xml files . Cheers From grzegorz at ee.ualberta.ca Tue May 4 13:44:36 2004 From: grzegorz at ee.ualberta.ca (Grzegorz Dostatni) Date: Tue, 4 May 2004 13:44:36 -0400 Subject: Python sets. Message-ID: <Pine.LNX.4.44.0405041335170.29617-100000@e5-05.ee.ualberta.ca> I've got a problem. Some time ago (I'm a bit fuzzy about the date) I read about sets in python. I even tried the code. I remember it was something fairly simple - just a base data type (like list or dictionary). I vaguely remember it had a syntax similar to creating dictionaries. Problem is I can't find it anymore. I've searched around, but it doesn't seem to exist. I know of "import sets" and creating classes like that, but I'm sure it was a base data type. No import necessary. There were operators for basic set operations like set difference, division, etc. Please tell me I'm not loosing my mind. Please tell me that these kind of things did/still exist? Greg Advice is what we ask for when we already know the answer but wish we didn't. -- Erica Jong (How to Save Your Own Life, 1977) From boris.boutillier at arteris.net Thu May 27 09:14:39 2004 From: boris.boutillier at arteris.net (Boris Boutillier) Date: Thu, 27 May 2004 15:14:39 +0200 Subject: Compiling python without garbage collector Message-ID: <pan.2004.05.27.13.14.33.647539@arteris.net> Is there a not too hackish way to compile Python without the garbage collector overhead ? Setting Py_TP_FLAGS_HAVE_GC to 0 in Include/object.h is not working and the configure flag has disappear. The gc overhead in all objects (3 words) is not invisible in memory, and exceeds the true gain of the gc in my application, so I was looking for a way to benchmark the two situation ( with and without gc overhead), is this possible ? Boris From j.ezequiel at spitech.com Tue May 4 21:20:53 2004 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Wed, 5 May 2004 09:20:53 +0800 Subject: optional arguments to pattern.findall() Message-ID: <2484E6467140254CB22A328F5E18A235018B2C99@SPI-MAIL2003.SPITECH.COM> In a thread with subject RE: Difficulty Finding Python Developers, Bill Anderson wrote: >foo = re.compile(regex) >foo.findall(stringtosearchon,0,50)[-1] Where can I find documentation on the optional arguments to findall()? Have gone to http://python.org/doc/current/lib/module-re.html and did not find any mention of these. PythonWin 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32. From bjg at network-theory.co.uk Mon May 17 03:54:36 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 17 May 2004 08:54:36 +0100 Subject: benchmarks and questions for new python programmer References: <c5f75ecc.0405161733.4bc95347@posting.google.com> Message-ID: <87oeon8p4z.fsf@network-theory.co.uk> demarchi at duke.edu (stormslayer) writes: > Note that I didn't fiddle overmuch with any of the programs -- each > one took about 15 minutes to bang out on the keyboard. I'm hoping > that there is some obvious mistake in the way I used something in > python to account for the speed differential. It seems like a really, > really nice language, but orders of magnitude slower than C/C++ and a > 5x slowdown over Perl seems abusive... In general Perl and Python should have roughly the same performance. There is a profiler included with the standard Python distribution. You can use it on any script from the command-line, $ python /usr/lib/python<version>/profile.py yourscript.py with the appropriate path for <version> on your system. It should show where your program is spending all its time. See the Python Library Reference Manual for details of the profiler. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From mdfairch at sfu.ca Sat May 8 09:07:13 2004 From: mdfairch at sfu.ca (Mark Fairchild) Date: Sat, 08 May 2004 13:07:13 GMT Subject: Preferences Files References: <pan.2004.05.08.11.53.33.506494@sfu.ca> <m2zn8jxelh.fsf@unique.phony.fqdn> Message-ID: <pan.2004.05.08.13.07.13.273079@sfu.ca> On Sat, 08 May 2004 08:55:54 -0400, Heather Coppersmith wrote: > On Sat, 08 May 2004 11:53:34 GMT, > (SNIP) > See also <http://www.python.org/doc/current/lib/lib.html>. > > Regards, > Heather Thanks -- that's exactly what I was looking for. I knew there had to be something in the Python API -- it's just too complete to be missing a preferences system. -- Mark Fairchild <mdfairch at sfu.ca> Learn Lisp today! Uncle Turing wants you! From jbors at mail.ru Wed May 26 15:01:35 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Wed, 26 May 2004 23:01:35 +0400 Subject: Embedding Python at the OS level - build problems [success] In-Reply-To: <20040526181307.GA28031@unununium.org> Message-ID: <E1BT3eh-000O7N-00.jbors-mail-ru@f13.mail.ru> > Success! They said it can't be done. "Python is too big", they said. > "Too high level for an OS". And yet, it's done :) Here's a list of what It sounds just great !!. I was thinking about the same for a long time now. My idea was to have a full featured framework as jvm or .net vm that runs Python bytecode( .pyo files ). With most of the drivers written in Python. This way it can be placed into HW layer( Python processor ). The framework I'm building now( pymedia ) is meant to run under such an environment. It would be great if you can make generic x86 build for those who wants to try. Thanks. From mhammond at keypoint.com.au Tue May 4 07:51:33 2004 From: mhammond at keypoint.com.au (Mark Hammond) Date: Tue, 04 May 2004 21:51:33 +1000 Subject: Setting CPU Affinity In-Reply-To: <mailman.216.1083614048.25742.python-list@python.org> References: <mailman.216.1083614048.25742.python-list@python.org> Message-ID: <c7804f$85q$1@arachne.labyrinth.net.au> Laughlin, Joseph V wrote: > When I spawn a new process via spawnv(), how can I set the CPU affinity > for the newly-spawned process with python? The pywin32 (win32all) extensions include the win32 functions for this in the win32process module. You should be able to: * use spawmv to get the new process ID. * use win32process.OpenProcess() to get a process handle. * use win32process.SetProcessAffinityMask() to set the affinity. Mark. From mike at nospam.com Tue May 18 20:35:10 2004 From: mike at nospam.com (Mike Rovner) Date: Tue, 18 May 2004 17:35:10 -0700 Subject: install problem with moinmoin on win2k References: <k1xqc.68848$K%.17063@newssvr25.news.prodigy.com> Message-ID: <c8ea3r$8bo$1@sea.gmane.org> asdf sdf wrote: > pages = os.listdir(text_dir) > WindowsError: [Errno 3] The system cannot find the path specified: > 'data\\text/*.*' > No subdirectory 'text' inside 'data' was found. HTH, Mike From nuffsaid at phreaker.net Wed May 5 11:22:32 2004 From: nuffsaid at phreaker.net (Nuff Said) Date: Wed, 05 May 2004 17:22:32 +0200 Subject: docstrings for module variables / pydoc Message-ID: <pan.2004.05.05.15.22.31.643784@phreaker.net> Is it possible to associate a docstring with a module variable (e.g. a constant) and to make them both show up when generating the documentation with pydoc? (E.g. the string module seems to solve this problem by mentioning all public module variables in the module's docstring. But I would like to put the docstrings next to the module variables themselves.) Thanks in advance for your help! Nuff. From jollinofrenoamano at sogno.net Sun May 9 04:34:54 2004 From: jollinofrenoamano at sogno.net (Jollino) Date: Sun, 09 May 2004 10:34:54 +0200 Subject: Python for Nokia Series 60 Message-ID: <jollinofrenoamano-D94CBF.10345409052004@individual.net> Hello, I've seen several articles about Nokia starting to support Python for its Series 60 phones (like the 6600, for example), and I even found a blog entry with some screenshots of it: <http://www.mobilewhack.com/programming/python/python_on_nokia_screenshot s.html>. The bad thing is that there's no mention of it in the 'Forum Nokia' where you can usually download development packages and information from. Does anyone have fresh news about it? TIA Daniele -- Jollino - per rispondere togli il freno a mano Photo portfolio and posters at http://www.nicolucci.net From ny_r_marquez at yahoo.com Wed May 26 11:24:20 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 26 May 2004 08:24:20 -0700 Subject: Transparent PNG and PIL Message-ID: <8a27e309.0405260724.5a9c1fdc@posting.google.com> I am trying to create a simple script that Opens an existing PNG and resaves it with a transparent color. With the command line version of ImageMagic this is an easy endevor (and my current solution). I can simply do something like: convert -transparent black image.png image-transparent.png (That makes anything black transparent in the saved image.) It would seem that using PIL would make this simmilarly simple, but so far I have not found a simple clear explanation of how to do this. If someone has figured this out could you post it for the benefit of mankind. ;) On a somewat off topic matter (as far as Python goes), I see that transparent PNGs, as created by tools such as image magic, do not display transparent on MS Internet Explorer. I know that this is probably because of MS's draggin their feet on supporting standards. But, I noticed that with tools such as PaintShop Pro I can add transparency to a PNG, and have it show correctly in IE. Does it do this by in effect creating a proprietary PNG format? When adding transparency to the PNG file, PaintShop says that the image needs to be reduced to a single, paletted, background layer. It then decreases the color depth to 256 colors. And then allows one to set a color as transparent. When saving the image it warns that no alpha channel will be saved. Nevertheless, the transparency is saved correctly and displays correctly on all the tools I've tried. Can someone shed a little light on what is going on here? From seefeld at sympatico.ca Tue May 18 11:31:24 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 18 May 2004 11:31:24 -0400 Subject: error converting list to tuple In-Reply-To: <tVpqc.50410$8L3.24856@newssvr29.news.prodigy.com> References: <mailman.48.1084889922.6949.python-list@python.org> <tVpqc.50410$8L3.24856@newssvr29.news.prodigy.com> Message-ID: <a3qqc.34397$325.832599@news20.bellglobal.com> john fabiani wrote: > Stefan Seefeld wrote: > >> hi there, >> >> I'm trying to convert a tuple to a list, >> and get a 'TypeError: list objects are unhashable'. >> >> Can anybody enlighten me as to the possible causes >> for this ? Where does hashing come into play during >> this conversion ? >> >> Could it be that my runtime is corrupted ? >> The code is executed from within a C++ extension >> module I'm developing... >> >> Thanks for any help, >> Stefan >> >> PS: I'm using python 2.3.3 in case that matters >> >> > God I can't believe I think I can answer this question: well, unfortunately that wasn't my question <wink/> I do: t = ('hello',) l = list(t) which is the standard tuple->list conversion. And yes, it does work when I run that code in isolation. The point is that the above, as simple as it looks, fails with said exception in a very specific context (I call this code from within a C++ extension module), so I'm wondering whether I could have messed up the python runtime somehow or whether there are other possible explanations for the exception. Regards, Stefan From lesstif-admin at lesstif.org Fri May 21 02:06:19 2004 From: lesstif-admin at lesstif.org (lesstif-admin at lesstif.org) Date: Fri, 21 May 2004 08:06:19 +0200 (CEST) Subject: Request to mailing list Lesstif rejected Message-ID: <200405210606.i4L66J6S034876@mxzilla7.xs4all.nl> Your request to the Lesstif mailing list Posting of your message titled "Important" has been rejected by the list moderator. The moderator gave the following reason for rejecting your request: "Non-members are not allowed to post messages to this list." Any questions or comments should be directed to the list administrator at: lesstif-admin at lesstif.org From tjreedy at udel.edu Mon May 17 02:11:38 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 May 2004 02:11:38 -0400 Subject: benchmarks and questions for new python programmer References: <c5f75ecc.0405161733.4bc95347@posting.google.com> Message-ID: <c89l2r$ir3$1@sea.gmane.org> "stormslayer" <demarchi at duke.edu> wrote in message news:c5f75ecc.0405161733.4bc95347 at posting.google.com... > I've been considering a shift to python. I currently use c++builder > (borland) or perl. I do computational models / statistics > programming, and was interested in python b/c it > > a. has a library that connects to the R stats package > b. has code that seems way more readable than anything else > > There is, however, at least for my work, a hard constraint. Execution > time for large data sets / lots of iterations of a model needs to be > reasonabe. For floating point calculations, and possibly integer, you may want to use Numerical Python, or maybe the replacement-in-progress Numarray, or SciPy, or PyRex, or Weave, or possibly Boost.Python -- besides the suggestion of Psyco (which is what I personally would try first, especially for iterative integer work). So, I wrote a program to test it out (appended to the > bottom of this email). As I said, this is my first python program. > I'm sure it is terrible, but in many ways, you hope that the > interpreter / compiler corrects some errors (or the langauge isn't > that easy to use after all). > > Benchmarks (for the paramter settings in the file): > > C++builder 6.0: 3 seconds > Perl (ActivePerl 5.6.1.638): 14 seconds > Python (ActivePython 2.3.2 Build 232): 1 minute 13 seconds Are you getting the same results from each, so that you know they are at least functionally equivalent if not algorithmically equivalent? Without identical rngs, this would require storing a sequence of outputs from one in a disk file for each program to use. > Python code: > > #!/usr/bin/env python > import random > > pop=[] # popluation of agents; initially empty list You might as well comment this out since init rebinds this anyway. Ditto for gold and standard > N = 10000 # population size > ep = .05 # mutation rate > its = 100 # number of times through the main loop > gold=0 # initial number of gold adopters; (1-gold) = silver > adopters > standard=0 # either 1 for gold or 2 for silver > shifts=0 # number of regime shifts > > def init_all(): # init globals > global pop, gold, standard > pop = [] pop = N*[None], followed by pop[i] = x in loop might be faster. so would be pend = pop.append followed by pend(1) and pend(2) in loop in either case, rint = random.randint followed by rint(1,2) in loop would definitely be so. making pop, gold, and standard local vars instead of globals wil be faster. then end with return pop, gold, standard > gold = 0 > for i in range(N): > if random.randint(1,2) == 1: > pop.append(1) > gold=gold+1 gold += 1 might be (should be?) faster here and below > else: pop.append(2) > if gold>N/2: standard=1 > else: standard=2 # if tie, silver wins > # print "Initial Population of Gold Users: ", gold > # end function init_all > > def one_choose(): make pop, gold, standard inputs and shifts a local same comment about lifting attribute lookups out of loop with rint,rdom = randon.randint, random,random > global pop, standard, gold, shifts > for i in range(its): > temp = random.randint(0,N-1) > tempval = pop[temp] > old_stand = standard > if random.random()<ep: > if random.random()<0.5: > pop[temp]=1 > if tempval!=pop[temp]: > gold=gold+1 > if gold>N/2: standard=1 > else: > pop[temp]=2 > if tempval!=pop[temp]: > gold=gold-1 > if gold<N/2: standard=2 > if standard!=old_stand: shifts=shifts+1 # check for regime > shift after each agent chooses anew > else: > if gold>N/2: > if pop[temp]!=1: > pop[temp]=1 > gold=gold+1 > if gold>N/2: standard=1 > else: > if pop[temp]!=2: > pop[temp]=2 > gold=gold-1 > if gold<N/2: standard=2 > if standard!=old_stand: shifts=shifts+1 # check for regime > shift after each agent chooses anew > # print "Final Population of Gold Users: ", gold > # end function one_choose > > # start main loop > > > for i in range(1000): > init_all() > one_choose() > print "Number of regime shifts: ", shifts > -- > http://mail.python.org/mailman/listinfo/python-list > From jarausch at skynet.be Wed May 12 11:28:56 2004 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 12 May 2004 17:28:56 +0200 Subject: Can Python be compiled by a C++ compiler ? Message-ID: <40A242B8.30703@skynet.be> Hi, having read http://www.python.org/doc/current/ext/ext.html by Guido van Rossum and Fred Drake, I got the impression I should compile Python with g++ since section 1.11 indicates that otherwise the constructor of a global or static object (of an extension in C++) won't be called. Now trying to build Python (CVS version) with g++ fails. E.g., one problem is in Parser/pgen.c line 364 with a typical C-like confusion of types and variables when it declares ss_arc *ss_arc where ss_arc is defined by a previous typedef. A C++ compiler won't accept this. Do I miss something? Many thanks for your comments, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From max at alcyone.com Sat May 15 23:03:45 2004 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 May 2004 20:03:45 -0700 Subject: Stackless python and microthreads References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <just-AEC793.15303514052004@news1.news.xs4all.nl> <2gk1k2F3li0jU1@uni-berlin.de> <just-0A0302.16084014052004@news1.news.xs4all.nl> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <87oeopl44w.fsf@vercingetorix.caesar.org> <tLadnSt3sul7SjvdRVn-sw@powergate.ca> Message-ID: <40A6DA11.93D47DC4@alcyone.com> Peter Hansen wrote: > Which raises the question, how do you pronounce "nuevo"? > > (Perhaps noo-VOH, as in the French nouveau?) Noo-WAY-voh. (More like NWAY-voh, actually.) -- __ 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 quality, not the longevity, of one's life is what is important. -- Dr. Martin Luther King, Jr. From tjreedy at udel.edu Sat May 22 10:57:35 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 May 2004 10:57:35 -0400 Subject: Documentation/Info on this sign References: <c8iims$24i$1@solaris.cc.vt.edu><1O-dnXHH1_PKTjHd4p2dnA@powergate.ca><40ACED36.5030706@hotmail.com> <c8lhq8$g7m$07$1@news.t-online.com><VYedndUn_vtmyjPdRVn-tA@powergate.ca> <c8mr7d$ueh$06$1@news.t-online.com> Message-ID: <c8npp1$p7p$1@sea.gmane.org> "Peter Otten" <__peter__ at web.de> wrote in message news:c8mr7d$ueh$06$1 at news.t-online.com... > Upon reflection it seems unlikely that an antivirus tool would resolve > shortcuts, but the basic idea that twice as many files being seen is an > indication of files being seen twice _somehow_ still seems compelling. I have a memory (about a year ago) of (McAfee?) AV scanning every file twice. Not sure why or settings used, but I think it applied two separate algorithms in separate passes. Don't remember if doubled number. More concerned by nasty infection it found;-) tjr From lbates at swamisoft.com Tue May 11 10:22:14 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 11 May 2004 09:22:14 -0500 Subject: import question References: <mailman.374.1084112165.25742.python-list@python.org> Message-ID: <QfudnYRjc50IfD3d4p2dnA@comcast.com> I do this by putting what you refer to as "staging" on separate logical drive (windows) or with a symlink (linux) and placing the root in my pythonpath environment. Then I don't have to change my code, just the pythonpath. HTH, Larry Bates Syscon, Inc. "Ksenia Marasanova" <ksenia at ksenia.nl> wrote in message news:mailman.374.1084112165.25742.python-list at python.org... > Hi list, > > I'd appreciate any advice on the following: > > In the "live" environment, I have some Python scripts which make use of > Python packages. The directory structure is something like that: > /live/ > /live/py/ > /live/lib/ > > There is a .pth file in the Python site-packages directory, which > contains "/live/lib". > In the scripts, packages are imported with a normal import statement, > like this: > > from module.submodule import someclass > > Nothing unusual. > > Now I want to use the same server for "staging" environment. The > additional directory structure will be: > /staging/ > /staging/py/ > /staging/lib/ > > After testing, files will be copied from "staging" to "live". > Now my question: what would be the proper way to construct the import > statement, so no modifications will be needed when copying files? I > first thought about relative import (from ..lib import something) , but > it seems not (yet) to be an option :-) > > > Appreciate any tips! > > Thanx, > Ksenia. > > > From rogerb at rogerbinns.com Tue May 11 16:31:07 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Tue, 11 May 2004 13:31:07 -0700 Subject: scraping display to obtain all on-screen text using OCR References: <27e4d2e8.0405111130.7081968e@posting.google.com> Message-ID: <4pp7n1-er2.ln1@home.rogerbinns.com> Jonathan Epstein wrote: > I would like to perform a more classical type of "screen scraping" > than what most people now associate with this term. I only want to > find all the text on the current screen, and obtain associated screen > coordinates. This probably must be done using OCR. > > This need only run on Windows. You can use the accessibility APIs to get that information. Start at http://weblogs.asp.net/oldnewthing/archive/2004/04/23/118893.aspx > A fairly-pure Python solution would be > ideal because most of the software which would use this functionality > is also written in Python. You may be able to do it using win32all, ctypes or worst case a SWIG wrapper. Roger From ekoome at yahoo.com Wed May 12 04:42:02 2004 From: ekoome at yahoo.com (Eric) Date: 12 May 2004 01:42:02 -0700 Subject: Python dynamic function selection Message-ID: <b0457a31.0405120042.31f97c@posting.google.com> The following example will explain what i want to do: >>> def func(): print "true" >>> rules=(func,) >>> for rule in rules: rule I expect the final function to print true, but instead i have <function func at 0x00DC6EB0> How do i get it to print true. I know if i had parameters in rule like: >>> def func(var): print var >>> rules=(func,) >>> for rule in rules: rule("true") it will work. But in my case i don't need to pass any parameters. How do i get the former method to print instead of returning a function? Eric From nicksjacobson at yahoo.com Sat May 1 01:52:09 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 30 Apr 2004 22:52:09 -0700 Subject: Help with C API Message-ID: <f8097096.0404302152.38dd1eae@posting.google.com> In the Python Cookbook, Luther Blisset wrote a very useful class with the Python C API. It takes a Python list of elements and copies it member by member into a C array. Here it is, (slightly modified by me): static PyObject *totaldoubles(PyObject *self, PyObject *args) { PyObject *seq, *item, *fitem; double *dbar, result; int i, seqlen; if (!PyArg_ParseTuple(args, "O", &seq)) return NULL; seq = PySequence_Fast(seq, "argument must be iterable"); if (!seq) return NULL; seqlen = PySequence_Fast_GET_SIZE(seq); dbar = malloc(seqlen * sizeof(double)); if (!dbar) { Py_DECREF(seq); return NULL; } for (i=0; i < seqlen; i++) { item = PySequence_Fast_GET_ITEM(seq, i); if (!item) { Py_DECREF(seq); free(dbar); return NULL; } fitem = PyNumber_Float(item); if (!fitem) { Py_DECREF(seq); free(dbar); return NULL; } dbar[i] = PyFloat_AS_DOUBLE(fitem); Py_DECREF(fitem); } Py_DECREF(seq); result = total(dbar, seqlen); /*call a C function using this array*/ free(dbar); return Py_BuildValue("d", result); } I'd like to do the reverse: take an C array (say, with 100 elements) and copy its elements into a Python list. But I don't know where to start...there's no PySequence_Fast_INSERT or even PySequence_Insert function, for example. Can I create an empty list in the API or should I just pass one in from Python? Can someone please help with this? Thanks in advance!! --Nick From simonettil at tiscali.it Thu May 27 09:36:26 2004 From: simonettil at tiscali.it (Luca Simonetti) Date: Thu, 27 May 2004 13:36:26 +0000 (UTC) Subject: Fortran-compiled DLLs in Python References: <c94crp$q8a$1@canarie.caspur.it> <mailman.353.1085653633.6949.python-list@python.org> Message-ID: <6b406be66698d75310fc1dd57214a08d.90847@mygate.mailgate.org> Hi Thomas! an answer from the true creator of the ctypes module - nice! anyway, we tried implementing your solution and got the following Traceback Error: >>>h2o.WATER(c_double(40.0), c_double(1.0), c_int(2),byref(dierr), byref(sig), prop) Traceback (most recent call last): File "<interactive input>", line 1, in ? WindowsError: exception: access violation which would seem to be the classical exception raised through a failed function call...? allthebest luca (+stephen) -- Posted via Mailgate.ORG Server - http://www.Mailgate.ORG From andrew-pythonlist at puzzling.org Mon May 3 20:01:14 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 4 May 2004 10:01:14 +1000 Subject: Method binding confusion In-Reply-To: <c760s2$ev4$04$1@news.t-online.com> References: <mailman.212.1083600570.25742.python-list@python.org> <c760s2$ev4$04$1@news.t-online.com> Message-ID: <20040504000114.GA18723@frobozz> On Mon, May 03, 2004 at 07:52:02PM +0200, Peter Otten wrote: [...] > > The machinery behind the observed behaviour is now somewhat clearer - I > think you can predict a function's behaviour as a method by checking > hasattr(func, "__get__"). But still the *reason* (or simply use-case) for > this dichotomy of functions (to me) remains unclear. Why are not all > functions created equal? I suppose that BuiltinFunctionType is probably slightly simpler and faster this way. After all, how often is an instance of a user-defined class going to be right type to be the first argument to a builtin function? (I can think of contrived cases, but I've never come across a need for this behaviour, which is why I'd never noticed it was missing until this thread.) That's just me speculating, though... Interestingly, >>> import types >>> types.BuiltinFunctionType is types.BuiltinMethodType True (types.BuiltinFunctionType seems to distinguish between functions and methods by looking at its __self__ attribute; builtin functions have a __self__ of None). -Andrew. From nav+posts at bandersnatch.org Fri May 7 10:25:00 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 07 May 2004 10:25:00 -0400 Subject: Python job opening at GPO in Washington, DC References: <b16e4ef7.0403030957.21a0c216@posting.google.com> Message-ID: <m3pt9gmi0z.fsf@tanelorn.bandersnatch.org> I've been way behind on reading this newsgroup, but I see someone noticed the posting for someone who will be my co-worker and partner in advocacy... steve at ferg.org (Stephen Ferg) writes: > I just saw this opening posted. It is a Federal government position > (GS-13) at the Government Printing Office, Washington, DC, right > across the street from where I work. We just got to interviewing for this position (government schedule, obviously) and there were very few applicants with real-world Python experience. Maybe I should have campaigned more heavily on this newsgroup. I've been working to get Python accepted here at GPO, my main arguments have been maintainability, portability, and developer productivity. 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 r_b_lawson at yahoo.com Tue May 4 17:39:43 2004 From: r_b_lawson at yahoo.com (Rick Lawson) Date: 4 May 2004 14:39:43 -0700 Subject: table widget in Tkinter ? References: <ac259413.0405040811.4e54137a@posting.google.com> Message-ID: <14460e6d.0405041339.7512bd9c@posting.google.com> s_gherman at yahoo.com (Sorin Gherman) wrote in message news:<ac259413.0405040811.4e54137a at posting.google.com>... > Is there any table/list-control/list-view widget available in Tkinter? > That is, something with several lines and columns (maybe similar to > wxlistctrl in wxWindows)? > > Thanks in advance, > /sorin Check out http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 Also http://tkinter.unpythonic.net/wiki/ContributedWidgets Regards, Rick From jzgoda at gazeta.usun.pl Sun May 23 13:12:25 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 23 May 2004 17:12:25 +0000 (UTC) Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <c8obsk$i6k$1@atlantis.news.tpi.pl> <pgs0b0dr6ur10tovkofhi4r2v72egsb8ep@4ax.com> <c8pt6e$r4f$1@atlantis.news.tpi.pl> <koi1b01kvljj9bh3440r7soitg15j8doi1@4ax.com> Message-ID: <c8qm1o$6kr$1@atlantis.news.tpi.pl> Manlio Perillo <NOmanlio_perilloSPAM at libero.it> pisze: >>>>You must use date in UTC format. >>> This is the date format used by the server cookie! >>See http://www.w3.org/TR/NOTE-datetime on how should date look in >>cookies. If date is not in valid format, the module functions may have >>trouble decoding it. > > It is not a my problem! As you see, it's your problem, since it's you who cann't decode this cookie. ;) > The web server follow the Netscape specification for Cookies and in > this spec the date is in the format I have posted. Netscape is not internet God, W3C is. I never tried to read cookies using Cookie module (I used Python only for writing), so I cann't help more here. Good luck. -- Jarek Zgoda http://jpa.berlios.de/ From mcherm at mcherm.com Thu May 6 12:45:40 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 6 May 2004 09:45:40 -0700 Subject: rectangle layout algorithm? Message-ID: <1083861940.409a6bb43267f@mcherm.com> Richard Taylor writes: > I need an algorithm to layout a collection of rectangles (images) within a > bounding rectangle (sheet of paper). Diez Roggisch replies: > That smells like a 2d-instance of the knapsack-problem, also called > cuttingstock-problem - which is np-hard. In other words: There is no such > thing like a general solution to this. Diez, I believe you are mistaken about what it means to be np-hard. It has nothing to do with whether the problem can be solved, just about how long it may take for large input sizes. All of which may be completely irrelevent if the number of rectangles to be laid out is reasonably small (as it would be for creating a photo layout or something like that). Richard, I don't think that you meant to say what you said, but the actual answer is exactly what you said. Your words were "I need an algorithm to...". I suspect that you meant "I need some code to...". But really, before you can code it, you need to define what algorithm you want the code to implement! For example, one common way of laying things out is to line them up horizantally, shrinking things so they fit. This is what the BoxLayout class in Java does. This algorithm would be easy to express in Python: # untested pseudo-code follows def layout(bounds, images): totalImageWidth = sum([i.width for i in images]) hScaleFactor = float(totalImageWidth) / bounds.width xPos = 0 for image in images: image.setXPos(xPos) image.setYPos(0) image.setWidth(int(image.width * hScaleFactor)) if image.height > bounds.height: image.setHeight(bounds.height) xPos += image.width Of course, I'm guessing that this isn't what you meant at all... if you'd wanted something this simple you wouldn't have needed to ask. But without knowing what algorithm you DO need, there's no way to answer the question. So you are correct after all: you DO need an algorithm to... -- Michael Chermside From uche at ogbuji.net Mon May 10 12:33:43 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 10 May 2004 09:33:43 -0700 Subject: A simple xml.dom.minidom question References: <c7dbc8$i4l$1@sunnews.cern.ch> <409ab05f$0$24803$9b622d9e@news.freenet.de> <c7fhhn$548$1@sunnews.cern.ch> Message-ID: <d116fbae.0405100833.78114cf0@posting.google.com> Paulo Pinto <paulo.pinto at cern.ch> wrote in message news:<c7fhhn$548$1 at sunnews.cern.ch>... > There are a set of applications that use XML files > as their configuration mechanism. Inside these files > there is some data that isn't standard XML but it in > form expected by the tools. > > For example > > <values> > "value1" "value2" > </values> > > Now, if I use writexml(), I get the following, > > <values> > "value1" "value2" > </values> > > Which I understand, because it is how it should be > in standard XML. > > However I am really required to use the first form. > > So I guess that the only way with xml.dom.minidom is > to write my own code to tranverse the XML tree. Right? FWIW, you can do this if you use the 4XSLT Python API to generate XML as discussed in: http://www.xml.com/pub/a/2003/10/15/py-xml.html For one thing, this API does not escape quotes in content. And if you need to preserve other characters from escaping you can do so by telling the output handler to always output values as a CDATA section, which would yield <values><![CDATA[ "value1" "value2" ]]></values> The Python would be along the lines of import sys from Ft.Xml.Xslt.XmlWriter import XmlWriter from Ft.Xml.Xslt.OutputParameters import OutputParameters oparams = OutputParameters() oparams.cdataSectionElements = [u'values'] writer = XmlWriter(oparams, sys.stdout) writer.startDocument() writer.startElement(u'values') writer.text(u'"value1" "value2"') writer.endElement(u'values') writer.endDocument() --Uche http://uche.ogbuji.net From fumanchu at amor.org Tue May 4 10:34:01 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 4 May 2004 07:34:01 -0700 Subject: fixedpoint cmp conundrum Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E562096@opus.amorhq.net> [Tim Peters] > > 4. Define an __eq__ method, which returns False if its arguments > > are non-comparable. [Silly me] > Looking at the SourceForge page, I think this is addressed by Bug > #887290: > > > def __eq__(self, other): > if isinstance(other, FixedPoint): > xn, yn, p = _norm(self, other, FixedPoint=type(self)) > return not(cmp(xn, yn)) > else: > return False > > def __ne__(self, other): > if isinstance(other, FixedPoint): > xn, yn, p = _norm(self, other, FixedPoint=type(self)) > return cmp(xn, yn) > else: > return True Duh. I should have said: def __eq__(self, other): if isinstance(other, FixedPoint): xn, yn, p = _norm(self, other, FixedPoint=type(self)) return xn == yn else: return False def __ne__(self, other): if isinstance(other, FixedPoint): xn, yn, p = _norm(self, other, FixedPoint=type(self)) return xn != yn else: return True ..using == and != instead of cmp(). I need to: [] Stop working so late [] Stop drinking so much Diet Coke [] Stop putting so much rum in the Diet Coke [] Go back to school ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org -- http://mail.python.org/mailman/listinfo/python-list From grante at visi.com Thu May 13 23:58:10 2004 From: grante at visi.com (Grant Edwards) Date: 14 May 2004 03:58:10 GMT Subject: struct doesn't handle NaN values? References: <mailman.543.1084503089.25742.python-list@python.org> Message-ID: <40a443d2$0$8693$a18e6209@newsreader.visi.com> In article <mailman.543.1084503089.25742.python-list at python.org>, Tim Peters wrote: > There's nothing new to be said about any of this, and I don't > have time to pursue it regardless. If you want to commit to > improving the story here, please do. Others have tried, over > the course of a decade, but nothing has come of it apart from > the PEP 754 reference implementation (which doesn't address > struct or pickle issues). It's a large task to give Python a > *good* x-platform 754 story, but it would indeed be easy to > make large isolated improvements in small areas on major > platforms. I'd like to work on the pack/unpack code so that pickle/strcut handle NaNs and Infinities. It should be easy enough on platforms that use 754 as the native format, and seems like a reasonable first step. However, I've got a gcc patch to finish first, and ... -- Grant Edwards grante Yow! Put FIVE DOZEN red at GIRDLES in each CIRCULAR visi.com OPENING!! From johan at svedberg.pp.se Thu May 13 14:39:03 2004 From: johan at svedberg.pp.se (Johan Svedberg) Date: Thu, 13 May 2004 18:39:03 +0000 (UTC) Subject: Help with Distutils References: <slrnca77ma.5il.johan@svedberg.pp.se> <oiqcn1-0ki.ln1@wintermute.g2ctech> Message-ID: <slrnca7g67.5il.johan@svedberg.pp.se> * Jorge Godoy <godoy at ieee.org>: > On Qui 13 Mai 2004 13:14, Johan Svedberg wrote: > >> I just started playing around with Distutils and there is one thing I >> could use some help with. I'm wondering if there is some convenient >> way to access the directories where the data_files was installed? > > Could you explain when and why you are trying to do that? Well, the reason is that I've told setup.py to install a bunch of templates in <prefix>/share/myapp/templates/ and I want to make sure that myapp can find these no matter what <prefix> is. -- Johan Svedberg, johan at svedberg.pp.se, http://johan.svedberg.pp.se/ From richie at entrian.com Fri May 7 12:54:10 2004 From: richie at entrian.com (Richie Hindle) Date: Fri, 07 May 2004 17:54:10 +0100 Subject: MySQL vrs SQLite In-Reply-To: <slrnc9l18b.1fk.ramen@lackingtalent.com> References: <mailman.283.1083787205.25742.python-list@python.org> <slrnc9is2h.8mg.ramen@lackingtalent.com> <mailman.304.1083838565.25742.python-list@python.org> <slrnc9l18b.1fk.ramen@lackingtalent.com> Message-ID: <0mim90d85lhft3mjh92crk6vngmmjo8uft@4ax.com> [Dave] > [long and reasonable argument snipped] > Surely you don't expect him to assume that since he already > uses Python, a dynamically typed (read: not *typeless*) language, he does > not need to consider the repercussions that switching from MySQL to SQLite > will have on his program, because of a few weak analogies and claims of > brain-fitting? Not at all. I wasn't advocating blindly accepting typelessness as something that doesn't need to be considered. I was saying that many of the same practices that go into writing a decent Python application also apply to using a typeless database. To put it another way: although it might at first appear that there's a whole slew of new dangers involved, in fact they're mostly the same dangers that Python programmers are already familiar with. Having read your arguments, I still think that's true. -- Richie Hindle richie at entrian.com From kdahlhaus at yahoo.com Thu May 27 13:43:35 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 27 May 2004 10:43:35 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 26) References: <10b9vus8q0kne61@corp.supernews.com> Message-ID: <283adf56.0405270943.2f905189@posting.google.com> Cameron and the other authors: Just wanted to thank you guys for putting together the Python-URL. It's something I look forward to each week and it also serves a greater purpose by helping to tie the python community together. From fumanchu at amor.org Sun May 9 16:12:22 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 9 May 2004 13:12:22 -0700 Subject: Replacing "illegal characters" in html Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E5620C6@opus.amorhq.net> > BenO wrote: > > I'm new to python and need to write a function to replace > > certain characters > > in a string (html). > > > > The characters I need to replace come from MS Word copy & > > paste and are: > > > > ' (Left quote) > > ' (Right quote) > > Double Left quotes > > Double Right quotes > > > > Can anyone help me or point me in the right direction on an > > efficient way of doing this? And I answered: > The two methods most often used are 1) the .replace method of strings, > and 2) regular expressions. > > 1) The .replace method: > > >>> replacemap = {""": '"', """: '"', "'": "'", "'": "'"} > >>> map(ord, replacemap.keys()) > [145, 147, 146, 148] > >>> test = ""hl" 'oh'" > >>> for k, v in replacemap.iteritems(): > ... test = test.replace(k, v) > ... > >>> test > '"hl" \'oh\'' > > 2) Regular Expressions: > > >>> import re > >>> test = ""hl" 'oh'" > >>> test = re.sub("[""]", '"', test) > >>> test = re.sub("['']", "'", test) > >>> test > '"hl" \'oh\'' But of course, the email gateway munged all the quotes. So here's a better version: 1) The .replace method: >>> replacemap = {"\x91": '"', "\x93": '"', "\x92": "'", "\x94": "'"} >>> map(ord, replacemap.keys()) [145, 147, 146, 148] >>> test = "\x91hl\x93 \x92oh\x94" >>> for k, v in replacemap.iteritems(): ... test = test.replace(k, v) ... >>> test '"hl" \'oh\'' 2) Regular Expressions: >>> import re >>> test = "\x91hl\x93 \x92oh\x94" >>> test = re.sub("[\x91\x93]", '"', test) >>> test = re.sub("[\x92\x94]", "'", test) >>> test '"hl" \'oh\'' Robert Brewer MIS Amor Ministries fumanchu at amor.org From cm at leetspeak.org Fri May 14 10:17:19 2004 From: cm at leetspeak.org (Michael Walter) Date: Fri, 14 May 2004 16:17:19 +0200 Subject: Stackless python and microthreads In-Reply-To: <just-0A0302.16084014052004@news1.news.xs4all.nl> References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <just-AEC793.15303514052004@news1.news.xs4all.nl> <2gk1k2F3li0jU1@uni-berlin.de> <just-0A0302.16084014052004@news1.news.xs4all.nl> Message-ID: <2gk2mtF3mcnaU1@uni-berlin.de> Just wrote: > In article <2gk1k2F3li0jU1 at uni-berlin.de>, > Michael Walter <cm at leetspeak.org> wrote: > > >>Just wrote: >> >>>In article <2gjokgF3mvvdU1 at uni-berlin.de>, >>> Michael Walter <cm at leetspeak.org> wrote: >>> >>>>Would you have an idea on how a higher-level replacement for >>>>continuations in web application development? I'm excited (and _not_ >>>>being any sarcastic or stuff, honestely!). >>> >>>Co-routines. >> >>Would you care to elaborate? Can you store the state of a coroutine and >>resume it multiple times? > > > You can resume a co-routine multiple times just like you can resume > generators mutliple times, but that's something completely different > from restarting a continuation multiple times. Well, I think you would want to resume it multiple times based on a given state (essentially like resuming a stored continuation). > When you mentioned continuations for web programming, I assumed you > meant their ability to turn flow control inside out (allowing to write > event-based networking code in a more natural way). Co-routines are a > much nicer abstraction for that than continuations. Would you have some links/papers for me in regard to web programming and coroutines? Some quick googling didn't bring anything up (but maybe I'm just too tired). What I meant was using continuations for "linear" code flow, such as mentioned in http://www.ai.mit.edu/~gregs/ll1-discuss-archive-html/msg02456.html, described in http://www.double.co.nz/scheme/modal-web-server.html and applied in Seaside, Borges, PLT Web Server etc. Cheers, Michael From shalabh at cafepy.com Sun May 9 21:31:34 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 09 May 2004 18:31:34 -0700 Subject: What's the difference? In-Reply-To: <409EB546.B8367374@shaw.ca> References: <409EB546.B8367374@shaw.ca> Message-ID: <c7mlrl$80p$1@sea.gmane.org> SeeBelow at SeeBelow.Nut wrote: > between this: > > name = "C" > > and this: > > name = StringVar() > name.set("C") > > I hope someone can explain that to me. I couldn't run your code. >>> name = StringVar() Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'StringVar' is not defined Where did you get StringVar from? > Thanks, > > Mitchell Timin > -- Shalabh From dsmith at programmablesolutions.net Tue May 4 16:27:32 2004 From: dsmith at programmablesolutions.net (David Smith) Date: Tue, 04 May 2004 15:27:32 -0500 Subject: pyxmms trouble Message-ID: <1083702451.2526.9.camel@gondor> Hi: I am a newbie to python and in general programming. My problem is that I am trying to use the pyxmms remote to add songs to the xmms playlist. However, no matter whether I open the interpreter or put it in a file and run the script the output is the same. It just sits there with no error msg of any kind and doesn't add the file to the playlist. I then have to ctrl-c to break it and alot of times this makes the keyboard stop working and I have to restart X to get it working again. Here is the I'm using code: import os import xmms.control import time import wx #Start xmms os.popen2('/usr/bin/xmms') time.sleep(5) print xmms.control.is_main_win(0) if xmms.control.is_main_win(0) == 1: xmms.control.main_win_toggle(0) print xmms.control.is_eq_win(0) if xmms.control.is_eq_win(0) == 1: xmms.control.eq_win_toggle(0) xmms.control.playlist_clear(0) seq = "/home/eomer/tumes.m3u" xmms.control.playlist_add_allow_relative(seq, 0) xmms.control.play(0) Under the interpretor I do access it differently (and I opened xmms myself): import xmms.control xmms.control.playlist_add('/home/eomer/tumes.m3u', 0) I have used both of these functions both ways. Both produce the same result. The playlist_clear function works perfectly. Also I have tried other files that aren't actually m3u lists. All have the same effects. I am running Xmms 1.2.10 (just in case you need to know :D). Oh also if you know a better way to open xmms from the script and allow the script to still run please feel free to comment. Oh, this is just an experiment not life or death (yet :)). Thanks, David -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: <http://mail.python.org/pipermail/python-list/attachments/20040504/00772a8c/attachment.sig> From joconnor at cybermesa.com Tue May 4 07:22:00 2004 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 04 May 2004 11:22:00 GMT Subject: Paging Mitch Chapman and/or Brian Kelly Message-ID: <s1Llc.6393$Hs1.1613@newsread2.news.pas.earthlink.net> Brian, Mitch If you're around, please drop me a line. Thanks Take care, Jay joconnor at cybermesa.com From ronaldoussoren at mac.com Mon May 31 04:51:04 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Mon, 31 May 2004 10:51:04 +0200 Subject: ANN: PyObjC 1.1 Message-ID: <A64E8E60-B2DF-11D8-9C27-0003931CFE24@mac.com> PyObjC 1.1 is now available for download at http://pyobjc.sourceforge.net/ PyObjC is a bridge between Python and Objective-C. It allows full featured Cocoa applications to be written in pure Python. It is also easy to use other frameworks containing Objective-C class libraries from Python and to mix in Objective-C, C and C++ source. Python is a highly dynamic programming language with a shallow learning curve. It combines remarkable power with very clear syntax. The installer package includes a number of Xcode and Project Builder templates for easily creating new Cocoa-Python projects, as well as support for syntax-coloring Python files. PyObjC also supports full introspection of Objective-C classes and direct invocation of Objective-C APIs from the interactive interpreter. PyObjC requires MacOS X 10.2 or later. PyObjC works both with the Apple provided Python installation in MacOS X 10.2 (and later) and with MacPython 2.3. Users of MacPython 2.3 can install PyObjC though the PackageManager application. The major improvement of PyObjC 1.1 is support for Key-Value Observing. It is now possible to write programs that use Cocoa Bindings. There are also numerous new examples. PyObjC is released with an open source license. From has.temp2 at virgin.net Sat May 29 18:36:14 2004 From: has.temp2 at virgin.net (has) Date: 29 May 2004 15:36:14 -0700 Subject: UK Social research job to suit Excel programmer (not necessarily VBA) References: <c9a3ln$t44$1@news8.svr.pol.co.uk> <40B8991F.4010207@engcorp.com> <c9a9k4$ffr$1@news5.svr.pol.co.uk> Message-ID: <69cbbef2.0405291436.1875512@posting.google.com> "Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message news:<c9a9k4$ffr$1 at news5.svr.pol.co.uk>... > "Peter Hansen" <peter at engcorp.com> wrote in message > news:40B8991F.4010207 at engcorp.com... > > Duncan Smith wrote: > > > > > http://www.man.ac.uk/news/vacancies/research.html#581 > > > > Sorry, but what's the connection to Python? > > There is (I am told) a significant amount of work automating Excel. > Unfortunately this isn't clear from the job description (I didn't write it). > I know from experience that this can be achieved admirably using Python (and > Mark Hammond's extensions). If it's any help, the Mac version of Excel can also be scripted via Apple events. The most common language for this is AppleScript [no comment:p], but Apple Event Manager bridges are also available for Perl (see Mac::Glue at <http://search.cpan.org/~cnandor/>) and MacPython (see appscript at <http://freespace.virgin.net/hamish.sanderson/appscript.html>; not quite finished but getting there). From merkosh at hadiko.de Fri May 14 17:37:41 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 14 May 2004 23:37:41 +0200 Subject: running a function in a different scope Message-ID: <c83e76$7vm$1@news2.rz.uni-karlsruhe.de> Hi, I've got a class that receives a function in the constructor and uses the __call__ method to execute the aforementioned function when the instance object is called: class foo(object): def __init__(self, func): self.func = func def __call__(self, *arg, **kwarg): return self.func(*arg, **kwarg) This is ok until I reassign i.e. the builtin function "vars": >>> vars = foo(vars) {'self': <__main__.foo object at 0x401ee78c>, 'kwarg': {}, 'arg': ()} instead of the scope: {'__builtins__': <module '__builtin__' (built-in)>, '__file__': '/home/merkosh/.pythonrc', 'sys': <module 'sys' (built-in)>, '__name__': '__main__', 'foo': <class '__main__.foo'>, '__doc__': None} Now the function "vars" does not bother me that much. I wonder which other side-effects will occur, which functions may not be called from within a foo-object and perhaps how to avoid this, i.e. can the foo-instance detect in which scope it was executed and call the passed function (vars) in that particular scope? Thanks for any hints. Ciao Uwe From wweston at att.net Thu May 6 13:18:58 2004 From: wweston at att.net (wes weston) Date: Thu, 06 May 2004 17:18:58 GMT Subject: Python 2.3 on RedHat 9 In-Reply-To: <mailman.652.1082042355.20120.python-list@python.org> References: <mailman.652.1082042355.20120.python-list@python.org> Message-ID: <6sumc.25762$Ut1.748552@bgtnsc05-news.ops.worldnet.att.net> Stephen Ng wrote: > Hi! > > Has anyone installed Python 2.3 on RedHat 9? Did you install on top of > Python 2.2 or did you install in a separate directory (eg the default)? > > I'm trying to find out in advance if it's hassle free to install as I am > planning to do it. > > Thanks. > > Stephen Ng > > Stephen, Yes and if you put the 2.3 ahead of the system python, things like the "network device control" tool quit working. I just did a pythonx script to run 2.3. wes From nospam at dontreply.com Sat May 1 08:29:33 2004 From: nospam at dontreply.com (Peter) Date: Sat, 01 May 2004 08:29:33 -0400 Subject: Pyrex 0.9.1.1 compile problem Message-ID: <Qd6dneK8yKywBQ7dRVn-gw@comcast.com> Kernel 2.6.5 Slackware 9.1 Python -V: 2.3.1 running python setup.py install yields the following error: peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ python setup.py install Traceback (most recent call last): File "setup.py", line 8, in ? if sys.platform in ("unix", "darwin"): NameError: name 'sys' is not defined peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ What am I missing? Thx From donn at u.washington.edu Wed May 12 14:08:21 2004 From: donn at u.washington.edu (Donn Cave) Date: Wed, 12 May 2004 11:08:21 -0700 Subject: Scope rule pecularities References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <2g8ag2F4re0lU1@uni-berlin.de> <slrnca428q.1i9.apardon@trout.vub.ac.be> <Xns94E78398B6CAAduncanrcpcouk@127.0.0.1> <slrnca4693.1i9.apardon@trout.vub.ac.be> Message-ID: <donn-A934F5.11082112052004@nntp2.u.washington.edu> In article <slrnca4693.1i9.apardon at trout.vub.ac.be>, Antoon Pardon <apardon at forel.vub.ac.be> wrote: > Op 2004-05-12, Duncan Booth schreef <me at privacy.net>: > > Antoon Pardon <apardon at forel.vub.ac.be> wrote in > > news:slrnca428q.1i9.apardon at trout.vub.ac.be: > > > >> IMO lacking an assignment that copies the value > >> of one object into another was a mistake and > >> which creats IMO a lot of difficulties. > >> > >> If I have a function with an object as a paramter. > >> and this object is mutable. Now within this function > >> I find a second object with the value I want the > >> argument to have. Now I can't simply copy the > >> second object over the argument but I have to > >> copy attribute by attribute from the second object > >> into the argument. > > > > Why wouldn't you just return the second value (or a copy of it) as a result > > from the function? That is usually a more flexible choice since it gives > > the caller the option of either replacing the original value or using the > > modified value somewhere different. > > Well because the object could be bound with more than one name. > > > Anyway, if you really need to do this then the mutable object should have > > some sort of updateState method which takes the second object as a > > parameter. That way the original object can have control over which > > attributes get overwritten and which don't. > > And I think it is a pain in the butt to always have to write such an > UpdateState method whenever you want one object to be copied in place > from an other. I really think this is a cases where you will write better programs if you let yourself be guided by what you can do in idiomatic Python. In modern programming, now that we have pretty much adopted the "structured" programming model, one of the main remaining burdens on the programmer is "mutable state". You need to be able to account for possible changes in values, if you want to be able to reason about your program. Python isn't any kind of extreme solution to this problem, it isn't a "pure" functional language, but it does have some helpful constraints and this is one of them - you know a function can't rebind names that you supply as its parameters. The inability to do this is a feature. Donn Cave, donn at u.washington.edu From hoel at gl-group.com Mon May 17 10:51:59 2004 From: hoel at gl-group.com (Berthold =?iso-8859-15?q?H=F6llmann?=) Date: Mon, 17 May 2004 16:51:59 +0200 Subject: Test error with Python 2.3.4c1 References: <m2fza1h6ka.fsf@pchoel.psh> <m27jvdh5k6.fsf@pchoel.psh> <c85sdb$802$1@panix3.panix.com> <m2vfixfnc3.fsf@pchoel.psh> <c866s7$fp0$1@panix2.panix.com> <m2ad082xpb.fsf@pchoel.psh> <mailman.9.1084799551.6949.python-list@python.org> Message-ID: <sen047t8c0.fsf@pc020549.dhcp.germanlloyd.org> Andrew MacIntyre <andymac at bullseye.apana.org.au> writes: > On Sun, 16 May 2004, Berthold H?llmann wrote: > >> > caused some changes to the way sre operates, so it was a non-starter for >> > the 2.3.x series. >> > >> > Anyway, please close your bug with a note about it being fixed in 2.4 >> > CVS. As for the other issue, I don't have enough time/energy to even >> > understand what the issue is. Given that it's about SAX, I suggest you >> > start a new thread and hopefully someone else will pick it up. >> >> OK, I closed the bug, but still would like to see USE_RECURSION_LIMIT >> default reduced to something like 6500 (3000 seems to be OK for >> FreeBSD on sparc64, so I guess this can't be a behavioral change). > > Prior to 2.4, sre is recursive. Recent versions of gcc (in particular) > at higher optimisation levels are generating much larger stack frames than > used to be the case. This is even moreso the case with 64-bit platforms. > > In the particular case of FreeBSD 4.x, in the presence of threads (the > default build choice, using libc_r) there is a hard coded stack size of > 1MB, which leaves this environment especially sensitive to stack frame > size. The alternative threads libraries (libkse/libthr) available on 5.x > are less affected, but I don't know to what extent (& Python's configure > script doesn't know about them that I've heard). > > I've seen reference to the problem on Linux, but I don't know why that > platform is (apparently) short on stack. > > This is a highly platform/compiler dependant issue, which is why the maze > of #ifdef'ery for USE_RECURSION_LIMIT - something that has only happened > since about Python 2.3.1 as I recall. > > The most effective solution with recent gcc versions is to recompile sre.c > with -Os (instead of -O3). It is unfortunately awkward to implement with > autoconf. The non-recursive sre in 2.4 is a complete fix, but is too > extensive/invasive a change for back-porting for a bug-fix release. But the current value for USE_RECURSION_LIMIT is a problem on (some) Linux Platforms. Why is reducing the default value a problem, when setting it to a smaller value on some platforms is not a problem. I thought everything causing segmentation faults from Python is to be avoided. Regards Berthold -- Dipl.-Ing. Berthold H?llmann __ Address: hoel at GL-Group.com G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 32/35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From dai4happy at yahoo.com Sat May 8 06:05:47 2004 From: dai4happy at yahoo.com (angel) Date: Sat, 8 May 2004 18:05:47 +0800 Subject: How python ActiveX to access DHTML document? Message-ID: <c7ibmb$24b2$1@news.f.de.plusline.net> Hi I want to write an ActiveX by using python. And I know how do, but I don't know how python to access DHTML Document.If using cpp, it can be done by following source. /****/ CComPtr<IOleContainer> spContainer; m_spClientSite->GetContainer(&spContainer); CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> spDoc(spContainer); if (spDoc) spDoc->put_bgColor(CComBSTR(_T("pink"))); /****/ Who can tell me how to do the same in python? Thanx ps. I use win32com package. Thanx again angel From has.temp2 at virgin.net Mon May 3 05:12:39 2004 From: has.temp2 at virgin.net (has) Date: 3 May 2004 02:12:39 -0700 Subject: What is good about Prothon? References: <bniq80hiib0gauiltuntk9jvia2getbnj4@4ax.com> <m0ps8092jss5mhpopkbj0a4hg0m0rlppqh@4ax.com> <vDvjc.5555$Qy.2995@fed1read04> <108t2tlo06j8vb9@corp.supernews.com> <hzwjc.6087$Qy.2366@fed1read04> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <ZHXjc.17225$Qy.13377@fed1read04> <69cbbef2.0404291609.72d391db@posting.google.com> <c6sf29$fvhns$1@ID-169208.news.uni-berlin.de> <69cbbef2.0404300115.574d93e7@posting.google.com> <c7452n$hg0p1$1@ID-169208.news.uni-berlin.de> Message-ID: <69cbbef2.0405030112.52da744e@posting.google.com> Greg Ewing <greg at cosc.canterbury.ac.nz> wrote in message news:<c7452n$hg0p1$1 at ID-169208.news.uni-berlin.de>... > has wrote: > > Not at all. I was arguing these issues long before Prothon got its > > copy() method. I'm aware of its recent addition, but it doesn't > > really change anything: the canonical Prothon way to create new > > objects is still b = a(), not b = a.copy(). > > In that case you're not arguing about what the language > provides, but about the preferred style of using what the > language provides. At which point we more or less come full circle, as we're back to the "all approaches are equally valid, so all criticisms are equally worthless" argument, then I point out that this sort of relativist fallacy is the same attitude that makes C++ what it is today, and then I get told that such statements are "ludicrious" (they're not; they're hyperbole) and "Lieberman said I could do it this way so that makes it okay", and then I completely waste another week of my time rehashing the same arguments I gave last time as to why such attitudes doom any such projects they touch to a lifetime of mediocrity as they perversely persist in reinventing every flaw and misfeature that better minds already solved donkeys years ago, and all with no more success than before. So I'm going to stop right there, because I've already said all I usefully can and have more useful things to be doing with my time, and what you do with yours is not any problem of mine, and everyone else on comp.lang.python are feeling their brains dribble out their ears. has From E.A.M.Huijbers at REMOVEstudent.tue.nl Mon May 24 10:42:46 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Mon, 24 May 2004 16:42:46 +0200 Subject: Jabber in Twisted In-Reply-To: <VYedndon_vtpyzPdRVn-tA@powergate.ca> References: <c8lgid$qj5$1@news.tue.nl> <VYedndon_vtpyzPdRVn-tA@powergate.ca> Message-ID: <c8t1g7$nd3$1@news.tue.nl> Peter Hansen wrote: > Rico Huijbers wrote: > >> Does anybody have experience in writing Jabber clients with Twisted? I >> came across a simple sample[0], and tried to build out from it, but >> for some reason it's barely working. >> >> When I run the application in the attached script, the logon goes fine, > > > I think you'll get far more attention from the right people if > you subscribe to the twisted mailing list, and post your > inquiry there. > > As with Zope, and some other large, non-standard packages, the dedicated > Twisted mailing list is where the core folks hang out. Some show up > here from time to time and answer questions, but you're doing yourself > a disservice by limiting the input to this general newsgroup/mailing > list. Yes, I saw that, but since I find it easier to post to and read newsgroups, and I already saw a couple of Twisted-related threads in here, I figured I'd try here first. But I'll take your suggestion and try again on the Twisted mailing list. Thanks for your reply. - Rico From sadplanet at MAPS.chello.be Sat May 15 03:59:58 2004 From: sadplanet at MAPS.chello.be (mr.happy) Date: Sat, 15 May 2004 07:59:58 GMT Subject: Python - open forever ? References: <mailman.511.1084452958.25742.python-list@python.org> Message-ID: <pan.2004.05.15.07.59.39.331631@MAPS.chello.be> On Thu, 13 May 2004 15:55:53 +0300, Romans Krjukovs wrote: > - There is a risk that Python can become closed and unsupported in the > future. > (Remember RedHat ?) RedHat is still open and supported, I don't know where you got the information that is was supposed to be closed and unsupported now. You can get the sources for RHES, they are available on the RH ftp servers. On the support side, they probably have better support now then ever before, though it's a bit more expensive now. > - Who can guarantee that Python will be usable and available to us if > it is > develeped and maintained by the hackers from all over the world > without > any obligations and guarantees ? who will guarantee you that software x from company y will be available to you! company y might go bust or just stop development of software x because there was no profit made with the product. _that_ is one fear you never have to deal with, as OSS programs exists because they are, and in theory never die. don't think it never happens, i have been in the IT world for a while and i've seen these commercial programs come and go, and when they are gone, you can do nothing but quickly upgrade to something else. even if for some reason all development would stop on python, the sources are still available and your company could hire programmers to continue the development as a last resort. > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) see this: http://www.python.org/psf/donations.html and this: http://www.python.org/psf/mission.html greets, -- There is no statute of limitations on stupidity. From greg at cosc.canterbury.ac.nz Thu May 20 21:40:59 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 21 May 2004 13:40:59 +1200 Subject: Unification of Methods and Functions In-Reply-To: <s13oa05mhn1584d2ljvij40ktrorpo432s@4ax.com> References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <2h2g50F87lb9U1@uni-berlin.de> <s13oa05mhn1584d2ljvij40ktrorpo432s@4ax.com> Message-ID: <2h551dF8d2p7U1@uni-berlin.de> Kevin G wrote: > Seems to me there's a semantic problem here: if you can't re-calculate > it, then by definition it's not redundant.] Obviously if it's redundant then in principle you can always recalculate it. But if you don't plan for that, you can end up not having any piece of code in the system you can call to recalculate it. Approaching the problem from the cacheing perspective at least ensures that you do have such a piece of code. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tkpmep at hotmail.com Wed May 19 09:58:38 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 19 May 2004 06:58:38 -0700 Subject: PyDoc errors Message-ID: <b4a8ffb6.0405190558.5d1ed0ad@posting.google.com> I created a program to play blackjack, and documented all the classes and functions. If I import it and then type >>>help(blackjack) I get a clean printout of all the documentation. However, if I start PyDoc and then try to view the documentation in a browser, I get the following error message: problem in c:\Python23\Programs\blackjack.py - EOFError: EOF when reading a line The program runs perfectly, and help(blackjack) gives me exactly what I expect. What should I be looking to fix to make it work in PyDoc's browser interface as well? Out of curiosity, I started PyDoc, clicked on Open Browser, and then randomly clicked on modules, scripts, etc. I consistently get errors when I click on items under scripts, including objgraph, which and mkreal. A typical error message is problem in C:\PYTHON23\Tools\Scripts\objgraph.pyc - SystemExit: 0 Is this a known problem? If so, is there a fix? Thomas Philips From lbates at swamisoft.com Fri May 21 19:11:13 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 21 May 2004 18:11:13 -0500 Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il> Message-ID: <r6-dnZ3iwqgNETPdRVn-uQ@comcast.com> I think it is odd that I have never encounter many of these types of constructs repeatedly in my code. Perhaps you could share a little more of where you see this type of think popping up a lot? I suspect that there is another method for solving the problem that might be faster and easier to read/program. Larry Bates, Syscon, Inc. "Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message news:c8l3s3$27o$1 at news.iucc.ac.il... > Hello, > Many times I find myself asking for a slice of a specific length, and > writing something like l[12345:12345+10]. > This happens both in interactive use and when writing Python programs, > where I have to write an expression twice (or use a temporary variable). > > Wouldn't it be nice if the Python grammar had supported this frequent > use? My idea is that the expression above might be expressed as > l[12345:>10]. > > This change, as far as I can see, is quite small: it affects only the > grammar and byte-compiling, and has no side effects. > > The only change in syntax is that short_slice would be changed from > [lower_bound] ":" [upper_bound] > to > ([lower_bound] ":" [upper_bound]) | ([lower_bound] ":>" [slice_length]) > > Just to show what will happen to the byte code: l[12345:12345+10] is > compiled to: > LOAD_GLOBAL 0 (l) > LOAD_CONST 1 (12345) > LOAD_CONST 1 (12345) > LOAD_CONST 2 (10) > BINARY_ADD > SLICE+3 > > I suggest that l[12345:>10] would be compiled to: > LOAD_GLOBAL 0 (l) > LOAD_CONST 1 (12345) > DUP_TOP > LOAD_CONST 2 (10) > BINARY_ADD > SLICE+3 > > Well, what do you think? I would like to hear your comments. > > Have a good day (or night), > Noam Raphael From pruebauno at latinmail.com Mon May 31 18:26:36 2004 From: pruebauno at latinmail.com (nnes) Date: 31 May 2004 15:26:36 -0700 Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> Message-ID: <d8778a53.0405311426.453dd187@posting.google.com> Arthur <ajsiegel at optonline.com> wrote in message news:<1r9ta017o5n64gman6mkt2ufg4v6m2tv1u at 4ax.com>... > On Fri, 21 May 2004 13:30:23 -0700, Shalabh Chaturvedi > <shalabh at cafepy.com> wrote: > > >I believe it is conceptual homogeneity and not type homogeneity that > >characterises the difference between lists and tuples. > > "conceptual homogeneneity" defined - as far as I see it - by > reference to whether a rational Python programmer would group the > objects together in a list. > > A perfect tautology. > > Which always seems to me to create more confusion, than clarification. > > Art Generaly speaking two objects "ham" and "spam" are of the same (duck) "type" in context "a" to "b" of a program if all the methods of "ham" used between "a" and "b" can be used with "spam" and all methods of "spam" used between "a" and "b" can be used with "ham". Example: ham=' Arizona ' spam=['C','o','l','o','r','a','d','o'] print type(ham) print type(spam) #line a --------- print ham.index('o') print spam.count('o') #Does work #print spam.index('o') #print ham.count('o') #line b --------- print ham.strip() print spam.pop(0) #Does not work #print spam.strip() #print ham.pop(0) #line c ------ #EOF ham and spam are of the same "type" in context a-b. ham and spam are of different "type" in context b-c. A list should be used to store ham and spam in context a-b. A tuple should be used to store ham and spam in context b-c. Of course "real type" of ham is 'str' and of spam is 'list' but that is irrelevant when considering "duck typing". "duck typing" is achieved in java by using interfaces, including the relevant methods in them and casting the objects at the appropiate context to that interface. So using java lingo we might translate the previous to: Lists are used if an usefull interface with common methods for the objects can be created. Tuples are used if no common interface can be created for the objects stored. NN Disclaimer: The previous is my personal opinion and may change in the future! PS: Just in case you feel temped to ask me the forbidden question: Which is better, duck typing or explicit typing? Answer: I don't know! From jzgoda at gazeta.usun.pl Sat May 22 16:06:45 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 22 May 2004 20:06:45 +0000 (UTC) Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> Message-ID: <c8obsk$i6k$1@atlantis.news.tpi.pl> Manlio Perillo <NOmanlio_perilloSPAM at libero.it> pisze: > I'm using the Cookie module (on the client side). > I have found a problem trying to parse the cookie: > > "Set-Cookie: value=thevalue; path=/; > expires=Fri, 21-May-2004 10:40:51 GMT" You must use date in UTC format. -- Jarek Zgoda http://jpa.berlios.de/ From cmedcoff at hotmail.com Sat May 29 08:52:27 2004 From: cmedcoff at hotmail.com (Chuck) Date: Sat, 29 May 2004 08:52:27 -0400 Subject: Python with TestDirector References: <mailman.375.1085682168.6949.python-list@python.org> Message-ID: <dJSdnX54AfIQGiXdRVn-hg@wideopenwest.com> MessageHi, I'm not using Python with TestDirector but I know that our QA group uses it. I'm a software architect and I am very interested in increasing the use of automated testing within my company. We are primarily a Java shop but I write a bit of Python for this and that especially testing. I've used PyUnit, JUnit, NUnit etc. and am trying to get others to use these tools. I'd be interested in learning about how Python can be used in conjunction with TestDirector. What's the relationship - Is TestDirector written in Python? "Taylor, Martin" <cmtaylor at ti.com> wrote in message news:mailman.375.1085682168.6949.python-list at python.org... Limor Hevroni asked on Mon Apr 19 06:49:06 EDT 2004 if anyone was using Python for testing with TestDirector. I am doing this extensively and would welcome discussions with other people who are either doing it or are interested in doing it. Regards, C. Martin Taylor Sr. Test Automation Specialist Texas Instruments, Inc. Educational and Productivity Solutions 7800 Banner Dr. MS 3946 Dallas, TX 75251 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040529/66eff452/attachment.html> From brian at sweetapp.com Wed May 5 07:50:08 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 05 May 2004 13:50:08 +0200 Subject: VIM and tab to space migration In-Reply-To: <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> References: <c5bg1k$25vq$1@news.wplus.net> <c5c138$i91$1@news.service.uci.edu> <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> Message-ID: <4098D4F0.4010605@sweetapp.com> Right now I'm working in an environment where tabs were mandated as the indentation style for Python. I've managed to persuade everyone to switch to 4 space indentation. The problem is that we now have a migration problem. Most of our develoeprs are using VIM which, AFAIK, is not intelligent enough to detect the current indentation style of a file. Modifying all of our source files at once to use spaces and then getting everyone to change their .vimrc is a posibility but not desirable because everyone would have to check in their work (whatever it's state) at the time of migration. Does anyone have any suggestions? Ideally, there would be some way to tell VIM to use the file's exsiting indentation style. That way I could slowly switch to spaces over time. Cheers, Brian From mark at prothon.org Sun May 23 17:37:29 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 23 May 2004 14:37:29 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> <30260531.0405231227.24089c9f@posting.google.com> Message-ID: <uQ8sc.12043$bF3.2078@fed1read01> "simo" <simoninusa2001 at yahoo.co.uk> wrote > > I dont understand why everybody seems to want a machinecode compiler. It > > wont make a high-level, dynamically typed language run any faster. > > I think distribution is the issue really, not speed. > > You can have a more secure distributable .exe file and not have to > bundle the huge Python23.DLL. I can do in 8Kb of compiled C++ what I > can only do in about 2Mb of Python (of course it'll take me twice as > long to figure out how to program it in C++, which is the usual > argument for Python). I think that 2 MB could be brought down to something reasonable like 0.1 MB with a proper "compiler". That is a nice goal to work towards in Prothon. BTW: The 0.008 MB you are talking about either does nothing useful or is just calling windows high-level routines. I assume maybe you are exaggerating? From NAIGIMSESRIMAIL at gims.com Sun May 16 04:32:47 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sun, 16 May 2004 10:32:47 +0200 Subject: ALERT - GroupShield ticket number OB21_1084696358_ESRIMAIL_3 was generated Message-ID: <B06B8FEF47ACD7119E720040F42845910322A311@ESRIMAIL> Action Taken: The message was blocked because of its subject. To: python-list at python.org <python-list at python.org> From: Richard Townsend <nospam at here.com> Sent: 1501791232,29637408 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1829 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040516/265aff36/attachment.bin> From deetsNOSPAM at web.de Sat May 1 09:19:27 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 01 May 2004 15:19:27 +0200 Subject: Embedding python into PyQt References: <Pine.LNX.4.44.0404301222520.24975-100000@e5-05.ee.ualberta.ca> Message-ID: <c707us$q4m$03$2@news.t-online.com> > What I am trying to do is to embed the python interactive interpreter > inside a qt TextEdit. > > I could write an event loop myself, but I was wandering if there exists a > solution somewhere, or the best way to do it myself. > I'm quite sure this has been discussed on the pykde mailing list a while ago - search the archines. A program that actually does do that is eric3. -- Regards, Diez B. Roggisch From andrew-pythonlist at puzzling.org Thu May 13 04:20:38 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 13 May 2004 18:20:38 +1000 Subject: Scope rule pecularities In-Reply-To: <slrnca69ju.1i9.apardon@trout.vub.ac.be> References: <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <2g8ag2F4re0lU1@uni-berlin.de> <slrnca428q.1i9.apardon@trout.vub.ac.be> <Xns94E78398B6CAAduncanrcpcouk@127.0.0.1> <slrnca4693.1i9.apardon@trout.vub.ac.be> <donn-A934F5.11082112052004@nntp2.u.washington.edu> <slrnca69ju.1i9.apardon@trout.vub.ac.be> Message-ID: <20040513082038.GE20388@frobozz> On Thu, May 13, 2004 at 07:40:45AM +0000, Antoon Pardon wrote: > > But I don't ask for rebinding, I ask for easy in place copying. > > Lets name a new operator "@=" Now given variables A and C > of the same class I would like to see the following: > > >>> B = A > >>> A @= C > >>> A is B > True > >>> A is C > False > >>> A == C > True It's already easy: from copy import copy b = a a = copy(c) [I'm using lowercase variables for instances, which is the usual convention... uppercase suggests that it's a class name (or maybe a constant) to me.] No new syntax necessary. > And maybe if D is of an other class > > >>> D @= C > TypError Assignments in Python don't care about what the name is currently bound to, if anything. They just (re)bind the name to an object -- so having an assignment to D depend on the type of D's old value would be inconsistent with the rest of Python. Many classes support a convention where you can pass a single argument to their constructor to construct a copy, e.g.: l2 = list(l1) So your example could become: d = d.__class__(c) Although in practice it's hard to think of an example where I'd want to dynamically care about the type of a object I'm about to discard like that... I certainly can't think of a time when I've wanted to do that. -Andrew. From jcb at iteris.com Tue May 4 18:26:51 2004 From: jcb at iteris.com (MetalOne) Date: 4 May 2004 15:26:51 -0700 Subject: Experience with vb2py? References: <_Azlc.44378$r37.39639@newssvr29.news.prodigy.com> Message-ID: <92c59a2c.0405041426.7183be8e@posting.google.com> I tried to use vb2py about a year ago for a project of about 15,000 lines. vb2py was not ready for that kind of a task. I encountered problem after problem. The author of the package was extremely helpful and glad to here about the problems. He seemed willing to almost immediately fix any problems that I had. However, I was on a very tight deadline and after a few days of experimenting with vb2py it was clear that it was not going to work for me. On another note, the VB code that I was working with was unbelievably bad. I found that I could reduce the amount of code from between 5 lines to 1 to about 30 lines to 1 depending upon the code sections. Frequently this entailed completely different solutions to the problems. The author of the VB code had absolutely no idea how to factor out any kind of redundancy in the code. The vb2py translations did not produce particularly optimized Python code for the VB code. It also became clear that if I wanted the project code in Python that rewriting the code by hand would be vastly better than automated translations. So much so that I could not recommend the automatic translation even if it worked. In the end, the project was cancelled. Bad VB code was deemed better than spending money to fix the code. From idbaxter at semdesigns.com Sat May 8 15:25:45 2004 From: idbaxter at semdesigns.com (Ira Baxter) Date: Sat, 8 May 2004 14:25:45 -0500 Subject: String/source code analysis tools References: <j0Khc.25133$Q%5.6444@newssvr27.news.prodigy.com> Message-ID: <409d326e$1@giga.realtime.net> "Moosebumps" <moosebumps at moosebumps.com> wrote in message news:j0Khc.25133$Q%5.6444 at newssvr27.news.prodigy.com... > I have a whole bunch of script files in a custom scripting "language" that > were basically copied and pasted all over the place -- a huge mess, > basically. > > I want to clean this up using Python -- and I'm wondering if there is any > sort of algorithm for detecting copied and pasted code with slight > modifications. > Not in Python, but could be used to do this. We offer a clone detection tool that works on very large source code basis, and detects cloned clone with "slight modifications". You'd have to provide a grammar for your 'scripting language'. See http://www.semanticdesigns.com/Products/Clone/index.html. -- Ira D. Baxter, Ph.D., CTO 512-250-1018 Semantic Designs, Inc. www.semdesigns.com From amireallyfat at yahoo.com.au Sat May 29 05:49:47 2004 From: amireallyfat at yahoo.com.au (whydoineedaname) Date: Sat, 29 May 2004 19:49:47 +1000 Subject: python crash Message-ID: <40b87620_1@news.iprimus.com.au> hi for like the last week the python shell keeps crashing and wont load when i try to open it and also when i tried to run some simple aps it crashes does anyone know how to fix this??? thanks nathan From compta at agorus.net Tue May 25 04:29:21 2004 From: compta at agorus.net (Frederic G. MARAND) Date: Tue, 25 May 2004 10:29:21 +0200 Subject: Documentation/Info on this sign References: <c8iims$24i$1@solaris.cc.vt.edu><1O-dnXHH1_PKTjHd4p2dnA@powergate.ca><40ACED36.5030706@hotmail.com><c8lhq8$g7m$07$1@news.t-online.com><VYedndUn_vtmyjPdRVn-tA@powergate.ca><c8mr7d$ueh$06$1@news.t-online.com> <mailman.181.1085237863.6949.python-list@python.org> Message-ID: <40b303dc$0$315$7a628cd7@news.club-internet.fr> eTrust antivirus can scan twice because it uses two different engines. Maybe this is what you are remembering ? "Terry Reedy" <tjreedy at udel.edu> a ?crit dans le message de news:mailman.181.1085237863.6949.python-list at python.org... > > "Peter Otten" <__peter__ at web.de> wrote in message > news:c8mr7d$ueh$06$1 at news.t-online.com... > > Upon reflection it seems unlikely that an antivirus tool would resolve > > shortcuts, but the basic idea that twice as many files being seen is an > > indication of files being seen twice _somehow_ still seems compelling. > > I have a memory (about a year ago) of (McAfee?) AV scanning every file > twice. Not sure why or settings used, but I think it applied two separate > algorithms in separate passes. Don't remember if doubled number. More > concerned by nasty infection it found;-) > > tjr > > > > From miki.tebeka at zoran.com Thu May 13 03:07:42 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 13 May 2004 09:07:42 +0200 Subject: Shipping embedded Python project In-Reply-To: <mailman.421.1084269213.25742.python-list@python.org> References: <c7nvde$npd$1@news2.netvision.net.il> <mailman.397.1084202553.25742.python-list@python.org> <40A076ED.3000107@zoran.com> <mailman.421.1084269213.25742.python-list@python.org> Message-ID: <40A31EBE.6060407@zoran.com> Hello Thomas, > If this works for you, it would be great if you write up a small recipe > into the py2exe wiki. http://starship.python.net/crew/theller/moin.cgi/ShippingEmbedded First time doing Wiki stuff. Fun. Miki From SeeBelow at SeeBelow.Nut Sat May 22 01:36:13 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Sat, 22 May 2004 05:36:13 GMT Subject: ANN: Graphical Neural Net Demonstrator Message-ID: <40AEE6E5.A681768C@shaw.ca> Here are the SourceForge Release Notes: Release Name: VizANN-1.0 This is a program to graphically demonstrate the operational details of a certain type of ANN (Artificial Neural Network). The program is 100% GUI, meaning that there is no line-by-line input nor output. The program is written in Python. (a free download from http://www.python.org) The .zip file contains only these three files: VizANN.py - The program source code VizANN.txt - documentation xor.gif - an image file which VizANN.py will display Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From qual at tiscali.de Sun May 2 08:43:08 2004 From: qual at tiscali.de (Uwe Hoffmann) Date: Sun, 02 May 2004 14:43:08 +0200 Subject: Passing data between threads In-Reply-To: <4094B2E3.E802F8D2@mega-nerd.com> References: <4094B2E3.E802F8D2@mega-nerd.com> Message-ID: <c72q5t$1pri$1@ulysses.news.tiscali.de> Erik de Castro Lopo wrote: > However, I'd like to pass some data back to the parent thread before alling > thread.exit () but I can't figure out how. take a look at the Queue class (e.g. calling thread provides queue as parameter): http://docs.python.org/lib/module-Queue.html greetings uwe From donn at drizzle.com Fri May 21 23:31:00 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 22 May 2004 03:31:00 -0000 Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> Message-ID: <1085196659.537172@yasure> Quoth Arthur <ajsiegel at optonline.com>: ... | Can't it be said, in helping to distinguish a Python list from the | standard collections in, say, Java and C++ - that among its most | important attributes is the ease with which one can work with a list | as a collection of objects of *heterogenous* type. "Type" here being | used in the sense that programmers generally use the word. | | In exploring Python early on, I found this to be a core feature, and a | real attraction. | | Am I missing something again? I think so, but if it's that you're actually missing the dozen or so posts on this topic today, perhaps you can find them on Google. Otherwise, don't know what to say. Donn From j_mckitrick at bigfoot.com Tue May 4 22:59:43 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 May 2004 19:59:43 -0700 Subject: Different values for property vs attribute??? References: <ec6dce8b.0405041123.19c4c6c3@posting.google.com> <c78sn7$11n72$1@ID-76829.news.uni-berlin.de> Message-ID: <ec6dce8b.0405041859.7ba02146@posting.google.com> I forgot to mention, I have another class like this: def getauditcheckpass(self): return self.state[AUDITCHK] == PASS # properties auditcheckpass = property(getauditcheckpass) and it seemed to work ok. From peter at engcorp.com Fri May 21 09:20:10 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 09:20:10 -0400 Subject: Python compilers? In-Reply-To: <8089854e.0405210201.2a9b6de@posting.google.com> References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <30260531.0405180848.42e2919d@posting.google.com> <8089854e.0405210201.2a9b6de@posting.google.com> Message-ID: <YJmdnddDGMqWnzPdRVn-gw@powergate.ca> Fuzzyman wrote: > Funnily though, most people call Java a compiled language, but it only > compiles to Java bytecode which runs on the virtual machine. Python > precompiles to python bytecode which runs on the python virtual > machine. So arguably it is *as* compiled as Java..... Actually, there are compilers that produce native machine code from Java for several CPUs available, and they are used at least in the embedded world. -Peter From bhoel at web.de Sat May 15 16:27:08 2004 From: bhoel at web.de (Berthold Höllmann) Date: Sat, 15 May 2004 22:27:08 +0200 Subject: Test error with Python 2.3.4c1 References: <m2fza1h6ka.fsf@pchoel.psh> <c85p2l$4df$1@panix3.panix.com> <m27jvdh5k6.fsf@pchoel.psh> <c85sdb$802$1@panix3.panix.com> Message-ID: <m2vfixfnc3.fsf@pchoel.psh> aahz at pythoncraft.com (Aahz) writes: > In article <m27jvdh5k6.fsf at pchoel.psh>, Berthold H?llmann <bhoel at web.de> wrote: >>aahz at pythoncraft.com (Aahz) writes: >>> In article <m2fza1h6ka.fsf at pchoel.psh>, Berthold H=F6llmann <bhoel at web.de= >>> wrote: >>>> ...> > In that case, you should check against the CVS version of Python; I > believe there've been some changes that affect this kind of thing. If > that fixes your problem, please close the bug report. OK, I just checked the latest CVS and test_re succeeds. But should't this fixed for 2.3.4 as well? Another problem not there in the CVS version is an error in test_sax, that fails for me on 2.3.4c1 with >echo test_sax > tests >make test TESTOPTS="-l -ftests -v" case $MAKEFLAGS in \ *-s*) LD_LIBRARY_PATH=/home/devel/compile/Python-2.3.4c1:/usr/local/pgsql/lib:/usr/teTeX/lib CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) LD_LIBRARY_PATH=/home/devel/compile/Python-2.3.4c1:/usr/local/pgsql/lib:/usr/teTeX/lib CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac running build running build_ext running build_scripts find ./Lib -name '*.py[co]' -print | xargs rm -f LD_LIBRARY_PATH=/home/devel/compile/Python-2.3.4c1:/usr/local/pgsql/lib:/usr/teTeX/lib ./python -E -tt ./Lib/test/regrtest.py -l -ftests -v test_sax Failed test_attrs_empty Failed test_attrs_wattr Failed test_double_quoteattr Failed test_escape_all Failed test_escape_basic Failed test_escape_extra Failed test_expat_attrs_empty Failed test_expat_attrs_wattr Failed test_expat_dtdhandler Failed test_expat_entityresolver Failed test_expat_file Failed test_expat_incomplete Failed test_expat_incremental Failed test_expat_incremental_reset Failed test_expat_inpsource_filename Failed test_expat_inpsource_location Failed test_expat_inpsource_stream Failed test_expat_inpsource_sysid Failed test_expat_locator_noinfo Failed test_expat_locator_withinfo Failed test_expat_nsattrs_empty Failed test_expat_nsattrs_wattr Failed test_filter_basic Failed test_make_parser Failed test_make_parser2 Failed test_nsattrs_empty Failed test_nsattrs_wattr Failed test_quoteattr_basic test test_sax crashed -- exceptions.TypeError: int argument required Traceback (most recent call last): File "./Lib/test/regrtest.py", line 394, in runtest the_package = __import__(abstest, globals(), locals(), []) File "/home/devel/compile/Python-2.3.4c1/Lib/test/test_sax.py", line 689, in ? confirm(value(), name) File "/home/devel/compile/Python-2.3.4c1/Lib/test/test_sax.py", line 502, in test_sax_parse_exception_str DummyLocator(None, 1))) File "/usr/local/lib/python2.3/site-packages/_xmlplus/sax/_exceptions.py", line 94, in __str__ return "%s:%d:%d: %s" % (sysid, self.getLineNumber(), TypeError: int argument required 1 test failed: test_sax make: [test] Error 1 (ignored) ... self.getLineNumber() is None if I check using pdb, but what disconcerts me is the File "/usr/local/lib/python2.3/site-packages/_xmlplus/sax/_exceptions.py", line 94, in __str__ line. Why is sax taken from the installed version instead of the 2.3.4c1 version. Regards Berthold -- bhoel at web.de / http://starship.python.net/crew/bhoel/ From gduzan at bbn.com Wed May 5 12:43:32 2004 From: gduzan at bbn.com (Gary D. Duzan) Date: Wed, 05 May 2004 16:43:32 GMT Subject: Zero-fill shift References: <mailman.241.1083693910.25742.python-list@python.org> <ad052e5c.0405041357.cd2650a@posting.google.com> <mailman.273.1083771861.25742.python-list@python.org> Message-ID: <UQ8mc.5619$8S1.3817@newsread2.news.atl.earthlink.net> In article <mailman.273.1083771861.25742.python-list at python.org>, Daniel Orner <cs993442 at cs.yorku.ca> wrote: > > > Great, this works. 8-) Unfortunately, I've run into another problem. In >the Java algorithm, two integers are added. This often results in an >overflow and a negative number, which is the desired result. However, I >can't seem to duplicate that in Python, as adding two integers that are >too large just results in a long (and using the int() method doesn't >work). I've tried various solutions, but haven't come up with something >that duplicates this behavior exactly. You could try scattering "(foo) % 2**32" around wherever there could be an overflow. Gary Duzan BBN Technologies From peter.maas at mplusr.de Thu May 13 14:24:00 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 13 May 2004 20:24:00 +0200 Subject: problem running wxPython demo.py In-Reply-To: <mailman.486.1084393832.25742.python-list@python.org> References: <mailman.486.1084393832.25742.python-list@python.org> Message-ID: <c80eh3$oh4$1@swifty.westend.com> Hornberger, Chris wrote: > And that, my friends, is why *nix is a long way from displacing > Windows on the desktop. [...] You forgot to add that Ken should replace libwx_gtk-2.4.so.0 by a more recent version. Concerning your sermon :) I'd like to add that these dependency problems are not really an OS matter but a consequence of the freedom that *ix users enjoy. There's no big brother telling (and forcing) them where to go today. But to ease the burden of freedom *ix should adopt some Windows features, notably the role of interfaces, registry and installation. I'd like to see in *ix systems: - interfaces that streamline communication between processes and objects and free users and programmers from *having to* look into source code. - a registry recording the state of the system and a well defined registry interface used by system and applications. - well defined procedures to modify the state of the system (installation, deletion and configuration) which respect dependencies and don't violate consistency. I would already be happy if this could be achieved for Linux if not for all open source unixes. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From della at toglimi.linux.it Thu May 13 15:14:24 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 13 May 2004 19:14:24 GMT Subject: Generators: section 9.10 of the python tutorial In-Reply-To: <mailman.527.1084471592.25742.python-list@python.org> References: <mailman.527.1084471592.25742.python-list@python.org> Message-ID: <kOPoc.52106$Qc.2107968@twister1.libero.it> David Stockwell wrote: > What does this error mean? Does it mean we can't use yield in our > code? Is yield a form of a 'return' ?? > > class9.py:71: Warning: 'yield' will become a reserved keyword in the future > File "class9.py", line 71 > yield data[index] > ^ > SyntaxError: invalid syntax Yes, you can use yield. It's different from "return", but I guess I couldn't explain it better then the tutorial. :-) You are probably using python2.2. If you want to create generators, you need this line at the start of your python program: from __future__ import generators From BruceWhoHKL at gawab.com Tue May 18 03:31:46 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Tue, 18 May 2004 15:31:46 +0800 Subject: how to keep one instance??? Message-ID: <mailman.113.1572213886.32708.python-list@python.org> Hi, can anyone tell me how to keep only one instance in memory? I write a python script,an editor, so if user click the .txt files, it will run. But if user click the same .txt file again , user will get another instance. So, how to prevent the other instance from running? and how could the second instance pass some information to the first one? Any helps are appreciated. ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-18 From dmq at gain.com Tue May 25 06:45:11 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 03:45:11 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> <slrncb5s7m.o6k.apardon@trout.vub.ac.be> Message-ID: <tp86b0lmerjkj0v6iibu87918naaskirru@4ax.com> On 25 May 2004 07:08:37 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote: >Op 2004-05-22, David MacQuigg schreef <dmq at gain.com>: >> If you are saying we can totally ignore the different method forms, I >> think you are wrong. Bound and unbound methods, for example, will be >> needed in almost any sizable program. The need for static methods >> will arise when the student first writes a method that needs to work >> without a current instance. > >He doesn't need a method for that. He can just write a function. > >Why do you want to write a method in circumstances that call for >a function? See my reply to Greg Ewing on Mon, 24 May 2004 16:17:59 -0700 From Scott.Daniels at Acm.Org Tue May 25 11:51:02 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 25 May 2004 08:51:02 -0700 Subject: Named integers and enums In-Reply-To: <HBF.20040524y0um@bombur.uio.no> References: <HBF.20040523gqks@bombur.uio.no> <mailman.202.1085350648.6949.python-list@python.org> <HBF.20040524y0um@bombur.uio.no> Message-ID: <40b37015$1@nntp0.pdx.net> Hallvard B Furuseth wrote: > I wonder: isinstance() says that even classic class instances are 'object' > instances, even though they do not seem to be (since __slots__ does not > work): > >>> class o: __slots__ = () > ... > >>> isinstance(o(), object) > 1 > >>> o().foo = True > >>> Actually __slots__ works, you just have a funny idea of what __slots__ is _for_. __slots__ is a _storage_optimization_. Try this: class Surprise(object): __slots__ = ('one', '__dict__', 'two') x = Surprise() x.one = 1 x.two = 2 x.three = 3 x.__dict__ -- -Scott David Daniels Scott.Daniels at Acm.Org From Mike at DeleteThis.Geary.com Sun May 23 19:47:05 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 23 May 2004 16:47:05 -0700 Subject: Reading a file, sans whitespace References: <8a0bb987.0405221102.dc679ff@posting.google.com> <5sl4o1-crf.ln1@eskimo.tundraware.com> <10avdpe73rnj20d@corp.supernews.com> <8a0bb987.0405222327.78ef180e@posting.google.com> Message-ID: <10b2dvrfqhmbm5a@corp.supernews.com> Uri wrote: > Thanks guys! Tim's idea seems like the easiest for a newbie > to implement, but I'll play around with Mike's pre-compiling > thing, too. I don't really understand what the compile part > does, could you expound upon that? It's just a way to make a regular expression more efficient when you use it repeatedly. When you use a regular expression, Python does two things: First, it compiles the regular expression into a special customized function that implements the string matching that the regular expression specifies. Then, it runs that function on the string you're using. If you're going to use the regular expression repeatedly, you can compile it every time, or compile it once and use the precompiled version after that. For example, these do exactly the same thing: import re for line in file( 'inputFile' ).readlines(): print re.split( '\s+', line.strip() ) import re reWhitespace = re.compile( '\s+' ) for line in file( 'inputFile' ).readlines(): print reWhitespace.split( line.strip() ) But for a large file, the second version will be faster because the regular expression is compiled only once instead of every time through the loop. It may not make much difference for a simple regular expression like this (and of course string.split is even simpler and probably faster), but for a complicated regular expression it will make more of a difference in performance. -Mike From rgacote at AppropriateSolutions.com Thu May 27 12:28:23 2004 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Thu, 27 May 2004 12:28:23 -0400 Subject: How to I print without newline ? In-Reply-To: <40B603E9.1070003@anonym.hu> References: <40B603E9.1070003@anonym.hu> Message-ID: <a06020427bcdbc750de2d@[192.168.24.239]> At 5:06 PM +0200 5/27/04, fowlertrainer at anonym.hu wrote: >Hi ! > >I want to print, but without newline. Hi FT: Putting a comma at the end of each print statement suppresses the newline. print "hello", print "world" Result: helloworld --Ray -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From curzio.basso at unibas.ch Mon May 10 11:25:17 2004 From: curzio.basso at unibas.ch (Curzio Basso) Date: Mon, 10 May 2004 17:25:17 +0200 Subject: [numarray] mean vector of 2d matrix Message-ID: <409f9edd$1@maser.urz.unibas.ch> Hi all, I was wondering what is the best way to compute the mean vector of a matrix. Currently I'm doing this: >>> data.shape (117027, 8) >>> mean = (numarray.add.reduce(data, axis=1))/(data.shape[1]) but maybe there is a faster way? cheers From BruceWhoHKL at gawab.com Thu May 20 21:51:21 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Fri, 21 May 2004 09:51:21 +0800 Subject: how to keep one instance??? Message-ID: <mailman.114.1572213890.32708.python-list@python.org> I'm using wxWidget to build an editor, so I need a cross-platform solution (at least it should work on windows & Linux). Yes,it does work ,if you use a file to lock. But I want the app behave like this : user click a .txt file, the the app runs and open the file, and later,if user click the same .txt file again, the app can detect the first app instance, and destruct, and popup the first instance to show the same .txt file. For example,you can not open the same .doc file in two MS Word windows. So, how can we get it ? Thanks. ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-21 From ajsiegel at optonline.com Sun May 23 19:30:37 2004 From: ajsiegel at optonline.com (Arthur) Date: Sun, 23 May 2004 23:30:37 GMT Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> Message-ID: <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> On Sun, 23 May 2004 16:13:14 -0000, "Donn Cave" <donn at drizzle.com> wrote: >I don't know what you mean by `outside the "tuple" sense of the word", >but in a way I think that may be nearly the problem. Of course if you >consider these objects on their own, the contents of the tuple but >isolated from that context, they're as homogeneous as you could want, >in fact they would be the very same object. > >But (I hope) no one articulating this point of view says "homogeneous >data", or "homogeneous contents", etc. http://mail.python.org/pipermail/python-dev/2003-March/033964.html Qutoeth Guido: "Tuples are for heterogeneous data, list are for homogeneous data." I have been trying to stict meticulously to his terminology, because my understanding is that is why it is being used. Lists are for homogenous data, with homogenous data defined as data that under some cricumstance might be sensibly used in a list. I routinely use lists to hold instances of different classes. The classes in the lists are fully homogenous. I wrote them all ;) Art From dmq at gain.com Mon May 24 17:17:36 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 14:17:36 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><slrnca6d58.1i9.apardon@trout.vub.ac.be><mailman.516.1084460227.25742.python-list@python.org><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><mailman.186.1085249459.6949.python-list@python.org><66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com><mailman.188.1085259396.6949.python-list@python.org> <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> <mailman.207.1085369037.6949.python-list@python.org> Message-ID: <m8e4b0phom9pj7uobol8h6cuhq287kjhdj@4ax.com> On Sun, 23 May 2004 21:23:43 -0600, "Dave Brueck" <dave at pythonapocrypha.com> wrote: >David MacQuigg wrote: >> >> I can't comment on the usage statistics you cite, but it seems to me >> >> that unbound methods are more important than these statistics would >> >> imply. >> > >> >All I'm saying is that for most programs, the bound method form is way, way, >> >way more commonly used than is the unbound calling form. >> >> I would agree if you cut out two of the "ways" in this sentence. :>) > >Well, for kicks I looked at the standard Python library, since I figured it >would have the greatest concentration of unbound method use (my reasoning was >that since it was a library more than a consumer of a library, you'd have lots >of class hierarchies and therefore more occurences of unbound method calls to >super classes. Even in this situation it appears that unbound method calls are >less than 2% of all method calls. The real point is simply that unbound method >calls are pretty rare. I appreciate your taking the time to actually research this question. The 2% number for unbound functions doesn't surprise me. It would be interesting if we could get similar statistics on static methods, but I suspect the numbers would not be meaningful, given that the staticmethod syntax is relatively new, and there is a long tradition in Python of using various alternatives to static methods. New users tend to copy traditions, which is OK, except that learning those traditions is time-consuming. To me, the real question is how often will my kind of users (no prior experience with Python traditions or OOP, just writing what "comes natural") - how often will they need a static method? That depends on the size and complexity of the programs they are working with. My CDP program will be fairly large, and I am using static methods without hesitation. I would guess half the programs they will encounter would have a static method here and there. >> Still this is like saying names that start with the letter 'q' are way >> less common than all other names, so it is OK if we have a special >> form for functions with such names. > >Not at all - that's a flawed analogy because variable names can be pretty >arbitrary and interchangable. The different types of function calls, method >invocations, whatever, are neither arbitrary nor interchangable. Here is a better analogy than my "no-q" functions. I will use the term "global method" to mean any method containing a global variable. We now have "normal methods", "static methods", "global methods", and a few others. There is no difference in the calling sequence or the header line between a global method and a normal method. Yet we don't seem to have any need for a statement like myMethod = globalmethod(myMethod) >> I've never stated or implied that unbound methods are as common as >> bound methods. Nor would I say that confusion abounds. The different >> calling sequences are just an unnecessary complexity that trips up >> some new users, especially those that don't have experience in some >> other OOP language. > >I'm beginning to understand the real root of the disagreement - you see no >value in the differences and therefore see the existence of the differences as >a flaw. But that's just the problem: these are not merely syntactic >differences, but they are semantic - they are different in purpose and in use, >so your suggestion to get rid of them seems very unappealing: from my >perspective you are removing something useful from the language to solve a >"problem" that I've yet to encounter, or seen anyone else encounter (including >new users of the language). > >> ><sigh> I know what static methods are _for_, but I don't see what is >> >necessarily complex about them, nor how your proposed unification would >help - >> >in fact, ISTM that it would make it much more confusing because both the >> >implementor and caller of the code would never be quite sure if the method >was >> >a static one or not, and that's something that needs to be known by both >> >parties. >> >> I think you have not understood the proposal. It is *not* necessary >> in the new syntax to know the difference between a static and >> non-static method. There *is* no difference. A "static method" (a >> function without instance variables) simply ignores __self__. > >And this is why the proposal seems so lousy: the difference between a static >and a non-static method is _not_ just a syntactic difference, their existance >is not _caused by_ the syntax. The syntax merely reflects that they are >different things to begin with. They are different tools, different features - >you use them for different things, so making them appear identical to the >maintainer of the code and the caller of the code seems like a really bad >idea - a maintenance nightmare. If you remove any syntactic difference, then >that information is lost from the code itself. But since that info is useful, >people will instead track that info in comments or something - yuck. > >> The differences are an artifact of the syntax, not any fundamental >> difference in purpose. Normal methods have a special first argument. >> Static methods do not. That's all there is to it. > >No, no, no - they are different tools, plain and simple. The difference just >isn't skin deep - changing the syntax won't make them go away, it'll instead >make the language more ambiguous. Without meaning to be offensive, I must ask: >how much have you actually used any of these features you're interesting in >consolidating? (static method, unbound methods, bound methods, etc.) I'm new to Python and object-oriented programming. I make no claim of language expertise or vast programming experience. I'm simply offering a perspective on Python from a technical professional (circuit design engineer) who intends to use it as the basis for a new design platform, and intends to recommend it to students and other technical professionsls who could benefit greatly, but don't have time to learn the language as well as they should. >> If there is were some fundamental purpose to static methods, there >> would be something they can do that can't be done with the proposed >> simpler syntax? > >That's just my point: after consolidating the syntax, static methods will still >exist, but there will be no way of knowing which ones are static and which ones >aren't _without reading every line of the code_ - there will be no syntactic >way to express the idea. Egads! > >> I may be wrong, but it looks to me like there *are* no benefits of the >> current binding syntax over the proposed syntax. > >Yes, I understand that it looks that way to you, but why is it that so many >people who have used the language for a long time disagree with you? Is it >because everyone else has blinders on? Could it be _possible_ that these >features have value and/or that the solution you propose is worse than what >currently exists? Saying everyone has blinders is too harsh. It's more like the particular group of users in this discussion are more advanced than the users I am concerned about, and the lack of unity in function/method syntax is a minor issue they have "sailed past" without even thinking. I have a similar reaction to problems that bother less technical users, like the need for a special operator to indicate "floor division" or the problems with storing decimal fractions in a binary floating-point number. These all seem pretty obvious to me, yet I appreciate that Python makes an effort to accomodate these "naive" users. >Again, how much did you use the language before coming to the >conclusion that you have? see above >> What are the benefits of the current design? > >I guess my real gripe with the proposal is that it takes what is currently >clear and makes sense and combines it in such a way to make it ambiguous to >everyone involved with the code. The features you propose consolidating really >are different in real programs, and making them all look the same just for the >heck of it doesn't seem to make much sense. > >> What can you do in the current syntax that can't be done more easily in the >proposed syntax? > >Understand my code 6 months from now. Modify the code with less risk. >Understand the level of intent in someone else's code I'm using. OK, here is what I can extract from all this: Having a separate syntax for static methods is beneficial because it tells the programmer at a glance that he can call a method from a class without having an instance of that class at hand. I can see this as a fundamental advantage of the current syntax, but I would still question the value of this advantage, assuming that static methods are rare. I would still opt for the unified syntax, and accept the burden on rare occasions of having to scan the body of a method (not "read every line") looking for the presence of instance variables. Perhaps this is why Ruby highlights them with @. I think a bare leading dot is pretty obvious, but now we're getting down to personal preference. If the need to quickly determine if a method is "static" is really an issue, I would say, don't muck with the standard calling sequence, but put a special "decorator" on the header line. I think that is being proposed in PEP 318. Having this decorator could provide the same fundamental benefit as the statement myMethod = staticmethod(myMethod), and this does not require a special first argument. >> Show me some code, and I will show you the equivalent in "Python 3". > >No, that burden is on your shoulders, as everyone not in favor of your >suggestions can let the thread die off and nothing will change. <0.5 wink> In You left out a piece of the prior discussion. You said that I was either ignorant or choosing to ignore the benefits of the current syntax. My response was "show me" such a benefit. Now you seem to be saying the burden is on me to show I have thought of everything. Obviously, I can't do that. Equally obvious is that you could show me one example of what you are talking about and prove your point. I think if we both forget about trying to win an argument, and dig for the facts wherever they may lead, we can avoid these deadlocks. >another thread I suggested you take the time to learn what the 2 or 3 most >common uses are for each of the features that will be affected, and show both >the implementation and use in current Python and after your proposed changes. >Not only will doing this give a clear example to everyone, it'll also show that >you are at least aware of how the different function/method forms are used >today in _real programs_ and not contrived examples - after re-reading some of >your comments I have my doubts. I have shown the 4 function/method forms I'm aware of, and how to translate them to a simpler syntax, in Appendix 1 of Prototypes.doc at http://ece.arizona.edu/~edatools/Python Have you read that? Again, we can avoid deadlock by focusing on the facts in front of us and avoiding the argument "I'm a better expert than you, so I win." We'll either get to the bottom of an issue, or agree that its a matter of personal preference. >> >> When you say the distinction between methods and functions makes >> >> sense, I assume you mean it has some value to the user. I would like >> >> to hear more about this, because I am assuming just the opposite. >> > >> >Yes it has some value, but more than that: it fits the brain quite well. IMO >it >> >adheres to the principle of least surprise, >> >> The Principle of Least Surprise has always been one of my favorites. >> It's a shame this principle offers us so little guidance in resolving >> a simple issue like this unification question. > >All of those guiding principles are subjective, but IMO it's pretty clear here >:) Equally clear from my perspective. >> us in opposite directions. I think the difference may be in our >> backgrounds. You seem quite comfortable with Java, so I would guess >> these different method forms fit with what you have learned there. > >I abhor Java, actually, and I'm not even sure how to do the bound method form >in Java (or C++, which is where my background lies more than Java). > >> I need to feel like I understand what is going on. I'm not >> comfortable with a bunch of arbitrary rules > >Please understand that these are not arbitrary. The fact that you think they >are arbitrary makes me wonder if you really understand them. Don't be offended! Again, you deleted the context. This is in response to your statement that there are only a handful of rules a beginner needs to adhere to. I do understand most of these rules (all but the strange example earlier in this thread). However, I would like to eliminate *some* of them, and keep just one: If you call a function from an insstance, you get a bound function. Otherwise all references to the function are unbound. Even the strange example will do exactly what you expect. Prothon, by the way, eliminates even this rule, following a little too rigidly the dictum "explicit is better". Their so-called explicit binding syntax is a mess. I much prefer Python's implicit syntax. "Practicality beats purity." >What I like about the current syntax, is that you don't really need to memorize >any rules because how you call them is pretty obvious, unless of course you're >not thinking about what you're doing, in which case there are bigger problems >at hand. For example, when I learned Python I never came across some tutorial >showing how to do an unbound method call - I got to the point where I needed >it, I tried the most obvious thing, and it worked. Likewise, the first time I >needed to get a reference to a bound method, I was impressed that the first >thing I tried worked (impressed with the language, not with myself :) ). It didn't go quite as smoothly for me, probably because I was rushed on my other projects, and also because I had no prior experience with OOP. I learned about bound and unbound methods by reading Learning Python, but it didn't really sink in until I started using them. I don't expect my students to learn these topics in the short time we have in class. Most of them will not be writing complete programs, so I don't expect them to pick it up later, either. Most of them will be modifying scripts that have been written by someone with more expertise in Python. A working knowledge of Python up to, but not including, the OOP chapters is sufficient for most. My interest in OOP is not only for what it can do in my own programs, but I see Python OOP as beautiful and elegant (but not perfect), and something that EE's could really benefit from over their entire careers. I will be using it heavily in my own programming, but not expecting my students to learn it. It's right at the edge of what they need to know to run the circuit design tools. That's why I'm so interested in simplified OOP, and uninterested in floor division or metaclasses. >> I need specific examples of problems introduced by the new syntax, or >> of something the old syntax can do better. We can argue general >> principles forever, but one good example will settle this question. > >Like I said, if you really are interested in making headway with your proposal, >*you* need to demonstrate through some non-contrived examples that you >understand how things work today. I've read the pages on your site and either >they don't show all cases that will be affected, or the examples are too buried >by other changes so I missed them. So, show a few examples of how bound methods >are implemented and used today in Python, and how they'd be used and >implemented the new way. Show a few examples of how unbound methods are >implemented and used today, etc. Just showing one example and stating that >everything will be like that glosses over the fact that these things are all >used in very different ways today, and leaves the reader wondering if you have >really thought things through. I think I've done my part on this. The best examples are in Prototypes.doc at http://ece.arizona.edu/~edatools/Python/ I'm also continually adding new examples under the Examples and Exercises link on that same page. Many of these are contributed by readers of this thread, including some who would rather not post here. (Gentle Request: A little less intolerance from some others on this thread might encourage more contributions from people they really need to hear from.) As for a real program, it will be a few months before I have anything sizable. I showed you the statefile example (in response to your request), but you seemed to be insulted, like you thought I was talking down to you, or something. I think the gap in our perceptions can be bridged by focusing on examples. I have to do a lot of work to extract from general criticism and dogmatic statements, anything that I can translate into a specific example. Anything you can do to clarify your statements with examples will be greatly appreciated. The 'bag' example was perfect. >> We can learn a lot by looking at >> how languages designed *after* Python have tried to improve on it. > >Look at the changes to Python, especially over the past few years - many of the >features are publicly credited as having come from other languages. Yes, and that is one of the things I like about Python. GvR is not hesitant to make changes when those changes improve the language. I'm also impressed with the attention to beginners concerns, like the integer division problem. GvR has a remarkable combination of language genius and understanding of beginners' problems. -- Dave From tmcdavid at yahoo.com Thu May 13 02:20:44 2004 From: tmcdavid at yahoo.com (Tom McDavid) Date: 12 May 2004 23:20:44 -0700 Subject: IDLE Path doesn't include current dir after chdir Message-ID: <5a58b1bd.0405122220.5d6be1a5@posting.google.com> I'm trying to learn more Python and have come across a strange behavior. I have Python2.3 installed on a Win2K machine. If I start the python command line, I can do the following: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getcwd() 'C:\\Python23' >>> os.chdir('d:\\python') >>> os.getcwd() 'd:\\python' >>> import fibo ## fibo is fibonacci example from tutorial. Everything works fine. But with IDLE, I get the following: Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 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 >>> import os >>> os.getcwd() 'C:\\Python23' >>> os.chdir('d:\\python') >>> os.getcwd() 'd:\\python' >>> import fibo Traceback (most recent call last): File "<pyshell#5>", line 1, in -toplevel- import fibo ImportError: No module named fibo >>> When I use a desktop shortcut that has my start directory as d:\python rather than the default, I can import my modules and things work reasonably. I get the same "can't find module" result from wxPython's PyAlaMode shell. I dug a little and found that sys.path in idle doesn't seem to contain ".", when I manually added it, import behaves itself in idle after chdir, but I don't want to have to manually fix my path every time I start up. Anyone have more insight or a fix? Thanks, Tom McDavid From newsgroups at jhrothjr.com Sun May 16 17:11:27 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 16 May 2004 17:11:27 -0400 Subject: general Wiki format question and Python Wiki markup parsing libraries References: <c87c38$otu$07$1@news.t-online.com> <c87e40$mbj$3@nemesis.news.tpi.pl> Message-ID: <10afm96drie41b5@news.supernews.com> "Jarek Zgoda" <jzgoda at gazeta.usun.pl> wrote in message news:c87e40$mbj$3 at nemesis.news.tpi.pl... > chris <csad7 at yahoo.com> pisze: > > > is there something like a "standard" wiki format at all, or at least one > > that is widely used? > > Don't think so. I saw more than 10 "simplified markups", of which nearly > all was more complicated than original HTML. Well, I think the "simplified" seems to be a tradeoff in terms of fewer keystrokes, rather than any conceptual simplicity. If you really want to simplify things, please come up with a little WISIWIG editor rather than yet more line noise. John Roth > -- > Jarek Zgoda > http://jpa.berlios.de/ From M.Waack at gmx.de Thu May 20 09:27:28 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Thu, 20 May 2004 15:27:28 +0200 Subject: question on DCOracle2 References: <mailman.102.1085025228.6949.python-list@python.org> Message-ID: <1boun1-ua4.ln1@valpo.de> Joe Wong wrote: > I have two system running with DCOracle2 library. On one system, > the data is returned as 'float' but the other system return the > value as 'string'. What could be the problem here? Maybe in the first system the column is declared as float and on the other as string? Note that a lack of information usually results in a wild guess;) Show us both the python code and the table declaration to get a better answer. Mathias From alfps at start.no Tue May 11 04:23:51 2004 From: alfps at start.no (Alf P. Steinbach) Date: Tue, 11 May 2004 08:23:51 GMT Subject: Make one GUI containing java and C++ componants ? References: <26079f73.0405102305.687f19e4@posting.google.com> Message-ID: <40a08d13.2336455562@news.individual.net> * bart59 at free.fr (bart59) schriebt: > > I have two application: > one in java, which use awt and wing componants as a GUI. > one in C++, which is a 3d engine, then it display in a window a 3D > modele. > > I'm looking for a solution to combine these two interfaces in one > containing the Java componant + the C++ window . > > Is there a way to manage with that? > > JNI doens t seem to be the good approach, it should be difficult to > render the c++ output in a java component Use the AWT native interface, that's what it's there for. > moreover, interactions with the mouse are required in the ed engine... This I think you will have to manage by passing mouse events from Java to C++ using ordinary JNI, but it's been a long time since I did such things. -- A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? From peter at engcorp.com Mon May 17 08:27:22 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 May 2004 08:27:22 -0400 Subject: [PYGTK] Insert Backspace into text widget? In-Reply-To: <a486eedd4fe2a4f69a31134419db3a4c@news.teranews.com> References: <a486eedd4fe2a4f69a31134419db3a4c@news.teranews.com> Message-ID: <AvSdnfp82-Q2MjXdRVn-uw@powergate.ca> Dennis Craven wrote: > Does anyone know how one could insert a backspace into a widget such as a > TextView/Buffer in Pygtk? Whenever I try something like insert(iter, '\b') > I get jibberish inserted into the buffer. What exactly do you expect to see when you insert a backspace into the buffer? (Backspace is a control character, so it is not normally "inserted into a buffer" unless you are actually trying to display it in some way. Are you expecting it to move the insertion point backwards one position, or what?) -Peter From dominpe at dominpe.com Wed May 19 10:27:24 2004 From: dominpe at dominpe.com (=?ISO-8859-1?Q?Juan_Antonio_Dom=EDnguez_P=E9rez?=) Date: Wed, 19 May 2004 16:27:24 +0200 Subject: PERT for python In-Reply-To: <c8fqcn$isb$1@newsg1.svr.pol.co.uk> References: <c8fhi7$qp1$1@news.ya.com> <c8fqcn$isb$1@newsg1.svr.pol.co.uk> Message-ID: <c8fqsl$141$1@news.ya.com> Duncan Smith wrote: > "Juan Antonio Dom?nguez P?rez" <dominpe at dominpe.com> wrote in message > news:c8fhi7$qp1$1 at news.ya.com... > >>Can anoyone let me know if there is a standar PERT algorithm >>implementation in python? >> >>Thanks in advance. >> >>-------------------------- >> >>Juan Antonio Dom?nguez P?rez >>http://www.dominpe.com > > > > Not as far as I know, but I will be coding one up shortly. I'll write one > (probably today / tomorrow) if you promise to give me some feedback :-). > Of course. I need the algorithm to make an offline process, so isolate the PERT code from your application. I only need to date the tasks, and resolve the conflicts by a set of simple rules. Well, I'll wait for your code. And, of course, thanks in advance :D > Duncan > > -- -------------------------- Juan Antonio Dom?nguez P?rez http://www.dominpe.com From guettli at thomas-guettler.de Wed May 26 08:13:03 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 May 2004 14:13:03 +0200 Subject: sys.stdout linebuffered Message-ID: <pan.2004.05.26.12.13.01.121337@thomas-guettler.de> Hi, I start a long running script like this (unix): nohup foo.py > foo.log & Now Python thinks sys.stdout should not be line buffered. How can I force linebuffering? I want to see the log file while the script is still running. I don't like this solution (Wrapping sys.stdout with an own class) http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&selm=u4rz0icqq.fsf%40ctwd0143.fitlinxx.com The "-u" switch is not an option. Thomas From fumanchu at amor.org Mon May 10 11:35:06 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 10 May 2004 08:35:06 -0700 Subject: function causing core dump Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E5620CA@opus.amorhq.net> Xaver Hinterhuber wrote: > I build a function with the following code segment: > > codeObject = new.code( > 0, # argcount > 0, # nlocals > 0, # stacksize > 0, # flags > codeString, # code > (), # consts > (), # names > (), # varnames > 'content', # filename > 'content', # name > 3, # first line number > codeString # lnotab > ) > f = new.function(codeObject, dict, 'f') > f() > > Everything runs fine, until the function is called with f(). > When python tries to execute f(), the core dump happens. > I don't have any clue why python core dumps. > The codeString is nothing complex, its a one-liner. > Could you plz give me some tips what I have to do? As usual, the tip is: include the one piece of information you left out of your post. What is the value of codeString? My first guess is that codeString is something like "return None", or some other string of uncompiled Python code, in which case, you should use eval() instead of new.code and new.function. Those two are used for creating code objects and functions from a _compiled_ codestring, like '\x88\x00\x00Sd\x00\x00S'. In addition, nearly all of the args passed to new.code are *very* important, and cannot simply be set to 0. If you want more info, show us the codeString! :) Robert Brewer MIS Amor Ministries fumanchu at amor.org From imbosol at aerojockey.com Mon May 24 20:40:48 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 24 May 2004 17:40:48 -0700 Subject: Solving the Einstein's Riddle in Python References: <juha.haataja-46ED17.14123824052004@newsread.funet.fi> Message-ID: <60dfb6f6.0405241640.561b9940@posting.google.com> Juha Haataja <juha.haataja at csc.no-spam.fi> wrote in message news:<juha.haataja-46ED17.14123824052004 at newsread.funet.fi>... > I have been learning Python since April, and would like a > few comments from the experts on list processing. > > I managed to implement a Python code for solving the > so-called Einstein's Riddle, see e.g.: > > http://www.manbottle.com/trivia/Einstein_s_Riddle.htm > > I solved the problem in two ways, first the straightforward > way by using lists and list comprehensions. Then I > refactored to code using the Python object model by > deriving new datatypes from the Python list object. The > two versions are available here: > > http://www.csc.fi/oppaat/f95/python/talot.py > http://www.csc.fi/oppaat/f95/python/talot_oo.py Wow, you wrote all that code? Here's my solution: print "I don't know" -- CARL BANKS From skip at pobox.com Thu May 20 12:29:19 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 May 2004 11:29:19 -0500 Subject: Why does the "".join(r) do this? In-Reply-To: <c8ilnb$t1p$00$1@news.t-online.com> References: <545cb8c2.0405200738.296bb094@posting.google.com> <mailman.111.1085068298.6949.python-list@python.org> <c8ilnb$t1p$00$1@news.t-online.com> Message-ID: <16556.56543.361976.551794@montanaro.dyndns.org> Peter> Skip Montanaro wrote: >> Try >> >> u"".join(r) >> >> instead. I think the join operation is trying to convert the Unicode bits >> in your list of strings to strings by encoding using the default codec, >> which appears to be ASCII. Peter> This is bound to fail when the first non-ascii str occurs: ... Yeah I realized that later. I missed that he was appending non-ASCII strings to his list. I thought he was only appending unicode objects and ASCII strings (in which case what he was trying should have worked). Serves me right for trying to respond with a head cold. Skip From tim.one at comcast.net Tue May 25 10:57:44 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue, 25 May 2004 10:57:44 -0400 Subject: r'\' - python parser bug? In-Reply-To: <5155aad2.0405250137.1cd7c53e@posting.google.com> Message-ID: <LNBBLJKPBEHFEDALKOLCOEDLLEAB.tim.one@comcast.net> [Konstantin Veretennicov, on raw strings] >>> Should i submit a bug report to development? [Tim] >> Nope: it's not a bug, and won't change. [Konstantin] > Ok. Does it mean i'm not encouraged to even try inventing a patch? If your purpose in inventing the patch would be to get it accepted into the language, it will be rejected (of course you're not the first person to notice this -- it's a FAQ! The "no trailing odd number of backslashes" business was known before raw strings were introduced, Guido was happy with that, and has explicitly rejected all attempts to change it.). There are also many reasons you might want to work up a patch without caring whether it's accepted (curiosity, education, experimentation, hubris <wink>, ...). > It won't break anything, or will it? Yup. Right now all tools (including Python itself) that scan over strings in Python source can (and usually do) treat backslashes identically, whether in loops or in regexps. If this is changed, you also need to change all such tools to match (including things like the Emacs Python mode, IDLE's parser, tokenize.py, and on & on). It's not *just* the Python compiler that believes r'\' is an unterminated string now. > I agree we can live without r'\', but are there any reasons *against* > r'\'? Yes: it would be an expensive and disruptive change, because it would affect so many programs. It's also opposed to the *purpose* of r-strings: they were introduced to ease creating input for functions and programs that want to do their own backslash escape processing, chiefly for regexp-slinging consumers. Input with an odd number of trailing backslashes makes no sense to them, so there's no need for r-strings to support such a thing. From claird at lairds.com Wed May 5 08:09:55 2004 From: claird at lairds.com (Cameron Laird) Date: Wed, 05 May 2004 12:09:55 -0000 Subject: Newbe-books References: <mailman.195.1083546110.25742.python-list@python.org> <0ktjm1-d3q.ln1@home.rogerbinns.com> Message-ID: <109hmcjdtbqvtf9@corp.supernews.com> In article <0ktjm1-d3q.ln1 at home.rogerbinns.com>, Roger Binns <rogerb at rogerbinns.com> wrote: >Adelein and Jeremy wrote: >> some other language(s). What you do not need (if my thinking is >> correct) is a book about programming using Python. Unfortunately, I >> doubt that such a book exists > >The Python Cookbook published by O'Reilly is a very good example >of such a book. It has something like 200 "recipes" in many >different areas. All of the recipes are solving a real problem, >and in doing so teach you what is Pythonic, what is available >in the standard library and many good (and some bad) practises. >You can see the complete list at >http://www.oreilly.com/catalog/pythoncook/toc.html > >Roger > > As fond as I am of the Cookbook <URL: http://www.unixreview.com/documents/s=7750/uni1041364857773/ > when *I* read "Adelein and Jeremy"'s description of "a straight-forward tour through each of Python's features", I thought of David Beazley's *Python Essential Reference* <URL: http://islab.cs.uchicago.edu/python/ >. -- Cameron Laird <claird at phaseit.net> Business: http://www.Phaseit.net From dygimailNo at SPAMpoczta.fm Fri May 14 10:57:11 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 14 May 2004 14:57:11 GMT Subject: Loop and the list References: <Xns94E9A04898D48dygimailpocztafm@127.0.0.1> Message-ID: <Xns94E9AC509A7A5dygimailpocztafm@127.0.0.1> According to your question and advice: Yes i mean indexing test in the if statement. Just corrected this simple bug. But it still doesn't work. This is a piece of results, the code gives: [1] TY = natezeniep(TX,TY,dr) print TY #first main point gives a list: [9.8627544243153125, 9.764861685914024, 9.6684191984269319, 9.5733984559832201, 9.479771649668697, 9.3875116471769786, 9.2965919731504503, 9.2069867901844269, 9.118670880469038, 9.0316196280445151, 8.9458090016465412, 8.8612155381193709, 8.7778163263753228, 8.695588991880193, 8.6145116816449576, 8.5345630497049747, 8.4557222430686831, 8.3779688881185095, 8.3012830774474473, 8.2256453571154164, ...] [2] max = maxvalue(TY) print "max =",max gives (now) a correct index '0', but... [3] TY = normowanie(TY) #normalize the function print TY gives a non correct () list: [1.0, 9.764861685914024, 9.6684191984269319, 9.5733984559832201, 9.479771649668697, 9.3875116471769786, 9.2965919731504503, 9.2069867901844269, 9.118670880469038, 9.0316196280445151, 8.9458090016465412, 8.8612155381193709, 8.7778163263753228, 8.695588991880193, 8.6145116816449576, 8.5345630497049747, 8.4557222430686831, 8.3779688881185095, 8.3012830774474473, 8.2256453571154164, 8.151036714310175, ...] [conclusion] So the only good item is '0' indexed. For better look there is the code responsible for the bug: def normowanie(TY,max): "normalize the function" for i in range(0,len(TY)-1): TY[i] = TY[i]/float(TY[max]) return TY The function call has arguments: max = '0' and the list TY from [1] at the top of the post. ps Normalizing, i mean to divide (float) all the items in TY list by the max value in the list. So the result list should contain of items between '0' and '1' (float of course, not rounded to int). -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From abcdebl2nonspammy at verizon.net Tue May 18 21:28:38 2004 From: abcdebl2nonspammy at verizon.net (David Lees) Date: Wed, 19 May 2004 01:28:38 GMT Subject: So what's a "pythong"? (was Re: Python/C++ Developers required for consulting position in Brooklyn, NY) In-Reply-To: <FOidnSvClJ3UvDfdRVn-sw@powergate.ca> References: <cf879d68.0405180550.33f29483@posting.google.com> <FOidnSvClJ3UvDfdRVn-sw@powergate.ca> Message-ID: <aLyqc.217042$L31.8420@nwrddc01.gnilink.net> Perhaps "Pythongs" are the current fashion statement in the head hunting world? See http://www.netpixel.com/default.asp which is a head hunting service. David Lees Peter Hansen wrote: >> We are looking for several contractors with very strong C++ and >> Pythong development skills. > > > "Pythong"... now there's a scary image. :-) Ouch! > > -Peter From afilip--usenet at freenet.de Tue May 18 07:22:55 2004 From: afilip--usenet at freenet.de (Arnold Filip) Date: Tue, 18 May 2004 13:22:55 +0200 Subject: "Extracting" a dictionary In-Reply-To: <mailman.20.1084820319.6949.python-list@python.org> References: <mailman.20.1084820319.6949.python-list@python.org> Message-ID: <c8crm8$8hb$1@nntp.ilk.net> Daniel Klein wrote: > Hello, > > I'm quite new to Python, and since a not-so-superficial look into the > docs didn't answer my question (although it still feels quite basic), I > decided to turn to this place: > > Is there a way to 'extract' a dictionary into the current namespace? > That is, if you have > {'foo' : 23, 'bar' : 42} > you would get a variable foo with value 23 and a variable bar with value > 42? Such a function would of course only work on string keys and would > probably have to check that, but still, it sounds practical enough that > surely someone else thought of it before. > > Daniel > How about this: In [1]: d = {'foo' : 23, 'bar' : 42} In [2]: for item in d.items(): ...: exec "%s = %d" % item ...: In [3]: foo Out[3]: 23 In [4]: bar Out[4]: 42 From mva at sysfault.org Thu May 13 12:20:14 2004 From: mva at sysfault.org (Marcus von Appen) Date: Thu, 13 May 2004 18:20:14 +0200 Subject: __slots__ vs __dict__ References: <120520041314481389%JBrouwers@ProphICy.com> <86hdul2tad.fsf@sysfault.org> <mailman.492.1084401209.25742.python-list@python.org> <86d659ylh0.fsf@sysfault.org> <mailman.498.1084425169.25742.python-list@python.org> Message-ID: <86oeosnvsx.fsf@sysfault.org> Andrew Bennetts <andrew-pythonlist at puzzling.org> writes: [...] > Now your example runs just fine (i.e. the script terminates normally, and > nothing happens). I still don't see any error. I thought you would inspect the objects yourself. Let me show you another (now working) example, which will explain it: ------ class DictClass (object): test = "DictTest" def __init__ (self): pass class SlotClass (object): __slots__ = "test" def __init__ (self): self.test = "SlotTest" def print_obj (obj): # inspect .test and show the object attributes print obj.test print dir (obj) # bind new attribute and inspect the object attributes obj.new_test = "Test" print obj.new_test print dir (obj) print "------" return if __name__ == "__main__": dict_obj = DictClass () slot_obj = SlotClass () print_obj (dict_obj) print_obj (slot_obj) --- You will get something like the following output: ---------------- DictTest ['__class__', '__delattr__', '__dict__', ....., '__weakref__', 'test'] Test ['__class__', '__delattr__', '__dict__', ...., '__weakref__', 'new_test', 'test'] ------ SlotTest ['__class__', '__delattr__', ...., '__slots__', '__str__', 'test'] Traceback (most recent call last): File "foo.py", line 31, in ? print_obj (slot_obj) File "foo.py", line 19, in print_obj obj.new_test = "Test" AttributeError: 'SlotClass' object has no attribute 'new_test' ---------------- As you will notice, a __slot__ed object/class has no __weakref__ nor __dict__ attribute. Thus binding new object attributes will fail with an AttributeError. So let's try it again with using __setattr__ in SlotClass: class SlotClass (object): test = "SlotTest" test2 = "SlotTest2" # just for making a tuple creation easier __slots__ = test, test2 def __init__ (self): pass def __setattr__ (self, name, value): # create a dict here to add its key to the __slot__ tuple self.__slots__.__add__ (tuple ((name))) return def print_obj (obj): # inspect .test and show the object attributes print obj.test print dir (obj) # bind new attribute and inspect the object attributes obj.new_test = "Test" print obj.new_test print dir (obj) print "------" return if __name__ == "__main__": #dict_obj = DictClass () slot_obj = SlotClass () #print_obj (dict_obj) print_obj (slot_obj) ---- As you will see, you get an AttributeError again.tuple ((name))was not concatenated to __slots__. I think that should explain enough about the advantage and disadvantage of __slots__ here. (And why do you keep > putting a redundant return at the end of your functions?) I'm used to it :-). > Are you sure this is the same code that you get a crash with? What version > of Python are you using? (I've tested with 2.2.3 and 2.3.3). No, I put messy code without _really_ thinking about it in my first post. I did not realize that self.__slots__ = self._slots in __setattr__ will end up in a recursion... Regards Marcus -- We don't understand the software, and sometimes we don't understand the hardware, but we can *see* the blinking lights! From qual at tiscali.de Sun May 2 08:51:19 2004 From: qual at tiscali.de (Uwe Hoffmann) Date: Sun, 02 May 2004 14:51:19 +0200 Subject: Passing data between threads In-Reply-To: <c72q5t$1pri$1@ulysses.news.tiscali.de> References: <4094B2E3.E802F8D2@mega-nerd.com> <c72q5t$1pri$1@ulysses.news.tiscali.de> Message-ID: <c72ql8$1q0j$1@ulysses.news.tiscali.de> Uwe Hoffmann wrote: > Erik de Castro Lopo wrote: > >> thread.exit () but I can't figure out how. oh you are using the "old thread" module. Try to switch to the threading module if you are not on a very old python version ( in this case the module Queue is not available) From nid_oizo at yahoo.com_remove_the_ Tue May 4 10:47:14 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 04 May 2004 10:47:14 -0400 Subject: Recursively test a package Message-ID: <Q1Olc.31957$ZJ5.896520@news20.bellglobal.com> Hi everyone, What is the simplest way to call unittest.main() for all modules providing it in a package hierarchy? Thx and regards, Nicolas From rechapman at hotmail.com Sat May 29 15:47:43 2004 From: rechapman at hotmail.com (Bob Chapman) Date: Sat, 29 May 2004 14:47:43 -0500 Subject: pywin32 201.1 Windows98SE Problem? Message-ID: <c9aper$6os$1@ngspool-d02.news.aol.com> On two different Windows 98SE Systems, I have attempted to upgrade working Python 2.3.3 and win32all installations to Python 2.3.4. After what appeared to be successful installations of Python-2.3.4.exe, I next executed: > pywin32-201.win32-py2.3.exe as downloaded from SourceForge, in the belief that it was the appropriate companion for Python-2.3.4 (perhaps this is my mistake?). In both cases, the installed Pythonwin outputs the following error messages and does NOT run: > File >"C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", line >163, in InitInstance > import interact > File >"C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\interact.py", line >26, in ? > import winout > File "C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\winout.py", >line 26, in ? > from pywintypes import UnicodeType > File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 69, in >? > __import_pywin32_system_module__("pywintypes", globals()) > File "C:\PYTHON23\Lib\site-packages\win32\lib\pywintypes.py", line 62, in >__import_pywin32_system_module__ > raise ImportError, "Can not locate " + filename >exceptions.ImportError: Can not locate pywintypes23.dll On checking, the NEW 'pywintypes23.dll' IS in c:\windows\system > 77824 May 28 11:10 c:\windows\system\pywintypes23.dll If this file is copied to C:\Windows then Pythonwin starts without the error messages and appears to work. In previous Windows 98SE installations, the pythonwin dlls have worked OK from c:\windows\system where they are installed so I don't understand what's happening here? (Note: I've installed Python-2.3.4.exe and pywin32-201.win32-py2.3.exe on a Windows XP sytem without this problem.) -- From peter at engcorp.com Wed May 26 12:48:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 12:48:30 -0400 Subject: sys.stdout linebuffered In-Reply-To: <pan.2004.05.26.14.43.44.743357@thomas-guettler.de> References: <pan.2004.05.26.12.13.01.121337@thomas-guettler.de> <KcednfJM-catAyndRVn-gQ@powergate.ca> <pan.2004.05.26.14.43.44.743357@thomas-guettler.de> Message-ID: <KpadnYaVlvDDVyndRVn-uw@powergate.ca> Thomas Guettler wrote: > I like to use #!/usr/bin/env > > ===> cat minus-u.py > #!/usr/bin/env python -u > > ===> ./minus-u.py > /usr/bin/env: python -u: No such file or directory Consider using /usr/bin/python instead? >>Nevertheless, in the unlikely case that you >>absolutely cannot use the -u switch, look at the description of >>that option in the output of "python -h" and use the environment >>variable mentioned there instead. > > The environment variable has the drawback, > that I need to set it before every call to this > script. Other scripts should not be unbuffered. If this is the only script with special needs, why not just create a separate shell script which invokes python on the other script directly? #!/bin/sh /usr/bin/env python -u specialscript.py -Peter From rogerb at rogerbinns.com Mon May 3 17:28:31 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 3 May 2004 14:28:31 -0700 Subject: pychecker proposal References: <f8097096.0405030958.1cc47dda@posting.google.com> Message-ID: <m4qim1-3gl.ln1@home.rogerbinns.com> Nick Jacobson wrote: > I think that PyChecker should be part of the "batteries included" > library that comes with Python. It can be a very useful tool for > catching errors and bad style. > > If it were in the standard library, newbies would be aware of it > sooner. I would prefer a "lint" mode to the Python interpretter that runs in a full warnings mode, using both static analysis that pychecker does as well as any dynamic analysis that could be done. I don't even care if it runs at half the speed of normal Python. Roger From mcherm at mcherm.com Wed May 5 07:44:40 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 5 May 2004 04:44:40 -0700 Subject: improving the Python docs -- a wiki? copy PHP's model? Message-ID: <1083757480.4098d3a86ddfa@mcherm.com> Stephen Ferg writes: > So I put this question to the entire Python community. Can we create > an interactive site, and the supporting organizational infrastructure, > that will enable everyone in the Python community easily to contribute > to the Python documentation? John Roth replies: > As Andrew commented, there's nothing stopping you from > contributing. There's also nothing stopping you from setting > up a wiki yourself so people can comment on various pages > of the official documentation. Actually, please don't set up yet another wiki. Instead, go to http://www.python.org/cgi-bin/moinmoin/ and start creating pages. (You'll need to create a user account.) If you're feeling REALLY ambitious, you could go to http://www.python.org/cgi-bin/moinmoin/ModulesThatNeedDocs and volunteer to help fill in some of the existing gaps in the official documentation. I happen to agree with you that it should be made easier for community members to contribute to the documentation. I agree that a wiki is a good system for doing so. But if you want to see it actually HAPPEN, the secret is to create some momentum and then others will start to jump on board. So use the wiki and start creating "supporting notes" for the documentation. If the "supporting notes" become good enough, I assure you that we will incorporate them into the "official" documentation -- either by using the text, or by including references to the wiki in the official documentation. One point you should note about the existing documentation is that, unlike a wiki, it is available in a large number of different formats. The original TEX source is used to generate multiple formats including HTML but also PDF and a number of other formats. A wiki can't take the place of that, but then static docs can't incorporate community involvement as easily as a wiki... there's room for both. -- Michael Chermside From andreas at kostyrka.org Sat May 15 13:00:13 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 15 May 2004 19:00:13 +0200 Subject: MailMan integrated with JSP/Servlet integration In-Reply-To: <1ed550fd.0405150539.3adffc13@posting.google.com> References: <1ed550fd.0405150539.3adffc13@posting.google.com> Message-ID: <1084640413.26865.468.camel@andi-lap> Am Sa, den 15.05.2004 schrieb michela rossi um 15:39: > Hi, > Wonder if anyone can help me. > > I have a client for whom we are building a website using J2SE & TOMCAT > 4.1.7. (at clients request). The client also has an installation of > MailMan that they would like us to use to validate registered users. > > All well and good, but given that the bulk of the websites code will > be written using Java, and MailMan is written in Python - this seems > to represent a problem or two : e.g. how will the Java code > interrogate the MailMan installation to find out whether a user has > validated correctly? Is there any kind of Java interface that anyone > knows about? Well the authentication game is fairly easy: Just access an URL that requires authentication. This should work both ways: Java -> Mailman and Mailman -> Java :) Andreas From michela_rossi66 at hotmail.com Tue May 18 17:50:27 2004 From: michela_rossi66 at hotmail.com (michela rossi) Date: 18 May 2004 14:50:27 -0700 Subject: MailMan integrated with JSP/Servlet integration References: <1ed550fd.0405150539.3adffc13@posting.google.com> <mailman.43.1084640492.4157.python-list@python.org> <1ed550fd.0405160226.5a088220@posting.google.com> <mailman.8.1084798433.6949.python-list@python.org> Message-ID: <1ed550fd.0405181350.6c5c880b@posting.google.com> list-python at ccraig.org (Christopher A. Craig) wrote in message news:<mailman.8.1084798433.6949.python-list at python.org>... > michela_rossi66 at hotmail.com (michela rossi) writes: > > > Andreas, > > > > Thanks - but I don't really understand the reply. Can you expand at all? > > Thanks, Michela. > > The easiest way is to make a seperate page (and it doesn't matter what > it's written in) that authenticates users and issues authentication > cookies. Then you need to change mailman and the java stuff to > respect those cookies. > > For an example, see Yale's CAS: > http://www.yale.edu/tp/cas/ Sounds good - except cookies not allowed. From sarah.tanembaum at yahoo.com Wed May 5 13:21:31 2004 From: sarah.tanembaum at yahoo.com (Sarah Tanembaum) Date: Wed, 5 May 2004 13:21:31 -0400 Subject: Web programming ... References: <c7b2er$1q2uv$1@ID-205437.news.uni-berlin.de> <D86dnTg-ForkgwTdRVn-vg@comcast.com> Message-ID: <c7b7r6$1uo6g$1@ID-205437.news.uni-berlin.de> Thanks Moxley. I too just finish with a very small project with PHP, Family Photo Album. Where can I find any good example of Python web programming - small, concise and easy to follow, to re-write my PHP apps in Python. I'm using MySQL to store the photos information. Thanks "Moxley Stratton" <moxley at moxleydata.com> wrote in message news:D86dnTg-ForkgwTdRVn-vg at comcast.com... > Sarah Tanembaum wrote: > > Is python good for creating Web application? I do like the OOness of Python, > > as a newbie, I'm trying to find out if Python has all its necessary > > modules/utilities for Web programming just as extensive as, say, PHP or > > Ruby(some say that Ruby is not ready for this sort of application and is not > > yet mature as Perl, Python, and PHP - is it true?). > > > > > > > > PHP is a more straight-forward web development language for a newbie > because it has been developed and marketed for the web developer in mind. > > However, this is how I see the difference: PHP provides only one > built-in basic approach to web application development: a web server > module (or CGI) plus a page template model, similar to asp and jsp, plus > the PHP language. Python doesn't provide any web application development > model built-in. You either develop Python web applications as CGI > scripts-- which isn't very popular because of performance issues-- or > you work with a web application model that somebody has developed. > Because Python doesn't enforce any particular web development model, > developers are free to take any approach that has been developed, or > they may develop their own model. This creates the potential for more > sophisticated applications, but it almost always makes it more difficult > than PHP to create small ones. It also means that as a newbie, you have > to spend the time to pick a model to start with. > > Another thing I'd like to say about the PHP model is that it is very > mature and well-known. > > I'm a PHP developer who has been tinkering around with Python for some > time now. I've been researching Webware as a candidate for my primary > Python web development model. > > -- > Moxley Stratton From donn at drizzle.com Fri May 28 00:28:00 2004 From: donn at drizzle.com (Donn Cave) Date: Fri, 28 May 2004 04:28:00 -0000 Subject: terminological obscurity References: <1085328791.560793@yasure> <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> <1085378050.309299@yasure> <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <donn-F5877E.11513724052004@nntp1.u.washington.edu> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <donn-10607D.09032925052004@nntp1.u.washington.edu> <dam7b0dip3fi1dnicj4gmnb30d5vf2up88@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> Message-ID: <1085718479.27401@yasure> Quoth Arthur <ajsiegel at optonline.com>: | On Thu, 27 May 2004 19:30:40 +0200, "Martin v. L?wis" | <martin at v.loewis.de> wrote: |> |> It is very clear to my why he did not say what Donn said - because |> he thought that the notion of homogenous and heterogenous is obvious |> to anybody. ... | ... That is the second time I was told the | problem was *my* capacity to understand what Guido meant. Well, I'm unable to see such problems in any other terms. Understanding is limited by capacity to understand, certainly. |> He then *also* said something about how static typing might be |> introduced into Python - but that was about possible static typing, |> not about the terms "homogenous" and "heterogenous". Even with |> static typing, it might be possible to declare a list that is |> statically typed, contains homogenous data, and yet contains |> objects as different as None and a module. The type of this |> list might be "list of (NoneType union ModuleType)", better |> declared as "list of optional ModuleType". | Donn. who I think we agree, brought some light to this discussion did | state clearly, I think, that the use of the "homogenous data" (in | describing for example None and a module) is bad and misleading | terminolgy. Perhaps, because it supports too well a supposition that | we are only talking in tautologies. What can be said be homogenous | about such data, outside of the membership in a list? Donn suggests | the list is homogenous, even if the data is not, in any meaningful | sense. I think I understand that a bit. Good! You're too generous, but it's good of you to spell my name right. | Yet you insist, with a fresh start on all this, on using the | terminology "homogenous data". Oh, well. You knew what he meant, though, didn't you? Note that the passage above describes a slightly different homogeneity. This list still contains a module and a None, but now some arrangement has been made to give them each the same type, when before they were of completely disparate types (and still are.) Well, I'm not really sure what he has in mind there, so there is some ambiguity for students of homogeneity such as ourselves. I'm convincing myself though that this type information does least for practical purposes become a property of the object, so they are indeed homogeneous considered on their own. In some way. In some languages with strong static typing, such as Haskell or ML, you'd use a parameterized `algebraic' type sort of like type option a = Some a | Nothing This is essentially a wrapper, a package from which you may retrieve either the actual data type, or `Nothing'. That "a" represents an item of the actual type. The complete type of the list would be `option ModuleType'. However it's done, obviously the fun is in the way a program can use typed expressions. Given a classic Python idiom, where the programmer has learned that optmodlist may contain Nones, v = optmodlist[i] if v is None: print i, '(None)' else: print i, 'Module', v.__name__ A strongly typed language will do just the same thing, but in a more explicit and rigorous way, under the sanction of the compiler. Like case optmodlist[i]: of Nothing: print i, '(None)' of Some v: print i, v.__name__ One of the problems though is how we fit Python's OOP model in here. List types like `option ModuleType' seem to be restricted to subtype polymorphism, plus casting to subtypes, which is no fun. We would surely not chafe at an `option FileType' that doesn't allow StringIO. So maybe the whole system needs to come from a really different angle, possibly having nothing to do with implementation types like FileType, NoneType, classes, but instead maybe the interface ideas that have been going around for some time now. And of course one could want the contents of a list to conform to a single interface, thus being homogeneous in yet another sense. Donn Cave, donn at drizzle.com From winexpert at hotmail.com Wed May 12 16:00:25 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 12 May 2004 20:00:25 +0000 Subject: Why is a None appearing in my output? Message-ID: <BAY2-F891vyJr6ucKH40000b549@hotmail.com> Thanks, I didn't see that. I'm a c/c++ programmer for the most part and this is my 2nd day at python... >From: "Hornberger, Chris" <Chris.Hornberger at blackrock.com> >To: "David Stockwell" <winexpert at hotmail.com>, <python-list at python.org> >Subject: RE: Why is a None appearing in my output? >Date: Wed, 12 May 2004 15:50:14 -0400 > >You're not returning a value, simply holding it or printing stuff out. >Return your value inside the function call. Thusly: > >def SomeFunction( someVar ): > returnVal = 0 > # do stuff > return returnVal > > > >-------------------------- >Chris Hornberger >Blackrock - 302.797.2318 >chris.hornberger at blackrock.com > >Card carrying MSDN member since 2004. >No, really. I've got the card to prove it. > > >-----Original Message----- >From: python-list-bounces+chris.hornberger=blackrock.com at python.org >[mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On >Behalf Of David Stockwell >Sent: Wednesday, May 12, 2004 3:47 PM >To: python-list at python.org >Subject: Why is a None appearing in my output? > > >Hello, > >I'm a fairly new user of python. I am going through the >tutorial on the python.org website and observed a weird thing >around the 6.0 modules area. (http://docs.python.org/tut/node8.html) > >My python version: >Python 2.2.3 (#1, Feb 26 2004, 14:37:42) >[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 > > >I entered the following text into a 'module file' and saved it: > >def fib6(n): # write Fibonacci series up to n > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b > else: > print "done b[",b,"], n[",n,"], a[", a,"]" > >print "fib6:", fib6(50), "---" >print "next" > > >I then run it and get the results: >fib6: 1 1 2 3 5 8 13 21 34 done b[ 55 ], n[ 50 ], a[ 34 ] >None --- >next > >The question I'm having is what is causing the 'None' to print? >The example tutorial doesn't have the None, but when I run >I am seeing it and I do not see what causes that. > >I added the 'else on the while and the "---" stuff to try to figure out >what >the None means. > >but i have no clue ... > >Thanks > >David > >_________________________________________________________________ >Getting married? Find tips, tools and the latest trends at MSN Life Events. >http://lifeevents.msn.com/category.aspx?cid=married > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Is your PC infected? Get a FREE online computer virus scan from McAfee? Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu May 20 14:38:50 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 20 May 2004 20:38:50 +0200 Subject: GetClipboardData(CF_BITMAP) unimplemented References: <90924643.0405200902.610baf23@posting.google.com> Message-ID: <c8iu11$kk4$1@news-reader5.wanadoo.fr> Hi ! And the same for .SetClipboardData( Please... Please ? Thanks by advance. From hwlgw at hotmail.com Sat May 22 02:36:41 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 21 May 2004 23:36:41 -0700 Subject: module looping Message-ID: <cb035744.0405212236.1a1e95c@posting.google.com> How to loop without using a looping construct; or a generator without "yield". ----- file: generatory.py -------------------------------- import receiver maxx = 10 def send(x): if x >= maxx: return x = x + 1 receiver.send(x) if __name__ == '__main__': receiver.send(1) ---------------------------------------------------------- ----- file: receiver.py --------------------------------- import generator def send(what): print 'receiver received:', what generator.send(what) ---------------------------------------------------------- From moma at example.net Thu May 20 12:24:15 2004 From: moma at example.net (moma) Date: Thu, 20 May 2004 18:24:15 +0200 Subject: Why does the "".join(r) do this? In-Reply-To: <545cb8c2.0405200738.296bb094@posting.google.com> References: <545cb8c2.0405200738.296bb094@posting.google.com> Message-ID: <iY4rc.2701$eH3.54310@news4.e.nsc.no> Jim Hefferon wrote: > Hello, > > I'm getting an error join-ing strings and wonder if someone can > explain why the function is behaving this way? If I .join in a string > that contains a high character then I get an ascii codec decoding > error. (The code below illustrates.) Why doesn't it just > concatenate? > > I'm building up a web page by stuffing an array and then doing > "".join(r) at > the end. I intend to later encode it as 'latin1', so I'd like it to > just concatenate. While I can work around this error, the reason for > it escapes me. > > Thanks, > Jim > > ================= program: try.py > #!/usr/bin/python2.3 -u > t="abc"+chr(174)+"def" > print(u"next: %s :there" % (t.decode('latin1'),)) > print t > r=["x",'y',u'z'] > r.append(t) > k="".join(r) > print k > > ================== command line (on my screen between the first abc > and def is > a circle-R, while between the second two is a black oval with a > white > question mark, in case anyone cares): > jim at joshua:~$ ./try.py > next: abc?def :there > abc�def > Traceback (most recent call last): > File "./try.py", line 7, in ? > k="".join(r) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xae in position > 3: ordinal not in range(128) What about unichr() ? #!/usr/bin/python2.3 -u t="abc"+unichr(174)+"def" print t print(u"next: %s :there" % (t),) print t r=["x",'y',u'z'] r.append(t) # k=u"".join(r) k="".join(r) print k // moma http://www.futuredesktop.org From newsgroups at jhrothjr.com Thu May 20 21:48:40 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 20 May 2004 21:48:40 -0400 Subject: Confused about while statement References: <dHcrc.86491$536.14466932@attbi_s03> Message-ID: <10aqo0n7pj9465e@news.supernews.com> "EAS" <eriksp at attbi.nospam.com> wrote in message news:dHcrc.86491$536.14466932 at attbi_s03... > In theory, the following code should ask for the user to enter a value for h > until he/she enters hello or goodbye. > > h = "hi" > while h != "hello" or "goodbye": > h = raw_input("Value for h:") > > But the program keeps asking for a value no matter what I enter. Why doesn't > it work? Operator precedence and a misunderstanding about how "or" works. Operator precedence means that the expression is equivalent to: (h != "hello") or "goodbye" The result of h != "hello" is either True or False. The way "or" works, if the result was false, the second operand would be substituted, so you would get "goodbye" which is true. In other words, the result of the entire expression is either True or "goodbye", which is also true. So the loop never terminates. The "proper" way to write this test is: while h not in ("hello", "goodbye"): There are other ways, but this is probably the most readable. John Roth > > From vsn5134 at charter.net Fri May 7 19:04:50 2004 From: vsn5134 at charter.net (Peter Smith) Date: 7 May 2004 16:04:50 -0700 Subject: Unix compress (.Z) files Message-ID: <f4fb9bc8.0405071504.51eb9325@posting.google.com> Hi: Are there any utilities in Python which can uncompress a file zipped on a unix system using "compress"? I tried playing around with zlib and was not successful. Also I am trying not to use the OS (os.popen('compress > file.Z','w') call. I am using Python 2.3.3. If you have the exact syntax that would be great. Thanks. From winexpert at hotmail.com Thu May 27 14:01:04 2004 From: winexpert at hotmail.com (David Stockwell) Date: Thu, 27 May 2004 18:01:04 +0000 Subject: How to I print without newline ? Message-ID: <BAY2-F58Kkc1F9LIV5o00005074@hotmail.com> oh one more small might be a freebie ftp usually supports the command 'hash' when you use it it displays that character (#) every X bytes. You can specify what each # maps to (as in how many bytes).... David Stockwell ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: "Larry Bates" <lbates at swamisoft.com> >To: python-list at python.org >Subject: Re: How to I print without newline ? >Date: Thu, 27 May 2004 12:44:57 -0500 > ><fowlertrainer at anonym.hu> wrote in message >news:mailman.364.1085670411.6949.python-list at python.org... > > Hi ! > > > > I want to print, but without newline. I want to create a progress for > > ftp, but the print is drop a newline for every percent. > > I want like this: > > > > 0% 25% 50% 75% 100% > > > > But this happening: > > 0% > > 25% > > 50% > > 75% > > 100% > > > > How to I prevent the newlines ? > > > > Thanx for help: > > FT > > > > > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From pe at ono.es Mon May 17 11:47:32 2004 From: pe at ono.es (Derfel) Date: 17 May 2004 15:47:32 GMT Subject: Binary handling References: <2gro06F5ti55U1@uni-berlin.de> <40A8D7F3.7080400@zoran.com> Message-ID: <2gs54kF69jomU1@uni-berlin.de> Miki Tebeka escribi? en news:40A8D7F3.7080400 at zoran.com: > Hello Derfel, > > --- bitter.py --- Thanks for the module, it works well and is the solution to my problem. Thanks. Regards -- Derfel From cs993442 at cs.yorku.ca Thu May 20 12:23:52 2004 From: cs993442 at cs.yorku.ca (Daniel Orner) Date: Thu, 20 May 2004 12:23:52 -0400 Subject: Socket sample? In-Reply-To: <c8g4nr$bkq$06$1@news.t-online.com> References: <mailman.81.1084983200.6949.python-list@python.org> <c8g4nr$bkq$06$1@news.t-online.com> Message-ID: <40ACDB98.4070908@cs.yorku.ca> Hmm... I'm looked at the SocketServer, but I'm pretty confused about how to use it. As far as I can tell it doesn't actually do any forking/threading/selecting at all. There's a lot of generic stuff which seems to allow that behavior for subclasses, but I can't see any specific code that does that kind of thing. Or maybe I'm just missing something stupendously obvious. If so, would you be so kind as to give me a quick example of how it would be used? I also took a quick look at twisted... it looks like it's way too complex for what I have in mind. -_- Basically, I just want a socket to transfer information to/from a client program, essentially to synchronize data between the server and the client. The program is run automatically (no user input). However, I do want it to be fast, which means no waiting for a connection. That's why I just want to see some sample code about how to use a server socket. Any help would be greatly appreciated! --Daniel From andrew-pythonlist at puzzling.org Wed May 5 01:11:31 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 5 May 2004 15:11:31 +1000 Subject: question: parameters for create_polygon() method In-Reply-To: <40986DD6.F06FF651@shaw.ca> References: <40984D5A.B819BF28@shaw.ca> <mailman.254.1083723811.25742.python-list@python.org> <40986DD6.F06FF651@shaw.ca> Message-ID: <20040505051131.GE20777@frobozz> On Wed, May 05, 2004 at 04:30:03AM +0000, SeeBelow at SeeBelow.Nut wrote: > Andrew Bennetts wrote: > > > > On Wed, May 05, 2004 at 02:11:28AM +0000, SeeBelow at SeeBelow.Nut wrote: > > > Tkinter's canvas object has the method create_polygon(). > > > > > > The docs say the parameters should be like: > > > (x1, y1, x2, y2, x3, y3, .....) > > > > > > But it's often much better programming practice to have a list of > > > tuples, each point being a tuple, like this: > > > [(x1, y1), (x2, y2), (x3, y3),......] > > > > > > Is there a good way to manipulate my polygons in the latter form, but > > > still use create_polygon() to draw them? > > > > create_polygon(*list_of_points) > > > > -Andrew. > > Thanks Andrew, but I don't understand it. What's that * thing? > > Is there a * operator that converts a list of tuples into one big tuple? Sorry, I misinterpreted the problem slightly; I just checked the docs for create_polygon and realised it takes an argument that is a sequence of co-ords, rather than a variable number of args that are the co-ords. I also realised that I wasn't thinking clearly anyway. You really just need a flatten function, e.g.: def flatten(iterable): for elem in iterable: for subelem in elem: yield subelem You can then use this like so: create_polygon(tuple(flatten(list_of_points))) (There are more complex flatten recipes out there, such as http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/118845, but this one is sufficient for your needs). -Andrew. From apardon at forel.vub.ac.be Wed May 12 07:50:09 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 May 2004 11:50:09 GMT Subject: Scope rule pecularities References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <c7kqgt$9ja$1@news.service.uci.edu> Message-ID: <slrnca43ri.1i9.apardon@trout.vub.ac.be> Op 2004-05-09, Josiah Carlson schreef <jcarlson at uci.edu>: >>>Except when the /referenced object/ is immutable. Name rebinding is >>>necessary to reference the newly created immutable object that was >>>created through the +=, -=, /=, %=, *=, &=, |=, or ^= operations. >> >> >> IMO having operators that should work in place for object that >> are immutable, sound contradictory. Having the following code: >> >> a = ... >> b = ... >> c = a >> a += b >> >> I now expect a and c still to be the same object. > > If 'a' is mutable, and 'a' has the proper __iadd__ operator, then 'a' > and 'c' will be the same object when you are done. However, integers, > strings, floats,... are immutable, so 'a' and 'c' won't be the same > object in those cases (Python only rebinds objects that are specified, > due to the whole "explicit is better than implicit" Zen). Python does more than enought things in an implicit way. > The real thing to remember is that Python isn't <insert the language you > expect Python to behave like>, I think it is reasonable to expect a language to behave consistently. > and your expectations are not what > actually happens. What you think /should/ happen is not what /does/ > happen, and I am quite sure it is not what /Guido thinks should happen/. So? Is what Guido thinks should happen above criticism. I think that if what Guido thinks should happen makes the language behave inconsistenly then > Once you wrap your mind around the implications of mutables and > immutables, Well the more I wrap my mind around them, the less I like them. > and what you can/can't do with them, then perhaps the += > semantics will seem less confusing. I would like to be able the understand what += does to an object without the need of knowing it is mutable or not. -- Antoon Pardon From mwh at python.net Mon May 10 13:42:13 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 10 May 2004 17:42:13 GMT Subject: newbie question - remove a module from ram References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> <c7nvr1$fsc$01$1@news.t-online.com> <LJMnc.77976$Dn1.10841@fe2.texas.rr.com> <vAOnc.65750$nG5.54169@newssvr25.news.prodigy.com> Message-ID: <m3llk0kwln.fsf@pc150.maths.bris.ac.uk> john fabiani <jfabiani at yolo.com> writes: > Paul McGuire wrote: > > So then what if he follows up with: > > del sys.modules["random"] > > Are there any other dangling references to this module that would > > stymie the > > garbage collector (assuming that the OP hasn't saved off his own reference > > to the module)? > > -- Paul > > > I think I follow: but doesn't the garbage collector decide what is to > be done? Assuming that there were no dangling references wouldn't > the ram be available for re-use? Well, that depends on vagaries of your allocator, but probably. Why are you so worried about the RAM your modules take up? Cheers, mwh -- The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offence. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From asdf at asdf.com Tue May 11 12:12:44 2004 From: asdf at asdf.com (asdf sdf) Date: Tue, 11 May 2004 16:12:44 GMT Subject: How to read files written with COBOL In-Reply-To: <Q%Ync.184795$L31.100023@nwrddc01.gnilink.net> References: <mailman.404.1084210463.25742.python-list@python.org> <Q%Ync.184795$L31.100023@nwrddc01.gnilink.net> Message-ID: <0Y6oc.47320$jI4.23568@newssvr29.news.prodigy.com> Steve Williams wrote: > I wrote an ETL system in python for a client to convert from Microfocus > COBOL to DB2. Here are some of the problems I saw: > > 1) COBOL has a very rich set of datatypes defined by the PICTURE clause <...snipping various items...> > That is, I took the original COBOL 01 level definition and > converted it to a list with definition parameters name, type, > length, decimal point, etc. to make it easy for Python and > to add some stuff to make DB2 happy (convert to title case. . .) Steve, I've been looking for ideas on getting at DB2 and Adabas from Python. You might have some thoughts. Is it feasible to go to directly to MVS/DB2/Adabas from Python on Unix or Win? Is it more realistic to hit DB2 on AIX or Linux and use some kind of DB2 linking or replication to reach DB2/MVS? Other ideas? Maybe 3270 emulation with screen scraping? How about telnet 3270? (Hundreds years of ago, I could dial into a command line MVS environment.) I don't mean to hijack the thread. I think this is related and might be helpful to unfortunates to have to interoperate with legacy systems. From __peter__ at web.de Thu May 13 12:42:43 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 May 2004 18:42:43 +0200 Subject: Logical AND question References: <c805mk01ore@enews1.newsguy.com> <ufza4705m.fsf@broadpark.no> Message-ID: <c808i3$aen$06$1@news.t-online.com> Tor Iver Wilhelmsen wrote: > "3c273" <nospam at nospam.com> writes: > >> >>> if s and t == '': >> print "This doesn't work!" > > This is really > > if (s) and (t == '') > > which evaluates to false since "if (s)" returns false for the empty > string. The original poster probably wants >>> if s == t == "": ... print "this works" ... this works >>> or the conventional >>> if s == "" and t == "": ... print "but this is more common" ... but this is more common >>> Peter From noamr at correctme.users.sourcephorge.net Sat May 22 17:01:12 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Sun, 23 May 2004 00:01:12 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: <r6-dnZ3iwqgNETPdRVn-uQ@comcast.com> References: <c8l3s3$27o$1@news.iucc.ac.il> <r6-dnZ3iwqgNETPdRVn-uQ@comcast.com> Message-ID: <c8of2o$o5k$1@news.iucc.ac.il> Hello, Larry Bates wrote: > I think it is odd that I have never encounter > many of these types of constructs repeatedly in > my code. Perhaps you could share a little more > of where you see this type of think popping up > a lot? I suspect that there is another method > for solving the problem that might be faster > and easier to read/program. > > Larry Bates, > Syscon, Inc. > > With pleasure. Here are two examples: 1. Say I have a list with the number of panda bears hunted in each month, starting from 1900. Now I want to know how many panda bears were hunted in year y. Currently, I have to write something like this: sum(huntedPandas[(y-1900)*12:(y-1900)*12+12]) If my suggestion is accepted, I would be able to write: sum(huntedPandas[(y-1900)*12:>12]) (Yes, I know that it may also be expressed as sum(huntedPandas[(y-1900)*12:(y-1901)*12]), but it's less clear what I mean, and it's still longer) 2. Many data files contain fields of fixed length. Just an example: say I want to get the color of the first pixel of a 24-bit color BMP file. Say I have a function which gets a 4-byte string and converts it into a 32-bit integer. The four bytes, from byte no. 10, are the size of the header, in bytes. Right now, if I don't want to use temporary variables, I have to write: picture[s2i(picture[10:14]):s2i(picture[10:14])+4] I think this is nicer (and quicker): picture[s2i(picture[10:>4]):>4] Thanks for your interest, Noam Raphael From ktr46 at hotmail.com Fri May 21 10:51:38 2004 From: ktr46 at hotmail.com (Kevin T. Ryan) Date: Fri, 21 May 2004 10:51:38 -0400 Subject: Help w/ HTMLParser lib References: <40ad7619$0$3114$61fed72c@news.rcn.com> Message-ID: <40ae177d$0$3106$61fed72c@news.rcn.com> Thanks to both of you - I will try to incorporate the regex's and I'll check out tidy. Take care, Kevin "Kevin T. Ryan" <kevryan0701 at yahoo.com> wrote in message news:40ad7619$0$3114$61fed72c at news.rcn.com... > Hi all - > > I'm somewhat new to python (about 1 year), and I'm trying to write a program > that opens a file like object w/ urllib.urlopen, and then parse the data by > passing it to a class that subclasses HTMLParser.HTMLParser. On the web > page, however, there is javascript - and I think that is causing an error > in parsing the data. Here's the error: > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "html_helper.py", line 30, in parse_data > p.feed(data) > File "//usr/lib/python2.2/HTMLParser.py", line 108, in feed > self.goahead(0) > File "//usr/lib/python2.2/HTMLParser.py", line 150, in goahead > k = self.parse_endtag(i) > File "//usr/lib/python2.2/HTMLParser.py", line 329, in parse_endtag > self.error("bad end tag: %s" % `rawdata[i:j]`) > File "//usr/lib/python2.2/HTMLParser.py", line 115, in error > raise HTMLParseError(message, self.getpos()) > HTMLParser.HTMLParseError: bad end tag: "</scr' + 'ipt>", at line 411, > column 7 > > I've tried to use a try/except clause both w/in my class and w/in a function > that wraps the class for easy access, but to no avail. The code works on > other websites, so I know that it's not *completely* off. Any help would > be greatly appreciated! TIA :) > > Kevin From richie at entrian.com Thu May 6 06:17:33 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 06 May 2004 11:17:33 +0100 Subject: MySQL vrs SQLite In-Reply-To: <slrnc9is2h.8mg.ramen@lackingtalent.com> References: <mailman.283.1083787205.25742.python-list@python.org> <slrnc9is2h.8mg.ramen@lackingtalent.com> Message-ID: <ie3k901681imsuvj6629o39re9pkgcmrmm@4ax.com> [Dave, quoting the SQLite docs] > """SQLite is "typeless". This means that you can store any kind of data you > want in any column of any table, regardless of the declared datatype of that > column. (See the one exception to this rule in section 2.0 below.) This > behavior is a feature, not a bug. A database is suppose to store and > retrieve data and it should not matter to the database what format that data > is in. The strong typing system found in most other SQL engines and codified > in the SQL language spec is a misfeature - it is an example of the > implementation showing through into the interface. SQLite seeks to overcome > this misfeature by allowing you to store any kind of data into any kind of > column and by allowing flexibility in the specification of datatypes.""" How about this? """Python containers (eg. lists, sets, tuples) are "typeless". This means that you can store any kind of data you want in any container, without a declared datatype for that container. This behavior is a feature, not a bug. A container is suppose to store and retrieve data and it should not matter to the container what format that data is in. The static typing systems found in many other programming languages and codified in many language specs is a misfeature - it is an example of the implementation showing through into the interface. Python seeks to overcome this misfeature by allowing you to store any kind of data into any container and by allowing flexibility in the specification of datatypes.""" See every third posting to comp.lang.python over the past ten years for why this kind of thing may or may not be a good idea. Most of the arguments that apply to dynamic typing in Python also apply to typelessness in databases (the main one being: it's up to your unit tests, not anything else, to make sure your program works). If Python's dynamic typing fits your brain, it seems likely that a typeless database should do so too. -- Richie Hindle richie at entrian.com From porky_pig_jr at my-deja.com Tue May 11 19:28:00 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 11 May 2004 16:28:00 -0700 Subject: newbie question: should I learn TKinter or skip it and learn more advanced toolkit? Message-ID: <56cfb0e3.0405111528.b203b78@posting.google.com> I'm in a process of digging into Python, and one of the problems I'm having is whether I should spend any time at all learning TKinter or skip it and start with more advanced staff like wx or QT. I have no experience with GUI whatsoever, so anything will be a learning experience for me. The reason I've decided to post this question is that I see some contradictory information in different resources. In 'Programming Python', learning TKinter is recommended -- before you move to more advanced toolkits. The rationale is (i) it is built-in and since it is also shared by TCL and Perl, it is well-maintained and always in sync with the latest version of Python, (ii) it is fairly simple to learn, small learning curve, easier to grasp some concepts before moving to more comprehensive production quality toolkit such as QT. In some other resources TKinter is critisized as not well integrated at Python at all, so recommendation is 'not to waste your time and start learning GUI with either wx or QT'. My intent is *not* to become professional GUI developer, but simply to get a handle on it, so if I write some utilities, I can provide some nice GUI if required. Yet of course, since I'm learning something new, it would be nice to learn it 'right from the start'. So: should I spend some time or TKinter or simply skip it and start learning GUI with something like wx or QT? (my background: solid C, enough C++ to understand the OOP concepts, Perl, too much of it to my liking, BTW) TIA. From hans at zephyrfalcon.org Tue May 25 15:51:44 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 25 May 2004 15:51:44 -0400 Subject: Fwd: Python opening in NY Message-ID: <mtNsc.20176$zs2.7774@fe39.usenetserver.com> I got the following email from Darsh Mehta. I am unable to move to New York myself, but maybe someone else here will be interested. In that case, please contact this person. He says he can pay up to $35/hr. --- I was wondering if you are available and if you would be interested in a python/c++ consulting position in NY. Its a 8+month project with good chances of a possible extension. Please call me at my number below or reply back if you are interested. If you know of someone who might be interested then feel free to forward this email or let them call me. Thank you. Regards, Darsh. Darshan at stsworldwide.com Tel 1.678.254.1000 x 249 Fax 1.678.254.1035 Cell 763.360.0775 -- Hans Nowak (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From insert at spam.here Thu May 6 10:50:47 2004 From: insert at spam.here (Doug Holton) Date: Thu, 06 May 2004 09:50:47 -0500 Subject: the dreaded double fork In-Reply-To: <mailman.272.1083771384.25742.python-list@python.org> References: <mailman.272.1083771384.25742.python-list@python.org> Message-ID: <l8qdndL0GeBbzQfdRVn-uQ@comcast.com> John Hunter wrote: > I am using python to run an xml rpc daemon using SimpleXMLRPCServer. > Following a cookbook recipe, I am trying to do a double fork so that > when I exit the shell the daemon remains running. But it doesn't. > Here is how I start the script > > >>ssh somehost >>sudo python mydaemon start& See also http://www.noah.org/python/daemonize.py But another way to do it without needing nohup or daemonize is to double background it and redirect stdout and stderr: (python mydaemon start > /dev/null 2>&1 & ) & Then you can exit and it will still be running (check ps -A to see it). From hugo_mesquita at hotmail.com Tue May 4 14:37:38 2004 From: hugo_mesquita at hotmail.com (Fernando) Date: Tue, 04 May 2004 18:37:38 GMT Subject: python CGI scripting References: <mailman.231.1083650172.25742.python-list@python.org> Message-ID: <SpRlc.53966$hR1.53874@fe2.texas.rr.com> jai_uw wrote: > Hello, > > I am trying to do CGI scripting with Python, but I have a slight > constraint. I do not have the CGI module installed on my machine. Is > there anyway I can still do CGI scripting in Python without the CGI > module installed? > > I don't have root access to the linux machine I am on, and so I won't > be able to install the Python CGI module. All I need to do is access > the text box fields of an html form in a Python script. The CGI > module makes this really easy, as we can import CGI, but I was > wondering if anyone knows a way to do this without using the CGI > module. Any input would be greatly appreciated. > > Thanks, > > Jai Modi . From peter at engcorp.com Fri May 21 15:26:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 15:26:50 -0400 Subject: Documentation/Info on this sign In-Reply-To: <c8lhq8$g7m$07$1@news.t-online.com> References: <c8iims$24i$1@solaris.cc.vt.edu> <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> <40ACED36.5030706@hotmail.com> <c8lhq8$g7m$07$1@news.t-online.com> Message-ID: <VYedndUn_vtmyjPdRVn-tA@powergate.ca> Peter Otten wrote: > Bart Nessux wrote: >>Both functions produce the same results (33,000 files)... the problem: >>the filesystem has twice as many files (66,000) than the actual sums of >>these two counts when doing a virus scan or an adaware scan. To make >>matters more confusing... the IBM Tivoli backup software that I use >>confirms the Python counts when it does a backup. I don't know of a way >>to see what the OS has to say what it thinks is correct. Any ideas on >>how to do this? > > Maybe you have a symlink (how are they called in windows?) in the root > folder. The number of files would vary depending on whether the software > follows symlinks or not. That could explain the factor 2. While the NTFS does support symbolic link, it doesn't even appear to include a utility to create them, and most people, I suspect don't even know they exist. (I had to check with Google to even find this out.) There is a utility called "junction" which can be had from http://www.sysinternals.com/ntw2k/source/misc.shtml#junction perhaps among other places. Very unlikely the OP has used this... -Peter From spamfilter at metva.com Fri May 14 12:13:23 2004 From: spamfilter at metva.com (spamfilter at metva.com) Date: Fri May 14 12:13:23 2004 Subject: AUTOREPLY - rejected email 'Re: Your website' Message-ID: <200405140213.MAA02219@metva.com.au> The email referred to in the subject line has been rejected by the ingress filter at metva.com. This is usually because of unacceptable content types such as executable files, screensavers, zip files or the like. If you really need to send such attachments, please tar/rar/zoo them and try again. If you did not send this email it may be indicative of viral activity on your system and it may be worthwhile checking your system for recent compromise by malware. metva.com apologizes for any inconvenience our actions may have caused. From mwh at python.net Mon May 10 13:43:37 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 10 May 2004 17:43:37 GMT Subject: function causing core dump References: <c7o6al$i1j$1@online.de> Message-ID: <m3hduokwja.fsf@pc150.maths.bris.ac.uk> "Xaver Hinterhuber" <xaver_hinterhuber at web.de> writes: > Hello pythonistas, > > I build a function with the following code segment: > > codeObject = new.code( > 0, # argcount > 0, # nlocals > 0, # stacksize > 0, # flags > codeString, # code > (), # consts > (), # names > (), # varnames > 'content', # filename > 'content', # name > 3, # first line number > codeString # lnotab > ) > f = new.function(codeObject, dict, 'f') > f() > > Everything runs fine, until the function is called with f(). > When python tries to execute f(), the core dump happens. > I don't have any clue why python core dumps. > The codeString is nothing complex, its a one-liner. > Could you plz give me some tips what I have to do? Doesn't the documentation for the new module have warnings plastered all over it? Why are you using it? Cheers, mwh -- About the use of language: it is impossible to sharpen a pencil with a blunt axe. It is equally vain to try to do it with ten blunt axes instead. -- E.W.Dijkstra, 18th June 1975. Perl did not exist at the time. From jepler at unpythonic.net Mon May 31 22:58:30 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 31 May 2004 21:58:30 -0500 Subject: exceptions In-Reply-To: <c9gkdh$ibv$1@reader01.singnet.com.sg> References: <cth8yf8n77o.fsf@lcpxdf.wm.lc.ehu.es> <G-OdnbDM6oaZrybdRVn-gg@powergate.ca> <mailman.452.1086013863.6949.python-list@python.org> <40bb96e2$1@nntp0.pdx.net> <c9gkdh$ibv$1@reader01.singnet.com.sg> Message-ID: <20040601025830.GA2697@unpythonic.net> > According to Scott David Daniels <Scott.Daniels at Acm.Org>: > > See this older thread: > > <http://groups.google.com/groups?threadm=3edd6118%241%40nntp0.pdx.net> On Tue, Jun 01, 2004 at 12:59:29AM +0000, Ng Pheng Siong wrote: > (I notice the older thread was one year ago. Is this an annual topic? ;-) Perhaps the older thread had an exception, but now it's been re-started? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040531/7ca8cb2d/attachment.sig> From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sun May 9 05:37:07 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 9 May 2004 11:37:07 +0200 Subject: Python for Nokia Series 60 References: <jollinofrenoamano-D94CBF.10345409052004@individual.net> Message-ID: <c7ku53$5aa$1@news-reader1.wanadoo.fr> Hi ! If Python exist on Nokia, I buy a tomorrow of it ! But i had already read this announce, but I never found one implementation. I will thus read the answers with interest. @-salutations -- Michel Claveau From kylotan at hotmail.com Mon May 31 19:51:19 2004 From: kylotan at hotmail.com (Ben Sizer) Date: 31 May 2004 16:51:19 -0700 Subject: mod python confusion Message-ID: <c9ggdn$fie@odbk17.prod.google.com> David Fraser wrote: > Kylotan wrote: > > > > I read somewhere today that > > mod_python made Python as simple to use for web apps as PHP etc, but if > > this is any indication of the amount of code you need to simply redirect > > execution to separate places based on the URI, then I'd have to disagree > > with that! > > > Actually redirecting execution to separate places based on the URI is > fairly easy in mod_python, I suspect you may want to use something like > publisher mod_python.publisher is poorly documented (the 'explanation' in section 6.1.2.1 of the manual is perhaps the most confusing attempt to explain something in clear language that I've ever seen) and seems pretty idiosyncratic, expecting you to return the page rather than write it out piece by piece. In the absence of decent documentation I've tried to experiment with it but couldn't find a consistent way of getting it to call my pages, and often ended up with 404 errors in situations where the tutorial led me to believe it would call a function. Is there a more clear guide on how to use this? By the way, thanks for the 3.1.3 file. That seems to have installed fine now. -- Ben Sizer From ods at strana.ru Wed May 12 11:13:59 2004 From: ods at strana.ru (Denis S. Otkidach) Date: Wed, 12 May 2004 19:13:59 +0400 (MSD) Subject: max value in list In-Reply-To: <c7te26$8q1$1@ucsnew1.ncl.ac.uk> Message-ID: <Pine.LNX.4.44L.0405121913290.8773-100000@ods.pravda.rfn.ru> On Wed, 12 May 2004, C GIllespie wrote: CG> I have a few lists. What's the best way of finding the CG> maximum number of all CG> the lists. CG> CG> For example, CG> CG> [2,3,4],[1,2,3],[4,7] CG> CG> The max is 7. >>> lists = [2,3,4],[1,2,3],[4,7] >>> max([max(l) for l in lists]) 7 -- Denis S. Otkidach http://www.python.ru/ [ru] From newsgroups at jhrothjr.com Sun May 23 15:30:44 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 23 May 2004 15:30:44 -0400 Subject: Problem concerning pyparallel References: <c8qqp4$u1$01$1@news.t-online.com> Message-ID: <10b1uvt47t75c94@news.supernews.com> "Harald Schreiber" <Harald.Schreiber at t-online.de> wrote in message news:c8qqp4$u1$01$1 at news.t-online.com... > Hi, > When trying to install the pyparallel-software under Windows98SE I got an > errormessage about a missing cl.exe. > Can someone there out give me some explanations? I believe that's either the compiler or the linker. Do you have Visual Studio installed? Or else either Cygwin or MinGW? John Roth > Harald Schreiber From grante at visi.com Thu May 13 21:07:25 2004 From: grante at visi.com (Grant Edwards) Date: 14 May 2004 01:07:25 GMT Subject: struct doesn't handle NaN values? References: <mailman.538.1084489118.25742.python-list@python.org> Message-ID: <40a41bcc$0$8705$a18e6209@newsreader.visi.com> In article <mailman.538.1084489118.25742.python-list at python.org>, Tim Peters wrote: >> but it never specifies which FP representation is used when. > > The same as everything else: in native mode, whatever float > and double representation the platform uses is what struct > uses, just as in native mode struct uses whatever the platform > uses for chars, shorts, ints and longs. In standard mode, the > representation is forced to IEEE 754 float or double format. My question was which "native" and "standard" mode? There appear to be two different "modes": "byte order" and "size and alignment". Which of the two modes determines the floating point representation to be used? My interpretation of the doc was the latter: use native FP representation when it says "native" in the "size and alignment" column and use IEEE when it says "standard" in the "size and alignment" column. > But it's still the case that all behavior wrt NaNs, Infs, and > signed zeroes is an accident in standard mode. Indeed, it's > precisely *because* standard mode tries to force the > representation to a known format (and Python has no idea > whether the platform it's running on uses 754 format natively > or not) that these accidents occur. In order to provide robust translation between native and IEEE floating point formats, Python is going to have to know what the native format is. > C89 predates 754 adoption, and so offers no portable > facilities even for recognizing whether a thing is a NaN, Inf, > or signed 0. "Standard" C tricks like > > if (x != x) { /* then x is a NaN */ } > > don't actually work across platforms (although many with > limited x-platform experience believe they do). Recognizing and generating IEEE NaNs, infinities, 0's and denormals is easy enough. Recognizing and generating native infinities, 0's and denormals would require some compile-time configuration, but that's not difficult either. All the C compilers I've used in the past dozen or two years provide pre-processor symbols to tell you want architecture you're compiling for. If one doesn't want to rely on that, compiling and running some simple test programs a-la autoconf should be able to determine pretty reliably if the host is using IEEE representation or not. Since the vast majority of hosts out there use IEEE representation, and the C compiler can tell you that at compile-tiem, I see no reason why struct can't be made to work better. IIRC, the other FP representations I've worked with (TI and DEC) were both minor variations on IEEE 754 and both provided NaNs and infinities. Why shouldn't we expect struct to convert an IEEE NaN into a native NaN (and the reverse)? Are there architectures that support multiple floating point representations that can only be determined at run-time? >> I would guess that FP native vs. standard representation >> matches the native vs. standard state of "size and alignment". > > I'm not sure what that sentence said, but bet it's right <wink>. I tried to state it more clearly above. -- Grant Edwards grante Yow! I have a TINY BOWL in at my HEAD visi.com From donn at u.washington.edu Thu May 6 15:05:25 2004 From: donn at u.washington.edu (Donn Cave) Date: Thu, 06 May 2004 12:05:25 -0700 Subject: Scope rule pecularities References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> Message-ID: <donn-7C0E85.12052506052004@nntp4.u.washington.edu> In article <slrnc9kkdo.5fa.apardon at trout.vub.ac.be>, Antoon Pardon <apardon at forel.vub.ac.be> wrote: ... > Beside you missed the point. I don't need solutions, I know the > work arounds to make it work. The point is that although a += b > is supposed to be syntactic sugar for a.__iadd__(b), you need > a global (and even that won't help if you have nested functions > and the a is on an intermediate level) to make the first work > but not for the second. += is a bit of a wart. The only value in it is that you can execute this read-and-modify sequence with a single access in some cases where accesses matter because of side effects. (Single access higher up in an expression - e.g., if we have a[0][0] += 1, you skip an a[0].) If that seems like a silly reason to take on this abominable kludge, I'm probably not explaining it well - wasn't my idea. Donn Cave, donn at u.washington.edu From hadi at nojunk.com.au Fri May 14 10:12:31 2004 From: hadi at nojunk.com.au (Hadi) Date: Sat, 15 May 2004 00:12:31 +1000 Subject: beginner's question References: <c82d51$78s$1@lust.ihug.co.nz> <Xs3pc.34385$dr1.943764@news20.bellglobal.com> <Ny3pc.34409$dr1.944419@news20.bellglobal.com> Message-ID: <c82jko$ake$1@lust.ihug.co.nz> Sean, I am grateful for your help. Sorry for the previous reply. God bless you. Thank you. regards, hadi "Sean Ross" <sross at connectmail.carleton.ca> wrote in message news:Ny3pc.34409$dr1.944419 at news20.bellglobal.com... > > "Sean Ross" <sross at connectmail.carleton.ca> wrote in message > news:Xs3pc.34385$dr1.943764 at news20.bellglobal.com... > > dst.write(str(w in lexicon)) # writes 'True, ' or 'False, ' > > The above code will run the True/False output together, e.g. > "TrueTrueFalseTrueFalse". > I doubt that's what you want. Perhaps this, instead: > > dst.write("%s "%(w in lexicon)) > > That would write "True True False True False". > > Sean > > From adwser at hotmail.com Mon May 3 04:40:39 2004 From: adwser at hotmail.com (jtd) Date: 3 May 2004 01:40:39 -0700 Subject: Efficient string concatenation methods References: <b3a34c4c.0405011643.70c163c3@posting.google.com> <5d83790c.0405021752.2b82345e@posting.google.com> Message-ID: <c57c103.0405030040.3eb7d1a3@posting.google.com> python at rcn.com (Raymond Hettinger) wrote in message news:<5d83790c.0405021752.2b82345e at posting.google.com>... > API. The real issue is how much space to allocate for the final > string. When iterating, as you do, there is little forewarning about > how many more entries to expect or the length of each. If too little > space is allocated, then room for a larger string needs to be created > and the previous result recopied (giving the O(n**2) behavior you're > trying to get rid of). Is there any particular reason why the space allocated does not increase *exponentially*, say with a factor of 1.5 or 2? That's how the string class is implemented in C++, IIRC. That'd give you amortized linear rather than quadratic time. From nothin at forgetit.com Wed May 12 01:24:44 2004 From: nothin at forgetit.com (sj) Date: Wed, 12 May 2004 05:24:44 GMT Subject: How to batch download files from web page? Message-ID: <wyioc.26539$DI7.25553@newssvr22.news.prodigy.com> I wish to download hundreds of files from the University of Iowa sound archive. Doing it manually would be a daunting task especially since the files are each a few mega bytes long. Is there a standard way of using Python for such a task? I have a fair amount of programming experiance but very little of it relates to networks. For those who are intrested the University of Iowa's sound archive may be found at http://theremin.music.uiowa.edu/MIS.html Thanks in advance Steven Jones From andrew-pythonlist at puzzling.org Sat May 15 01:06:13 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 15 May 2004 15:06:13 +1000 Subject: Stackless python and microthreads In-Reply-To: <95aa1afa.0405142053.76ae0818@posting.google.com> References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <mailman.12.1084550223.4157.python-list@python.org> <95aa1afa.0405142053.76ae0818@posting.google.com> Message-ID: <20040515050613.GB4397@frobozz> On Fri, May 14, 2004 at 09:53:03PM -0700, Michele Simionato wrote: [...] > > On a different note, I could notice that giving so much power to > metaprogrammers may have unfortunate results. For instance, we already > have three different kind of interfaces in three different frameworks > (Zope, Twisted, Peak) whereas there should be only one obvious way. FWIW, Twisted will be using Zope 3's interfaces framework soon, which will leave just Zope and PEAK. -Andrew. From chuck.amadi at ntlworld.com Thu May 27 20:56:36 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Fri, 28 May 2004 01:56:36 +0100 Subject: Example of a email processing to a file Message-ID: <40B68E44.4050909@ntlworld.com> Hi sorry to try and get someone to do my job but im at logger heads at the moment . I have been assigned a duty to abstract from a mail acoount (/var/spool/mail/Usersurvey) The email messages are encapsulated in xml I want to parse the data into a database. I have been programming with UnixMailbox Module and been able to view the contents but how do I get all the messages into one file.I know the database part just this extraction bit. I fsomeone has a snippet or example would be great as I got a tight deadline . Cheers all From s.brennan at cox.net Fri May 14 14:34:54 2004 From: s.brennan at cox.net (Shane) Date: Fri, 14 May 2004 18:34:54 GMT Subject: Python and Windows.Forms In-Reply-To: <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> References: <mailman.350.1074089447.12720.python-list@python.org> <87n08qrpcv.fsf@pobox.com> <sTAoc.67180$sK3.3272@nwrddc03.gnilink.net> <PIydnS3kI_d-Qj7dRVn_iw@comcast.com> <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> Message-ID: <ij8pc.127698$G_.21879@nwrddc02.gnilink.net> Tim Roberts wrote: > "Larry Bates" <lbates at swamisoft.com> wrote: > >>You can access all the Windows common dialogs (forms?) >>Python by using Win32 extensions. > > > His specific question was about Windows.Forms, which is a .NET class in the > Common Language Runtime. Hooking that is not as easy as popping into the > common dialogs. Sorry Tim, I first learned programming with C# so when I said Windows.Forms I meant any generic Windows form, and especially common dialogs. My mistake! I'm glad I made though since Marijan Tadin pointed out that python .NET link that I wasn't aware of (see his reply). Thanks again... Shane Brennan From SeeBelow at SeeBelow.Nut Tue May 18 11:30:09 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 18 May 2004 15:30:09 GMT Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> Message-ID: <40AA2C16.C1245362@shaw.ca> Leif K-Brooks wrote: > > Svein Ove Aas wrote: > > Is anyone working on a python-to-native compiler? > > I'd be interested in taking a look. > > What are you trying to achieve? > > If it's faster code execution, the primary slowdown with a very > high-level language like Python is caused by high-level data structures > (introspection, everything being an object, etc.), not the code itself. > A native compiler would still have to use high-level data structures to > work with all Python code, so the speed increase wouldn't be very much. Yes, fast execution. I have been using C. In my applications there is a population of "chromosomes" which are arrays of floats, about 2 to 5 k in length. Then there are subroutines which operate on a chromosome using pointers. For example, the "crossover" routine uses two pointers to swap portions of two chromosomes. My software sometimes runs for hours, perform many millions of operations like these. Clearly, speed of execution is of dramatic importance. A related problem is that it seems to be a big deal to call C routines from Python. I have not actually tried it, because when I read about how its done I was not able to understand it. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From mailadmin at persgroep.be Sun May 2 16:22:29 2004 From: mailadmin at persgroep.be (mailadmin at persgroep.be) Date: Sun, 02 May 2004 22:22:29 +0200 Subject: Virus Alert Message-ID: <E1BKNTp-0007XJ-00@mail3.persgroep.be> De mail die werd afgeleverd op de mailservers van De Persgroep bevatte een virus. Voor meer info raadpleeg http://blacklist.persgroep.be/virusalert.htm From E.A.M.Huijbers at REMOVEstudent.tue.nl Fri May 21 14:10:37 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Fri, 21 May 2004 20:10:37 +0200 Subject: Jabber in Twisted Message-ID: <c8lgid$qj5$1@news.tue.nl> Does anybody have experience in writing Jabber clients with Twisted? I came across a simple sample[0], and tried to build out from it, but for some reason it's barely working. When I run the application in the attached script, the logon goes fine, and I can receive messages sent to the account, but it never seems to receive subscription requests. When I ran it on an account that already had some items on the contact list, I did receive <presence> messages to indcate that a user changed status, but I don't receive <presence type="subscribe"> messages... Ultimately, I tacked a "/*" handler on to the code to see if I was receiving any packets at all, but the only thing that seems to trigger anything are messages. This is very frustrating for me. Is it a problem with the code, or am I missing something in the Jabber protocol? Any help would be greatly appreciated. - Rico P.S: Please don't mind the code, I know it's a bit (a lot) hackish right now, but my first step is to get it running. I'll make it beautiful afterwards ;). [0] http://randomthoughts.vandorp.ca/WK/blog/706?t=item ##### code starts here ##### from twisted.protocols.jabber import client, jid from twisted.protocols import xmlstream from twisted.xish import domish from twisted.internet import reactor name = 'Foo' server='bar.com' resource = 'PythonBot' password = 'foobar' me = '%s@%s/%s' % (name, server, resource) thexmlstream = None tryandregister = 1 def initOnline(xmlstream): global factory print 'Initializing...' xmlstream.addObserver('/message', gotMessage) xmlstream.addObserver('/presence', gotPresence) xmlstream.addObserver('/iq', gotIq) xmlstream.addObserver('/*', gotSomething) def authd(xmlstream): thexmlstream = xmlstream print "we've authd!" print repr(xmlstream) #need to send presence so clients know we're #actually online presence = domish.Element(('jabber:client', 'presence')) presence.addElement('status').addContent('Online') xmlstream.send(presence) initOnline(xmlstream) def gotMessage(el): print 'Got message: %s' % str(el.attributes) def gotSomething(el): print 'Got something: %s -> %s' % (el.name, str(el.attributes)) def gotIq(el): print 'Got IQ: %s' % str(el.attributes) def gotPresence(el): print 'We got a presence message!' print repr(el.attributes) try: t = el.attributes['type'] if t == 'subscribe': # Grant every subscription request xmlstream.send(domish.Element(('jabber:client', 'presence'), attribs={ 'from': me, 'to':el.attributes['from'], 'type':'subscribed' })) except KeyError: # Big fat ignore pass def invaliduserEvent(xmlstream): print 'Invalid user!' global tryandregister if tryandregister: tryandregister = 0 print 'Attempting to register...' global factory factory.authenticator.registerAccount(name, password) else: global reactor reactor.stop() def authfailedEvent(xmlstream): global reactor print 'Auth failed!' reactor.stop() def registerfailedEvent(xmlstream): global reactor print 'Register failed!' reactor.stop() myJid = jid.JID(me) secret = password factory = client.basicClientFactory(myJid,secret) # Register authentication callbacks factory.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, authd) factory.addBootstrap(client.BasicAuthenticator.INVALID_USER_EVENT, invaliduserEvent) factory.addBootstrap(client.BasicAuthenticator.AUTH_FAILED_EVENT, authfailedEvent) factory.addBootstrap(client.BasicAuthenticator.REGISTER_FAILED_EVENT, registerfailedEvent) # Go! reactor.connectTCP(server, 5222, factory) reactor.run() From sorry at but.no.spam Mon May 17 15:02:58 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Mon, 17 May 2004 22:02:58 +0300 Subject: This program makes Python segfault - no other does References: <pan.2004.05.17.10.17.01.120134@but.no.spam> <mailman.11.1084805883.6949.python-list@python.org> <pan.2004.05.17.16.42.48.115195@but.no.spam> <m33c5zgcrs.fsf@pc150.maths.bris.ac.uk> Message-ID: <pan.2004.05.17.19.02.55.248340@but.no.spam> On Mon, 17 May 2004 17:54:32 +0000, Michael Hudson wrote: > Juho Saarikko <sorry at but.no.spam> writes: >> #0 0x400c4c1b in free () from /lib/libc.so.6 >> #1 0x400c4aa3 in free () from /lib/libc.so.6 >> #2 0x0807ff2e in PyObject_Free (p=0x81d7240) at Objects/obmalloc.c:774 >> #3 0x0807f5a6 in PyMem_Free (p=0x81d7240) at Objects/object.c:2111 >> #4 0x4023a2d4 in unQuoteBytea (sin=0x81dd2ec ">nemo wrote:") at libpqmodule.c:417 > > Oh look, this is clearly inside the libpq extension module! What > evidence do you have for a bug in Python itself? The function unQuoteBytea allocates memory with PyMem_Malloc, and frees it with PyMem_Free. The segfault happens at freeing the memory (as the backtrace shows). It seems to me that if Python's memory management routines fail to free an object they've allocated, it must be a bug in Python. That or some other bug corrupts memory structures, in which case it's almost impossible to track down. At this point I'm considering either switching to a different database plugin, or to Java. I tried the new Python version (3.3.4c1) and got the exact same behaviour. Aarrgghh. Here, I'll attach the unQuoteBytea function, it's a short one. Maybe you can find some problem in it I couldn't: PyObject *unQuoteBytea(char *sin) { int i, j, slen, byte; char *sout; PyObject *result; slen = strlen(sin); sout = (char *)PyMem_Malloc(slen); if (sout == (char *)NULL) return PyErr_NoMemory(); for (i = j = 0; i < slen;) { switch (sin[i]) { case '\\': i++; if (sin[i] == '\\') sout[j++] = sin[i++]; else { if ((!isdigit(sin[i])) || (!isdigit(sin[i+1])) || (!isdigit(sin[i+2]))) goto unquote_error; byte = VAL(sin[i++]); byte = (byte << 3) + VAL(sin[i++]); sout[j++] = (byte << 3) + VAL(sin[i++]); } break; default: sout[j++] = sin[i++]; } } sout[j] = (char)0; result = Py_BuildValue("s#", sout, j); PyMem_Free(sout); return result; unquote_error: PyMem_Free(sout); PyErr_SetString(PyExc_ValueError, "Bad input string for type bytea"); return (PyObject *)NULL; } From __peter__ at web.de Thu May 13 15:38:29 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 May 2004 21:38:29 +0200 Subject: Generators: section 9.10 of the python tutorial References: <mailman.527.1084471592.25742.python-list@python.org> Message-ID: <c80irl$veo$03$1@news.t-online.com> David Stockwell wrote: > Section 9.10 of the tutorial discusses the yield keyword. When I tried > using it I get the following SyntaxError. > > What does this error mean? Does it mean we can't use yield in our code? You need the line from __future__ import generators as the first statement in your script (or you can update from Python 2.2.x to 2.3.x). > Is yield a form of a 'return' ?? In the context of a for loop, you can indeed think of yield as a kind of return that stops the execution of the function (reverse() in your example) but saves its internal state, and on the next iteration resumes execution at the point where it stopped the last time - until it encounters the next yield. When the function aka 'generater' terminates, the for loop ends. (The underlying mechanism is a bit more general, but as generators are used with for loops in the great majority of cases you shouldn't care until you are comfortable with the common case as well as classes and exceptions). Peter From chad at sabinasp.com Tue May 18 21:46:02 2004 From: chad at sabinasp.com (Chad Thompson) Date: Wed, 19 May 2004 01:46:02 GMT Subject: alternatives to making blocks like { } or other ?? References: <c8do0u$9fb$1@news.atman.pl> Message-ID: <u%yqc.15650627$Id.2594622@news.easynews.com> "CYBER" <usenet at zly_adres.com> wrote in message news:c8do0u$9fb$1 at news.atman.pl... > Hello > > Is there any other way under python to create blocks ?? > > instead of > > def sth(x): > return x > > > > could i use something else like > > def sth(x): > { > return x > } > > > ??? http://www.python.org/doc/Humor.html#parsing From alloydflanagan at comcast.net Fri May 14 10:17:36 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 14 May 2004 07:17:36 -0700 Subject: PEP: import version References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> <mailman.517.1084462055.25742.python-list@python.org> <c80bsk$q8m$1@news.nems.noaa.gov> <mailman.532.1084478808.25742.python-list@python.org> <c80v79$h2o$1@news.nems.noaa.gov> Message-ID: <e838aa6e.0405140617.6b9a2f4f@posting.google.com> Christopher Barker <Chris.Barker at noaa.gov> wrote in message news:<c80v79$h2o$1 at news.nems.noaa.gov>... > differences. A big one is that you could never use more than one version > of wxPython in a single program, but you might very well be able to use > multiple versions of other packages in the same program. So, while for Using multiple versions in one program sounds like a recipe for disaster to me, even with some sort of language support. Also, we shouldn't make the normal single-version case more complex or less efficient to support a case that should be extremely rare. From newsgroups at jhrothjr.com Wed May 12 18:04:10 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 12 May 2004 18:04:10 -0400 Subject: if Request("something") == None: doesn't work References: <AVsoc.47661$FI7.6868@newssvr29.news.prodigy.com> Message-ID: <10a57riii39q7d0@news.supernews.com> "Sam Sungshik Kong" <ssk at chol.nospam.net> wrote in message news:AVsoc.47661$FI7.6868 at newssvr29.news.prodigy.com... > Hello! > > I use Python for ASP programming. > I found something weird. > > Response.Write(Request("something")) > It draws "None" when there's no value for something. > Actually I expect "" instead of "None". > > So I changed it like > if Request("something") == None: > Response.Write("") > else: > Response.Write(Request("something")) > > Strangely, the result of comparison is False. > > if str(Request("something")) == "None": > works! > > Also, > if len(Request("something")) == 0: > works! > > What's wrong? Darned if I know. However, there are two comments. 1. The standard way to check for None is to use the "is" operator, not the "==" operator. You might try that. The equals test ought to work, though. 2. However, the even easier way to do it is not to do a check at all, but simply rely on the fact that both None and the null string act like False in an if statement. In other words, just remove the "== None" and see what happens. John Roth > > ssk > > From peter at engcorp.com Fri May 14 16:55:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 16:55:43 -0400 Subject: make faster Richards benchmark In-Reply-To: <9c2d8268.0405140624.f7a167e@posting.google.com> References: <mailman.540.1084499664.25742.python-list@python.org> <osGdnfaC2oTOtjndRVn-tw@powergate.ca> <9c2d8268.0405140624.f7a167e@posting.google.com> Message-ID: <iOidnRHzf-LPrzjdRVn-uw@powergate.ca> Meno wrote: > On AMD XP 2500 and 512 MB RAM: gone from 855430 ticks to 503353 ticks > with psyco. That is I think 41% less time. > > Peter, note that getting it to run twice as fast "only" means 50% less > time. Maybe that is what you should compare with your 38%... Thanks for the comparison. When I say 38% speedup, I mean a reduction in time of 27%, or I mean it now runs at 73% of the time it used to. We _are_ using the same meaning for "speedup" here... My raw numbers are 862806 ticks beforehand, which corresponds reasonably well with your value. After inserting the two lines "import psyco" and "psyco.full()" as the very first lines in the file, I get 627476 ticks. Am I putting it in the wrong place? (Also tried it at the end just before the call to main() with no difference.) -Peter From opengeometry at yahoo.ca Sat May 29 14:56:53 2004 From: opengeometry at yahoo.ca (William Park) Date: 29 May 2004 18:56:53 GMT Subject: UK Social research job to suit Excel programmer (not necessarily VBA) References: <c9a3ln$t44$1@news8.svr.pol.co.uk> <40B8991F.4010207@engcorp.com> <c9a9k4$ffr$1@news5.svr.pol.co.uk> Message-ID: <2hs4ndFgjvpgU1@uni-berlin.de> Duncan Smith <buzzard at urubu.freeserve.co.uk> wrote: > > "Peter Hansen" <peter at engcorp.com> wrote in message > news:40B8991F.4010207 at engcorp.com... > > Duncan Smith wrote: > > > > > http://www.man.ac.uk/news/vacancies/research.html#581 > > > > Sorry, but what's the connection to Python? > > There is (I am told) a significant amount of work automating Excel. > Unfortunately this isn't clear from the job description (I didn't > write it). I know from experience that this can be achieved admirably > using Python (and Mark Hammond's extensions). Personally I would like > to see the work done in Python, but that depends on who applies and > whether those who make the decisions can be convinced that it's an > appropriate language (well, moreso than VBA). It's certainly not a > full-time programming job (due to the social science / modelling > component), but it does need someone who can write good maintainable > code. Bash, Awk, Python are all good tools, and Math/Engineering would be good background to have. But, this is job for local undergraduate students, not outside programmer or consultants. :-) -- William Park, Open Geometry Consulting, <opengeometry at yahoo.ca> Slackware -- because I can type. From pit.grinja at gmx.de Sat May 1 11:13:20 2004 From: pit.grinja at gmx.de (Piet) Date: 1 May 2004 08:13:20 -0700 Subject: Size of wxDialog restricted to screen size? Message-ID: <39cbe663.0405010713.66a5ce34@posting.google.com> Hello there. I have written a python app that reads data from xml files and displays them in a wxDialog window. For large Xml files, this will lead to a wxDialog which is wider than the screen size. It turned out than in this case, the information outside the screen are not displayed at all. Dragging the dialog window so that the parts of the dialog which outside screen limits will become visible doesn?t help. Is this a general problem or is it possible to dynamically create dialogs which are larger than the scree? Many thanks for your advice Peter From peterm at resmed.com.au Sun May 9 18:28:57 2004 From: peterm at resmed.com.au (Peter Milliken) Date: Mon, 10 May 2004 08:28:57 +1000 Subject: emacs alphabetize methods References: <mailman.377.1084133181.25742.python-list@python.org> Message-ID: <Kgync.737$UC4.26334@nnrp1.ozemail.com.au> Not that I am aware of - but this wouldn't be an impossible job to tackle yourself and provide the results for benefit of the rest of us who uses Emacs :-) My suggestion for how to do this (off the top of my head :-)) is to write a support (Python) program to call from your emacs using Pymacs (http://pymacs.progiciels-bpi.ca/manual/The--Pymacs--buffer.html). Then you could probably locate the points where your methods start and finish using services available from the Python Language Services section in the Python Library Reference (Chapter 18), re-arrange the source code and then re-insert it back into your Python buffer. Probably not a very big job at all - if you don't do it then I might well do it myself one day (but not in the foreseeable future due to other work loads :-)). Regards, Peter "John Hunter" <jdhunter at ace.bsd.uchicago.edu> wrote in message news:mailman.377.1084133181.25742.python-list at python.org... > > Using emacs python-mode with a class > > class C: > def method1(self): > pass > > def anothermethod(self): > pass > > def method2(self): > pass > > is there any way to select all the methods and have emacs order them > alphabetically? If not, is there a good too to do so? > > Thanks, > John Hunter > From apardon at forel.vub.ac.be Fri May 14 11:11:26 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 May 2004 15:11:26 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <mmo7a0d17d0oigka5icevb9qj3ogudtvai@4ax.com> <slrnca9etd.1i9.apardon@trout.vub.ac.be> <2ek9a0lteqvdibptihek5eeg6mqm959gkb@4ax.com> Message-ID: <slrnca9ocv.1i9.apardon@trout.vub.ac.be> Op 2004-05-14, David MacQuigg schreef <dmq at gain.com>: > On 14 May 2004 12:29:32 GMT, Antoon Pardon <apardon at forel.vub.ac.be> > wrote: >>Op 2004-05-13, David MacQuigg schreef <dmq at gain.com>: >>> On Thu, 13 May 2004 10:56:58 -0400, "Terry Reedy" <tjreedy at udel.edu> >>> wrote: >>>>"Antoon Pardon" <apardon at forel.vub.ac.be> wrote in message >>>>news:slrnca6d58.1i9.apardon at trout.vub.ac.be... >>>>> One could argue that all forms of methods and functions are unified. >>>>> It is just that python does some magic so that the method you >>>>> access from an object is not the actual function but the curried >>>>> function with the object. >>>> >>>>My view is similar: in Python, a method is a dressed up (wrapped) function. >>>>'Unification of methods and functions' reads to me like 'unification of >>>>dressed-up bodies and naked bodies'. What would that mean? >>> >>> By unification, I mean making the calling sequence identical for all >>> methods and functions. >> >>It already is. It is just that the function you have defined within >>the class, is not the function you call through the object. > > In the current sytnax, we need a special "staticmethod" statement to > define a method we can call without an instance. Not realy, this would work just as well: def __func(a,b): ... class C: def __init__(self): self.func == __func Why one wouldn't just write func and use it, instead of having a staticmethod is beyond me, but it you want it be my guest. > In the proposed > syntax, there is no distinction between the different method styles, > and no need for special syntax. A "staticmethod" has the same > arguments as normal method, and the same as an ordinary function. > This is what I mean by having the same "calling sequence". > > For an example of how unification simplifies the presentation of OOP, > see the first 8 pages of > http://ece.arizona.edu/~edatools/Python/Prototypes.doc > >>> The choice of how to identify instance variables is a minor issue. I >>> think it is actually better not to *hide* the instance variables, but >>> to *highlight* them. Ruby uses $var for instance variables. Prothon >>> uses a leading dot, which is quite visible in most code editors. >>> >>> The real issue is not self.var vs .var It is the complexity resulting >>> from having different calling sequences. >> >>There really aren't different calling sequences, just to different >>related function. > > In the Animals.py example at http://ece.arizona.edu/~edatools/Python/ > there is a method Mammal.show(). Normally, the calling sequence is > Mammal.show(cat1) > where cat1 is just an instance needed to satisfy the requirement for a > special first argument. The method does not *use* cat1, and in > general, there may not be an instance of every class available. If we > convert Mammal.show to a static method, we don't need the special > first argument. The calling sequence is then > Mammal.show() > > Do you understand what I mean by "different calling sequences"? And do you understand it when I say, that it is not different calling sequences but different functions. Two functions that use the same name, are related in functionaly but are different. Did you understand what happened with the "two" object? > ><snip> > >>Having __self__ being >>a global variable is disaster waiting to happen. What if a method >>calls another method, what if you use threads? > > If a method calls another method, the same thing happens in the > proposed syntax as in current Python. Normally, the current instance > doesn't change. In current python no global variables are set by a call to a method. > Python 2>>> Mammal.talk(self) > Python 3>>> Mammal.talk() > If you want to *over-ride* the normal behavior and *force* a specific > binding: > Python 2>>> Mammal.talk(cat2) > Python 3>>> __self__ = cat2; Mammal.talk() > I don't know why anyone would ever want to do this within a method, > but it is possible. > > I don't understand the problem with threads. Perhaps an example would > help. You talk about a global variable that is being set, What if two threads quasi simultaneously call a method. To what value is this global __self__ set. -- Antoon Pardon From j_mckitrick at bigfoot.com Sat May 8 15:40:52 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 8 May 2004 12:40:52 -0700 Subject: What I don't like about wxPython Message-ID: <ec6dce8b.0405081140.16b8143d@posting.google.com> Just thought I'd play devil's advocate... I tried wxPython briefly, and it had some nice features. It has a huge list of dependencies. I don't like the fonts (but I'd love to know how to get fixed fonts, or at least anything that looks better on a small laptop screen. TkInter seems much easier to use... less effort to do things. jonathon From grey at despair.dmiyu.org Sat May 29 15:56:00 2004 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sat, 29 May 2004 19:56:00 GMT Subject: JMS-like Messaging Service for Python? References: <9405c70f.0405290650.8e5ad88@posting.google.com> Message-ID: <slrncbhqmh.2th.grey@dmiyu.org> On 2004-05-29, Sarah Wang <sarah_wang23 at hotmail.com> wrote: > Does python have JMS-like messaging service? (open-source preferred) > or any kind of message queue server? Anyone else sitting here thinking, "Whoa, JMS' postings to the net are done by a program and not by him!?" JMS being the writer/creator of Babylon-5. I know, I know, it means something else but that's what first came to mind. :P -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From cweimann at k12hq.com Sat May 15 20:13:40 2004 From: cweimann at k12hq.com (Christopher Weimann) Date: Sat, 15 May 2004 20:13:40 -0400 Subject: Python vs. VBScript vs. JavaScript in context of Windows Scripting Host? In-Reply-To: <051601c43aaf$07874590$210110ac@jsbwxp3> References: <051601c43aaf$07874590$210110ac@jsbwxp3> Message-ID: <20040516001340.GA17343@smtp.k12us.com> On 05/15/2004-12:01PM, John Benson wrote: > > * no record types, just numerically-indexed arrays, so record handling is > kludgy Scripting.Dictionary http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/jsobjDictionary.asp A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array. From notarangelotonio at tiscali.it Thu May 6 17:25:56 2004 From: notarangelotonio at tiscali.it (Tonio) Date: Thu, 06 May 2004 21:25:56 GMT Subject: Embedded Python Tutorials References: <de5dd424.0405021302.38db896e@posting.google.com> Message-ID: <E3ymc.41547$Qc.1623768@twister1.libero.it> "Arkon" <arkon at ragestorm.net> ha scritto nel messaggio news:de5dd424.0405021302.38db896e at posting.google.com... > Hello people, > what's up? > > I'm not sure if this is the right place for my post... > > I wrote two tutorials while ago explaining thoroughly, in my opinion > at least, how to embed Python in C applications, well the basics and > some more. > > The reason I wrote them was because the lack of info about embedding > Python in C applications, so I explored the subject and gathered info > all over the Internet... > > First part: http://www.ragestorm.net/tutorial?id=21 > Second part: http://www.ragestorm.net/tutorial?id=25 > > That's it, > I hope it can help you somehow. > > I will be glad to receive any comments... > Thanks, > Arkon > http://ragestorm.net/ > Thanks Arkon, i'm a italian student and i need your tutorial. If you have a example, can you send me in my email? Thanks. From irmen at -nospam-remove-this-xs4all.nl Mon May 10 16:50:29 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 10 May 2004 22:50:29 +0200 Subject: ANN: Pyro 3.4 beta (remote objects) Message-ID: <409feb15$0$61616$e4fe514c@news.xs4all.nl> After 9 months since the previous stable release (3.3), finally it's time to announce the beta release of the next Pyro version! You can get Pyro 3.4 beta via http://pyro.sourceforge.net, then go to the SF project homepage download area. Pyro 3.4 will mainly be a "polished and tweaked" version. Not many new features are added, but many things have been improved. Please download it, and test it, and let me know what you think. Pyro 3.4 final will be released within a week or two. Have fun! --Irmen de Jong ---> What is Pyro? Pyro is an acronym for PYthon Remote Objects. Pyro is an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. It is extremely easy to implement a distributed system with Pyro, because all network communication code is abstracted and hidden from your application. You just get a remote Python object and invoke methods on the object on the other machine. Pyro offers you a Name Server, an Event Service, mobile objects, remote exceptions, dynamic proxies, remote attribute access, automatic reconnection, a very good and detailed manual, and many examples to get you started right away. From __peter__ at web.de Tue May 11 02:00:21 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 May 2004 08:00:21 +0200 Subject: How do you register cleanup code to be run after script execution? References: <20040508090936.21319.00000994@mb-m04.aol.com> <c7n9md$kcr$00$1@news.t-online.com> <mailman.411.1084225465.25742.python-list@python.org> Message-ID: <c7pq5l$mu0$02$1@news.t-online.com> pxlpluker wrote: > why not use > try: > code > finally: > cleanup code Because cleanup code will run immediately after code (regardless of an exception that might occur in code) whereas atexit.register(cleanupCode) will trigger the cleanupCode() function when the script terminates. You can think of atexit as try: whole script finally: for f in registeredFunctions: f() You could implement this manually as you have suggested, but then you'd need to know what cleanup code is necessary for every module you imported. If you have modules needing cleanup that aren't always imported, you'd even have to check for these. Putting atexit.register(cleanupForModule) into every module needing cleanup doesn't affect its public interface and thus simplifies client code. Peter From asdf at asdf.com Fri May 7 17:04:59 2004 From: asdf at asdf.com (asdf sdf) Date: Fri, 07 May 2004 21:04:59 GMT Subject: Newbie : Greek letters In-Reply-To: <533d6c6fafbf3d9231eb53099cf64982@news.teranews.com> References: <c7elnr$jjs$1@news.Stanford.EDU> <8KDmc.45741$Sf4.40969@newssvr29.news.prodigy.com> <533d6c6fafbf3d9231eb53099cf64982@news.teranews.com> Message-ID: <%RSmc.45968$6_1.13304@newssvr29.news.prodigy.com> Christopher Culver wrote: > On Fri, 07 May 2004 03:52:36 +0000, asdf sdf wrote: > >>Oh Kyu Yoon wrote: >> >>>Is there an easy way to include greek letter symbols in TextCtrl of >>>wxPython? >>> >>> >> >>this is only a idea. no experience with it myself. Try using SetFont >>to get Symbol font. Symbol font is available on WinPCs. Couldn't say >>about any other platforms though. > > > That is a bad idea. Not only does it break cross-platform compatibility > (the goal of wxWindows) by using a proprietary font, it totally ignores > Python's excellent Unicode support. Greek has it's own block in Unicode, > you just have to create the characters from there. Using special fonts to > overcome character sets is sooooo 1998. > > Christopher Culver well, i'm edified. how about a code example? isn't there some issue about whether a given wxpython build has unicode support? how do you tell? how do you add it if you don't have it? if i may paraphrase the OP's question... "can i do greek letters in python?". if i may paraphrase your helpful response..."yes". cool 'tude though. From daniel at dittmar.net Thu May 6 14:57:35 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Thu, 06 May 2004 20:57:35 +0200 Subject: Windows scripting In-Reply-To: <35c88c68.0405061051.1be719ba@posting.google.com> References: <35c88c68.0405061051.1be719ba@posting.google.com> Message-ID: <c7e1rs$98h$1@news.eusc.inter.net> Scott wrote: > Can I use Python to automate an arbitrary program's execution? For > example, if I have an application like Firefox, could I use Python to > say "Move mouse to position x, click right mouse button here, etc.."? > What is involved in this process? Thanks, see http://users.swing.be/wintclsend/windpysend/index.html, though it's shareware. Daniel From jlearman at cisco.com Thu May 20 17:25:45 2004 From: jlearman at cisco.com (Jeff Learman) Date: Thu, 20 May 2004 17:25:45 -0400 Subject: shell script stdout to python string? In-Reply-To: <40ad0844$0$15829$39cecf19@news.twtelecom.net> References: <1085078933.436553@sj-nntpcache-3> <40ad0844$0$15829$39cecf19@news.twtelecom.net> Message-ID: <1085088194.895189@sj-nntpcache-5> Thanks! Just what I was looking for ... don't know why I didn't see it in the docs. Rick L. Ratzel wrote: > > Check out: > > http://www.python.org/doc/current/lib/module-commands.html > > It's Unix-specific, but I guess you did say "Unix command"... > > > -Rick Ratzel > > > Jeff Learman wrote: > >> >> Hi -- sorry for not searching first, but I get an NNTP error from >> netscape (a known bug, still looking for workaround). >> >> Inside a python script, I want to execute a UNIX command and >> send the output to a Python string, returning the shell return >> code value as an integer or exception. >> >> I'm sure I could write a function using pipes and whatnot, but >> I'm hoping this is a solved problem by now, more elegantly and >> correctly coded than my hack job would be. >> >> Thanks, >> Jeff >> >> Python rocks, btw. I've almost broken the #!/bin/ksh habit ;) >> From me at privacy.net Tue May 25 04:08:46 2004 From: me at privacy.net (Duncan Booth) Date: 25 May 2004 08:08:46 GMT Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> <slrncb5s1p.21a.bignose-hates-spam@rose.localdomain.fake> Message-ID: <Xns94F45CB2C1E18duncanrcpcouk@127.0.0.1> Ben Finney <bignose-hates-spam at and-benfinney-does-too.id.au> wrote in news:slrncb5s1p.21a.bignose-hates-spam at rose.localdomain.fake: > On Tue, 25 May 2004 08:10:51 +1000, mr_vocab wrote: >> i never got this its always in my tutial bookfor i in range(...) > > "Index". i.e., the variable will be the index of an array you want to > iterate over. > > The usage of "i" was promulgated by the FORTRAN language, which allowed > only single-letter variable names (and was all upper case, too, so it > was actually I). The FOR statement was commonly used to iterate over an > array, and I and J were the commonly used index variables for that > purpose. Close, but not quite there. Early versions of Fortran supported variable names up to 6 characters long. Actually, Fortran always allowed longer variable names, but only the first 6 were significant. I believe the reason why it was 6 characters was that with a 36bit word length and 64 characters in your character set (as you say, no lower case), you could exactly pack a 6 character string into 1 machine word. The actual reason why everyone uses I and then J as the for loop indexes was that Fortran, by default, assumed all variables starting with letters from I-N were integer, and all other variable names were real. Integer names starting with I was presumably chosen for its mnemonic value and the other letters then follow on in sequence, presumably far enough for what the original language designers thought was a reasonable 20:6 split real to integer variables. Obviously you are going to pick some really meaningful :^) 6 character name for that all important linear-regression library function but for a simple loop, why bother. From tzot at sil-tec.gr Tue May 25 15:37:02 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 25 May 2004 22:37:02 +0300 Subject: Solving the Einstein's Riddle in Python References: <juha.haataja-46ED17.14123824052004@newsread.funet.fi> <40B22B86.152586E4@alcyone.com> <e838aa6e.0405250858.7bc1c440@posting.google.com> Message-ID: <qu77b01u3o38kuh0rf3ji2jihr088a1vct@4ax.com> On 25 May 2004 09:58:20 -0700, rumours say that alloydflanagan at comcast.net (A. Lloyd Flanagan) might have written: >Actually it was created by Al Einstein, and he was really quite famous >for it, until that Albert guy came along a century later. So then >this new guy has a little theory or two, and suddenly everybody >forgets about Al. Kind of a sad story, actually. Right. Not only so, but Albert also used the same blackboard Al used, as you can clearly see in the link provided by the OP: http://www.manbottle.com/trivia/Einstein_s_Riddle.htm I think Albert Einstein was a fraud, and the true hero was another guy with the same name. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From Mike at DeleteThis.Geary.com Thu May 27 13:05:07 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 27 May 2004 10:05:07 -0700 Subject: How to I print without newline ? References: <40B603E9.1070003@anonym.hu> <mailman.370.1085675950.6949.python-list@python.org> Message-ID: <10bc7u41tmckoaf@corp.supernews.com> Ray Cote wrote: > Putting a comma at the end of each print statement suppresses > the newline. > > print "hello", > print "world" > > Result: helloworld Actually, that will print "hello world", not "helloworld". Of course, the OP wanted spaces anyway, so it doesn't matter. To suppress the spaces as well as the newlines, use sys.stdout.write(). -Mike From alan.gauld at btinternet.com Sun May 16 02:43:29 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 May 2004 07:43:29 +0100 Subject: Fw: Python vs. VBScript vs. JavaScript in context of Windows Scripting Host? References: <mailman.4.1084671402.13608.python-list@python.org> Message-ID: <753ea0plhp1cndpiu9u969e85huis9kst0@4ax.com> On Sat, 15 May 2004 18:36:21 -0700, "John Benson" <jsbenson at bensonsystems.com> wrote: > Yes, but I was referring to VBScript apart from the runtime children like > Dictionary, Network etc., like the C language apart from the Standard > Library. I agree, though, Dictionaries are cool, however supplied. I missed the beginning of this thread so I may be missing the point too... If anyone is interested in comparing VBScript with Python the rewrite of my web tutor uses VBScript as a comparison language (along with Javascript) against Python. The rewrite is only half way finished but all the basic topics (data,sequences,loops and branches) have been converted already, The OO bits and error handling are the big ommissions for now: http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ Just in case anyone is interested! Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From NOmanlio_perilloSPAM at libero.it Sun May 30 12:25:45 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sun, 30 May 2004 16:25:45 GMT Subject: httplib bug? Message-ID: <6k2kb09l4ku9f3qkrnfqj40tmdhini0au4@4ax.com> Hi. I'm not sure of this. When one do an HEAD command, no response body is returned. But httplib does not check this and when I do another request without first calling HTTPResponse.read, raises a ResponseNotReady exception. Thanks and regards Manlio Perillo From PPNTWIMBXFFC at spammotel.com Fri May 28 04:13:15 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 28 May 2004 10:13:15 +0200 Subject: pdf2txt References: <Z3Atc.28409$zO3.22415@newsread2.news.atl.earthlink.net> Message-ID: <opr8pagdgs35jo5o@news.gmane.org> For me 'ps2ascii' did the job... From alloydflanagan at comcast.net Tue May 25 13:18:18 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 25 May 2004 10:18:18 -0700 Subject: newbie: how to capture/write to stdio on NT References: <jLMrc.5349$Tn6.1709@newsread1.news.pas.earthlink.net> Message-ID: <e838aa6e.0405250918.35b86e83@posting.google.com> "Sholtz" <nospam at nospam.com> wrote in message news:<jLMrc.5349$Tn6.1709 at newsread1.news.pas.earthlink.net>... > Hi, > > I am trying to figure out how to 'control' the input & output using > popen/popen2 etc on Python 2.3 > I have found examples for unix such as the one below but I can't get it to > work on Windows NT. > > If I use the os.popen module I can read OR write not both. > > Anybody have any ideas? > > Regards, > > Sholto. > popen() at least used to not work reliably under Windows, not sure if that's the current status. There apparently were problems with the POSIX emulation and the fact that the Windows methods for creating processes are somewhat different. You might look into the CreateProcess() system call. From mcfletch at rogers.com Tue May 4 02:47:52 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 04 May 2004 02:47:52 -0400 Subject: Setting an Image File Values In-Reply-To: <JgFlc.6232$Hs1.4362@newsread2.news.pas.earthlink.net> References: <JgFlc.6232$Hs1.4362@newsread2.news.pas.earthlink.net> Message-ID: <40973C98.7070108@rogers.com> W. Watson wrote: > I have a 640x480 b/w bmp image file that can be converted to a dat > file. I would like to convert the value of each pixel that is below > say 120 units to exactly 40 units. ... > python -c "open('mask.dat','w').write(chr(40)*640*480)" Well, if you're going to take this as the baseline, then we can do some pretty darn simple stuff indeed: >>> import string >>> def createMask( threshold=120, target=40 ): ... """Create 256-char mapping of destination characters""" ... return string.maketrans( "".join( [chr(x) for x in range(threshold)]), chr(target) * threshold ) ... >>> data = open( "p:\\drawcurve.py", 'rb' ).read() # mode 'rb' is important! use 'wb' to write >>> mask = createMask() >>> data "'''Test of the glVertex function\r\n\r\nDrawing TT glyphs as Cubic splines...\r\n\thttp://support.microsoft.com/support/kb/articles/q243/2/85.asp\r\n\r\n'''\r\nfrom OpenGLContext import testingcontext\r\nBaseContext" >>> data.translate( mask ) '((((((((((((((((((((((x((((((((((((((((((((((((((y(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((x(((((((((((((((((((((x((((((((((((x(' >>> ord('x') # just to see why x and y show up... 120 Of course, most Python programmers, when faced with a problem like this would turn to either PIL (Python Imaging Library) or Numpy (Numeric Python), but if all you need is quick-and-dirty, there you go. Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From hugo_mesquita at hotmail.com Tue May 4 20:28:24 2004 From: hugo_mesquita at hotmail.com (Fernando) Date: Wed, 05 May 2004 00:28:24 GMT Subject: tkinter question... References: <cmRlc.53931$hR1.23957@fe2.texas.rr.com> <Pine.LNX.4.44.0405041326120.29617-100000@e5-05.ee.ualberta.ca> Message-ID: <IyWlc.54870$hR1.7168@fe2.texas.rr.com> Well, Here is what I get: [root at exodus lib-dynload]# uname -a Linux exodus 2.6.5 #1 Fri Apr 30 13:52:04 CDT 2004 i686 i686 i386 GNU/Linux [root at exodus lib-dynload]# pwd /usr/local/lib/python2.3/lib-dynload [root at exodus lib-dynload]# ldd _tkinter.so ldd: ./_tkinter.so: No such file or directory [root at exodus lib-dynload]# rpm -q tk tk-8.3.5-93 [root at exodus lib-dynload]# rpm -q tcl tcl-8.3.5-93 [root at exodus lib-dynload]# Thanks! Fernando, Grzegorz Dostatni wrote: > > Cheers. > > This means that Tkinter is not fully installed. Exactly it means that the > _tkinter.so or _tkinter.dll file is missing. > > It may help to let us know which operating system, etc you've got > installed, but... > > I assume you're not running Windows - the installer generally does not > leave stuff like that. > > Now, you may be running linux or some version of unix. Try searching > inside python directory for _tkinter.so. On my computer it is: > /usr/local/lib/python2.3/lib-dynload/_tkinter.so. > > If this file exists - that means there are libraries it needs that it > cannot find. Try ldd: > > grzegorz at e5-05:/usr/local/lib/python2.3/lib-dynload$ ldd _tkinter.so > libtk8.3.so => /usr/lib/libtk8.3.so (0x4000b000) > libtcl8.3.so => /usr/lib/libtcl8.3.so (0x400b7000) > libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x40138000) > libc.so.6 => /lib/i686/libc.so.6 (0x40217000) > libdl.so.2 => /lib/libdl.so.2 (0x4034a000) > libm.so.6 => /lib/i686/libm.so.6 (0x4034d000) > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) > > The most likely problems are the libtk8.3 and libtcl8.3. Make sure that > tcl and tk are installed and their libraries are in the LD_LIBRARY_PATH. > > If the _tkinter.so file does not exist - you may need to recompile python > from source and read the documentation. > > Greg > > Advice is what we ask for when we already know the answer but wish we > didn't. > -- Erica Jong (How to Save Your Own Life, 1977) > > > On Tue, 4 May 2004 fernando at localhost.localdomain wrote: > >> Hi there, >> When I try to run IDLE I get the error bellow. Can anybody help? >> Thanks! >> >> [fernando at exodus fernando]$ idle >> Traceback (most recent call last): >> File "/usr/local/bin/idle", line 3, in ? >> from idlelib.PyShell import main >> File "/usr/local/lib/python2.3/idlelib/PyShell.py", line 19, in ? >> from Tkinter import * >> File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 38, in ? >> import _tkinter # If this fails your Python may not be configured for >> Tk >> ImportError: No module named _tkinter >> >> From hungjunglu at yahoo.com Fri May 7 22:34:51 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 7 May 2004 19:34:51 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <c7f6fj$aok$1@panix1.panix.com> <997a06e0.0405071007.3b903c7b@posting.google.com> Message-ID: <8ef9bea6.0405071834.752f732a@posting.google.com> pugnatio2 at yahoo.com wrote in message news:<997a06e0.0405071007.3b903c7b at posting.google.com>... > Thanks to all who replied. I think I've got it straight now, and by > the way I did use "polymorphism" incorrectly; I should have said > "method overloading." You did not make a mistake. Others did. http://en.wikipedia.org/wiki/Polymorphism_(computer_science) In terms of code factorization, polymorphism simply means "factorization of a name". Same name, different code. The actual code used is decided by some underlying/implicit mechanism. Anything that fits the criterion "same name, different code" can be called polymorphism. It can be applied to data or functions/methods alike. "Polymorphism" itself means several things. In a sense, the term itself is polymorhic: same word, several meanings. The precise meaning depends on context. If you understand this last part, you understand polymorphism. :) regards, Hung Jung From amireallyfat at yahoo.com.au Fri May 28 00:55:09 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Fri, 28 May 2004 14:55:09 +1000 Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> Message-ID: <40b6c627$1_1@news.iprimus.com.au> great thanks "mr_vocab" <amireallyfat at yahoo.com.au> wrote in message news:40b2e204$1_1 at news.iprimus.com.au... > i never got this its always in my tutial bookfor i in range(...) > > > From michele.simionato at poste.it Sat May 22 04:37:04 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 22 May 2004 01:37:04 -0700 Subject: Passing options between modules References: <939f49f8.0405210907.4f12a613@posting.google.com> <mailman.147.1085160124.6949.python-list@python.org> Message-ID: <95aa1afa.0405220037.7f5131f@posting.google.com> David Goodger <goodger at python.org> wrote in message news:<mailman.147.1085160124.6949.python-list at python.org>... > Chris wrote: > > I'm trying to come up with a not-so-ugly manner of passing many > > command-line options between modules. > > Use optparse.py. It's standard in Python 2.3, or get it from > http://optik.sf.net for older versions of Python. > > The result of parsing command-line options is a "Values" object, > with standard dotted-attribute access. For example, for > "--an-option", you'd say "options.an_option". It's easy to pass > the single Values object around. > > -- David Goodger I second this. <shameless plug> You may also want to look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844 which will make your life with optparse easier. </shameless plug> Michele Simionato From peter at engcorp.com Fri May 21 11:29:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 11:29:09 -0400 Subject: Deleting Directories In-Reply-To: <wbKdncJOeLp5gzPdRVn-tA@powergate.ca> References: <mailman.138.1085151361.6949.python-list@python.org> <wbKdncJOeLp5gzPdRVn-tA@powergate.ca> Message-ID: <_KSdnVRCELHbvTPdRVn-sw@powergate.ca> Peter Hansen wrote: >> But, when I find the folder a simple rmdir() command does not work >> because the directory is not empty. What else do I need to do to delete >> a directory that contains content? > > I've also been able to get shutil.rmtree() to do it before, as I recall, > with an appropriate error handler, though I vaguely recall it had to > restart in some way after each directory which failed to be removed > the first time because it was not empty. Since Rico didn't give a disclaimer about the directories being empty, I just did a little test and sure enough, rmtree will wipe out everything without complaint. As it turns out, the only time you need special handling is if some of the files are not deletable. -Peter From nid_oizo at yahoo.com_remove_the_ Tue May 25 12:30:11 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 25 May 2004 12:30:11 -0400 Subject: Slice assignment for strings? In-Reply-To: <c8vre2$ruk$04$1@news.t-online.com> References: <c8vre2$ruk$04$1@news.t-online.com> Message-ID: <jwKsc.27899$tb4.969902@news20.bellglobal.com> Jens Lippmann wrote: > So, my questions are: > - How do I get it right? > - If slicing seems to be the favorite way to address substrings, why > is it impossible to use it on a left side of an assignment? > Strings are immutable in python; it means you cannot change them in-place. You can still change the value of variables and do things like: a = "hello" a = "a" + a[2:] # producing allo Strings are immutable, but there's (mutable) containers that might do a better job for what you want to do. Module array could be a possible solution (and I'm sure there's others). Regards, Nicolas From ahk at writeme.com Sat May 1 11:31:07 2004 From: ahk at writeme.com (ahk) Date: 1 May 2004 08:31:07 -0700 Subject: python/pyGtk : How to generate a keyboard interrupt? Message-ID: <eb02dbae.0405010731.a251212@posting.google.com> I would like to emulate the keyboard interrupt through other means other than the actual hitting on the keyboard such that a call to scaninput() (a C function call?) will be able to pick up the interrupt. How is it possible to do that in python/pyGTK? TIA. From stephen.mcphail at casaccia.enea.it Thu May 27 05:36:23 2004 From: stephen.mcphail at casaccia.enea.it (byte biscuit) Date: Thu, 27 May 2004 11:36:23 +0200 Subject: Fortran-compiled DLLs in Python Message-ID: <c94crp$q8a$1@canarie.caspur.it> Hi there everybody! The problem is the following: we have a DLL (H2O.dll) - compiled in Visual Fortran - depending in turn on another DLL. H2O.dll contains only one (1) function, with a known name (WATER). The WATER function is called with the following parameters: - TT (datatype: double precision) [input] - PP (datatype: double precision) [input] - State (datatype: integer) [input] - DiERR (datatype: integer) [output] - SIG (datatype: double precision) [output] - Prop (datatype: double precision array[16 elements]) [output] Obviously, we would like to make use of Python to handle the function and pick out the results... We thought of using the **ctypes** module to tackle the problem, but we have stranded just about at the first attempt: >>> from ctypes import * >>> h2o = windll.H2O >>> h2o.WATER(c_long(40.0),c_long(1.0),c_int(2),c_int(dierr),c_int(Sig),c_long*1 6(prop)) Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: int expected instead of float instance Who can show us the Right way, riding the Python? THANKS! stephen From cbrown at metservice.com Fri May 28 02:17:15 2004 From: cbrown at metservice.com (Colin Brown) Date: Fri, 28 May 2004 18:17:15 +1200 Subject: Determine rights and privileges on Windows. References: <mailman.369.1085675362.6949.python-list@python.org> Message-ID: <40b6d88d$1@news.iconz.co.nz> "Peter Schmiedeskamp" <pschmied at yahoo.com> wrote in message news:mailman.369.1085675362.6949.python-list at python.org... > Hello, I'm writing a python program (in Windows) from > which I would like to determine whether or not either: > 1. The user has administrative access on the current > PC. > or (better) > 2. The currently running process has administrative > access. Hi Peter It may be worth having a look at WMI (Google "python wmi"). Cheers Colin Brown PyNZ From smeier at exelixis.com Wed May 26 15:33:02 2004 From: smeier at exelixis.com (Stefan Meier) Date: Wed, 26 May 2004 12:33:02 -0700 Subject: prefix matching In-Reply-To: <c92q07$iat$05$1@news.t-online.com> References: <c92q07$iat$05$1@news.t-online.com> Message-ID: <200405261233.02037.smeier@exelixis.com> Must be something like >>> l=["pref1","pref2"] >>> s="String" >>> if filter(lambda x:s[:len(x)] == x, l): >>> # do something Cheers, Stefan On Wednesday 26 May 2004 12:08 pm, Christian Gudrian wrote: > Hello, there! > > Given a list with strings. > > What is the most pythonic way to check if a given string starts with one of > the strings in that list? > > I started by composing a regular expression pattern which consists of all > the strings in the list separated by "|" in a for loop. Then I used that > pattern to do a regexp match. > > Seems rather complicated to me. Any alternatives? > > Christian -- Stefan Meier Computational Biology & Informatics Exelixis, Inc. 170 Harbor Way, P.O. Box 511 South San Francisco, CA 94083-511 fon. (650)837 7816 From roy at panix.com Sun May 23 16:37:17 2004 From: roy at panix.com (Roy Smith) Date: Sun, 23 May 2004 16:37:17 -0400 Subject: Unit testing in Prothon? Message-ID: <roy-4558B5.16371723052004@reader2.panix.com> I've read through the Prothon tutorial and must admit there is something kind of interesting about the idea of prototypes instead of classes. My thoughts quickly turned to testing. If nothing else, classes give us a nice place to hang unit tests on. I can design and test one class at a time, then move on to the next one. What would unit testing look like in Prothon? From theller at python.net Thu May 27 06:26:48 2004 From: theller at python.net (Thomas Heller) Date: Thu, 27 May 2004 12:26:48 +0200 Subject: Fortran-compiled DLLs in Python References: <c94crp$q8a$1@canarie.caspur.it> Message-ID: <y8ne2mjb.fsf@python.net> "byte biscuit" <stephen.mcphail at casaccia.enea.it> writes: > Hi there everybody! > The problem is the following: > we have a DLL (H2O.dll) - compiled in Visual Fortran - depending in turn on > another DLL. > H2O.dll contains only one (1) function, with a known name (WATER). > The WATER function is called with the following parameters: > - TT (datatype: double precision) [input] > - PP (datatype: double precision) [input] > - State (datatype: integer) > [input] > - DiERR (datatype: integer) > [output] > - SIG (datatype: double precision) > [output] > - Prop (datatype: double precision array[16 elements]) [output] > > Obviously, we would like to make use of Python to handle the function and > pick out the results... > We thought of using the **ctypes** module to tackle the problem, but we have > stranded just about at the first attempt: > >>>> from ctypes import * >>>> h2o = windll.H2O >>>> > h2o.WATER(c_long(40.0),c_long(1.0),c_int(2),c_int(dierr),c_int(Sig),c_long*1 > 6(prop)) > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > TypeError: int expected instead of float instance Looking at your function description above, I would guess you have call it in the following way (although the error you get is that c_long(40.0) complains about the float argument): dierr = c_int() prop = (c_double * 16)() # create a 16 element double array h2o.WATER(c_double(40.0), c_double(1.0), c_int(2), byref(dierr), prop) Although I do know nothing about fortran (anymore). Thomas From tzot at sil-tec.gr Tue May 11 14:34:32 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 11 May 2004 21:34:32 +0300 Subject: OT: Idea for Python T-shirt References: <ppj1a09ee7766t94o439qd2bgbc18resg1@4ax.com> <JpqdnYIeR4GMRT3dRVn-gg@powergate.ca> Message-ID: <2472a0tgrcv1oc3mbu0ndljogpc5out9da@4ax.com> On Tue, 11 May 2004 09:41:35 -0400, rumours say that Peter Hansen <peter at engcorp.com> might have written: [snip "nibbles exploding with desire"] >Also, I don't get it... Based on the hungarian phrase-book sketch from the Flying Circus... "my nipples explode with desire!" -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From andrew-pythonlist at puzzling.org Sun May 9 20:56:53 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 10 May 2004 10:56:53 +1000 Subject: list comprehension In-Reply-To: <c7mii9$988$1@lust.ihug.co.nz> References: <c7mii9$988$1@lust.ihug.co.nz> Message-ID: <20040510005653.GA14313@frobozz> On Mon, May 10, 2004 at 12:32:20PM +1200, Guy Robinson wrote: > Hello, > > Trying to change a string(x,y values) such as : > > s = "114320,69808 114272,69920 113568,71600 113328,72272" > > into (x,-y): > > out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" > > I tried this: > > print [(a[0],-a[1] for a in x.split(',')) for x in e] > > But it doesn't work. Can anyone suggest why or suggest an alternative > way? The text strings are significantly bigger than this so performance > is important. It has several syntax errors; (a[0],-a[1] for a in x.split(',')) is not a valid expression because list comprehensions are bracketed by square brackets, not parentheses. Also, the first part of a list comprehension, the expression to calculate each element, needs to be in parens to if it has a comma, so that the parser can disambiguate it from an ordinary list. I also don't know where you got 'e' from. Is it 's', or 's.split()'? If list comprenhensions grow unwieldy, just use a for loop. They're probably easier to read than a list comprehension that takes you ten minutes to concoct, and performance is almost identical. For the sake of answering your question, though, here's a expression that does what you ask: >>> s = "114320,69808 114272,69920 113568,71600 113328,72272" >>> s.replace(',',',-') '114320,-69808 114272,-69920 113568,-71600 113328,-72272' You could do this with list comprehensions, e.g.: >>> ' '.join(['%s,-%s' % tuple(x) for x in [pairs.split(',') for pairs in s.split(' ')]]) '114320,-69808 114272,-69920 113568,-71600 113328,-72272' But I don't really see the point, given the way you've described the problem. -Andrew. From martin at v.loewis.de Sat May 22 18:57:53 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 23 May 2004 00:57:53 +0200 Subject: terminological obscurity In-Reply-To: <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> Message-ID: <40AFDAF1.4080400@v.loewis.de> Arthur wrote: > Given a tuple (1,1,1) representing X,Y,Z corrdinates, I - for one - > have trouble explaining the heterogenous nature of the data, outside > of the "tuple" sense of the word. Most people tend to think that "height" and "width" are different concepts. I am 199cm high, not 199cm wide. So my extension, in Y direction, is 199cm - not my X extension, nor my Z extension. The fact that I use cm to measure X, Y, and Z still doesn't make them homogenous. If they were homogenous, I could add many more of these in a meaningful way (yes, I know that some people have applications where you process arbitrary numbers of coordinates. typically, 2D, 3D, and 4D are entirely different things). > Similarly, "conceptual homogeniety" in this context can mean anything > - to me, pretty much -, within the limit of describing data elements > that it might be sensible to handle together in a list. A collection of data is homogenous if their relative position in the sequence does not matter much. They are heterogenous if different elements have entirely different meanings. Regards, Martin From peter at engcorp.com Thu May 6 12:13:26 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 May 2004 12:13:26 -0400 Subject: Private identifiers - naming In-Reply-To: <mailman.312.1083852957.25742.python-list@python.org> References: <930ba99a.0405060600.17e076bc@posting.google.com> <mailman.312.1083852957.25742.python-list@python.org> Message-ID: <TY-dnTW1648x_gfdRVn-hg@powergate.ca> Heiko Wundram wrote: > Am Donnerstag, 6. Mai 2004 16:00 schrieb Sridhar R: > >>Any thoughts? > > If you find "__varname" difficult to read, don't use it. Python doesn't hide > (try a dir(<instance>)) or protect access to these variables anyway, so you > actually gain nothing using this syntax if it makes it cryptic for you. Actually, using __varname causes the compiler to munge the name so that it is actually _ClassName__varname, to allow subclasses to use the same name without stepping on the parent class' variable of that name. So cryptic or not, you actually _do_ gain something if, for example, you are trying to write a library for reuse and don't want to have to document all the attributes which are used internally, just to make sure nobody inadvertently defines a subclass which uses the same name and buggers up the works. It's not about _preventing_ such access, just protecting against casual/accidental collisions. -Peter From jcarlson at uci.edu Thu May 6 02:49:26 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 05 May 2004 23:49:26 -0700 Subject: Efficient string concatenation methods In-Reply-To: <c57c103.0405030040.3eb7d1a3@posting.google.com> References: <b3a34c4c.0405011643.70c163c3@posting.google.com> <5d83790c.0405021752.2b82345e@posting.google.com> <c57c103.0405030040.3eb7d1a3@posting.google.com> Message-ID: <c7cncu$sdl$1@news.service.uci.edu> > Is there any particular reason why the space allocated does not > increase *exponentially*, say with a factor of 1.5 or 2? That's how > the string class is implemented in C++, IIRC. That'd give you > amortized linear rather than quadratic time. The C++ string class is mutable. When you have immutable strings, having extra space at the end is useless. - Josiah From dmq at gain.com Wed May 12 21:28:46 2004 From: dmq at gain.com (David MacQuigg) Date: Wed, 12 May 2004 18:28:46 -0700 Subject: Ideas for Python 3 References: <s1pt80h988ucqd8vbrd3occhpagtpssigg@4ax.com> <onrt805i8q1qv5amhk06pqpe8umm9i7mhc@4ax.com> <c6mtgm$e09bj$1@ID-88904.news.uni-berlin.de> <n9q490hbe2a2mp65e5rh59eb97r2k1b9hn@4ax.com> <c7b2h1$eo$1@news.service.uci.edu> <lqti90hga2d7s19r012tjfm9v1gku2glf0@4ax.com> <c7clt9$r3k$1@news.service.uci.edu> <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> <c7pi8h$pcp$1@news.service.uci.edu> <2r91a0tlksovkn20maa7mk5vekr8h2joa5@4ax.com> <c7u9at$cvh$1@news.service.uci.edu> Message-ID: <n5f5a09pu7h6r52ibjo8d8h2oh3pbm2quu@4ax.com> On Wed, 12 May 2004 15:39:41 -0700, Josiah Carlson <jcarlson at uci.edu> wrote: >>>I've read the link you posted, and I've previously taken a look at >>>Prothon. Prototype syntax does not suit my taste in programming >>>languages. If Python 3.0 becomes Prothon, I'll fork the most recent >>>Python 2.x codebase that I prefer, maintaining it myself if necessary. >>> >>>Just as my anti-prototype perspective colors my opinions on what is >>>reasonable, I would imagine that your pro-prototype perspective colors >>>yours. >> >> I am currently neutral on the idea of prototypes, still waiting for >> anyone to show me a good use case, so I can include it in my webpage. >> I still have "cloning" of instances in my proposal, but you will >> notice they are at the bottom of the list of benefits at >> http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm > >Considering that you provide an animal heirarchy use-case to illustrate >what you propose, I'd say that you're a bit on the positive side of neutral. The animal hierarchy is intended as a vehicle to demonstrate *all* the features of the proposal. The "with" statement, and the ability to "clone" instances are actually outside of that hierarchy, and are easily separable. Taking them out won't hurt the main part of the proposal, and I probably should do that on the next revision, just to avoid having the whole proposal valued on a feature that can't be justified. On the other hand, maybe I should leave these in as "throw-aways", so if the proposal ever does get near implementation, they can cut these features instead of something important. :>) >I don't believe I understand the idea of "cloning", at least in terms of >prototypes. In my mind it brings up either using a copy() method on >instances, or using instance1.__dict__.update(instance2.__dict__) to >transfer instance variables. Unless there is more (or an actual) >description about what a "clone" is, I can't say whether it is a benefit >or drawback. It's real hard to get a clear statement from the prototype advocates, but my understanding is that they want to eliminate all classes, and just make instances, one from another by "cloning". Cloning is different than instantiation in Python, because all attributes are copied to the clone. This means you cannot change an ancestor's attribute and have it change for all descendents that don't explicitly over-ride that attribute. This lack of an active "inheritance" mechanism seems like a major disadvantage to me. Presumably there is some counterbalancing advantage, but I have not been able to figure that out. >> I typically get enthusiastic about something when I first see it, then >> I learn a little more, and some of the new tricks/features drop to the >> bottom of my list. What remains of my original enthusiasm for Prothon >> is still in the unification of methods and functions. > >I guess I must be an "Expert", because unifying methods and functions >doesn't seem to be necessary to me. While some (including yourself) >state that it would make learning portions of Python easier, never >having had issues handling lambdas, functions, class methods, static >methods, or instance methods, I don't know what people have issues with. > >Really the question is: "Is there a problem with current function, >method, etc., syntax?" If there is a problem, the next question is, >"What are people having problems understanding?" At some point there >would likely be examples provided that show where the user was confused. > Documenting those examples to explain the syntax, I believe, would be >sufficient, but then again, I RTFM. I've never been able to convince anyone based on an isolated example. The problem is that even if I show something with a benefit as obvious as the elimination of special syntax for a static method, the counter is either static methods are simple, or you don't need them. Take a look at the 96 pages devoted to OOP in Learning Python, 2nd ed. This is generally considered the best introductory text on Python, and it looks to me like it includes the right choice of topics, and is well written. Then take a look at http://ece.arizona.edu/~edatools/Python/Prototypes.doc In 8 1/2 pages, I provide a basic introduction to everything students will need to write class hierarchies, work with bound and unbound functions, and write programs that in Python would require static methods. If I were to add some additional topics, examples and exercises, I think this presentation would expand to 40 or 50 pages. This is something I could usefully teach in 4 hours of the student's time ( lecture, reading, and practice ). The key to making this work is to build on of what the students already know ( functions, modules, and global variables ). With the unification I am proposing, there is almost nothing to learn in going from modules to classes. It's just a different way to package data and functions. I could probably do almost the same in Python by ignoring all but the most common method form. The problem is that ignoring these other forms is not the same as ignoring metaclasses. The student is unlikely to encounter a need for metaclasses, but the need for static methods arises naturally. At least it seems natural to me, having not been conditioned to avoid them. Not being able to call function from a class without a special first argument, seems to me like not being able to have the letter 'q' in a variable name. There is extensive discussion of this topic on the thread "Unification of Methods and Functions", including some examples of how to write classes which avoid the need for static methods. So far, I have not seen anything that is better as an introduction to OOP than my original example. You might want to join in that discussion, if you can add something to our understanding. >In terms of instance variables and accessing via .variable, I would >imagine the lack of 'this' (for C++ or Java programmers) or 'self' (for >Python programmers) to be somewhat disconcerting, and though '.' is used >to denote a namespace heirarchy in functions, modules, classes, etc., >having it lead a an instance variable or function suffers from the same >"punctuation-itis" that is listed as a drawback for various function >definition syntaxes. The issue is not .var vs self.var vs $var or any other variant. They are all equally explicit, and everyone will have a different opinion as to which is ugly or pretty. The issue is the different argument sequences. To unify all forms of functions and methods, we need to get 'self' out of the argument list. I know this seems like a trivial change, but take a look at how many pages in Learning Python are devoted to the different function and method forms. >For those that I come across who are hung up on the handful of syntaxes >available for functions/methods, I point out that really only two are >generally needed (function(), instance.method()). The others are merely >there to make life easier for 'advanced' users, and if are not labeled >as such, should be (class.method(instance) is pretty useful, as can be >lambda, and are the two 'advanced' function types that I use). By only >introducing the two major syntaxes, whose only difference is the naming >of the referenced instance (for flexibility), I believe the vast >majority of people who had troubles before, would have very few now. If you can show me that static methods are not necessary, please join the discussion under "Unification of Methods and Functions". We have a fairly simple problem, an animal hierarchy, and some fairly simple requirements. These are stated as an exercise at http://ece.arizona.edu/~edatools/Python/Exercises/ >> The key to finding what is fundamentally good in these other >> languages, and what is just someone's personal preference for being >> different, is keeping an open mind. It's astonishing how few people >> can do that in comparing computer languages. I guess it is just >> easier to be "anti" or "pro" and skip the investigation and thinking. > >On that note, I am relatively closed-minded about (even suggested) >alterations to Python because it works so well for me /now/, I'm being >paid to write software with it /now/, of the alterations that are being >offered, I don't believe any would increase my productivity /soon if >ever/, and I find them to be both aesthetically unpleasing, as well as >relying on the assumption that people don't /currently/ understand Python. What I am proposing will be of no benefit to advanced users. But it won't be a problem for them either. I would expect an advanced user to learn the new simpler syntax in about five minutes. As for the aesthetics, I would trust GvR to make a good choice, and after using the new syntax for a while it will look just right. What I like about GvR is that in spite of his genius, he can still show concern for something as simple as the problem beginners have with dividing two integers. That problem doesn't bother me or anyone I know, but I like the fact that he fixed it. >I believe that the current learning curve of Python is sufficiently >gradual as to allow the vast majority of people to use it effectively. >Knowing the ins and outs of the entirety of the language is not >necessary, and even a reasonable subset excludes staticmethods, >metaclasses, etc. Take a look at the link above for a simple problem that uses static methods. The lack of static methods would seriously cramp my style. >>>I would also expect that someone who enjoys using lisp or >>>perhaps SML would have their opinion on what is reasonable, colored by >>>their preferences. Considering that Python is not a prototype-based >>>language today in 2.3 (or the forthcoming 2.4 in the fall), having it >>>become one in Python 3 would be quite a drastic change, quite literally >>>like going from Python 2.3 to Prothon. >> >> I continue to find new surprises in Python. The ability to change >> classes into prototypes by using descriptors is the latest exammple. >> This seems like a drastic change, but it is all within the capability >> of Python. > >Being able to use prototypes, without prototype syntax, is not changing >the language syntax. The fact that Python doesn't need prototype syntax >to have prototypes, I believe, is an argument against altering Python's >syntax. It's an argument agains making prototypes ( 'with' statements and cloning ) part of the core. It's irrelevant to the more important parts of the proposal. >> Prothon does have some changes that are more drastic, but in my >> opinion have no real benefit over Python. I measure drastic by how >> much effort it will take to translate existing Python programs to >> Prothon. By this measure, the unification of functions and methods is >> not a drastic change. I believe it will be possible to automatically >> translate all Python methods into the new form. So if we categorize >> syntax changes as ( Compatible / Migratable / Totally Different ), the >> proposed changes are in the middle. > >Function/method unification is certainly migratable, I've never claimed >otherwise. In fact, with a good refactoring tool, it is trivial (and >actually a search+replace will go a long ways towards migrating). The >'.' prefix "punctuation-itis" I described earlier, coupled with your >statement that __self__ is magical (more or less so doesn't matter >much), suggests that together, they are trying to replace an easy to >understand magic, with another easy to understand magic. The only >/real/ change that the function unification is advocating, is the >replacement of an explicit name for something that is passed implicitly, >with an implicit name for something that is passed implicitly, and the >replacement of an explicit instance name with no name at all. Which is >better is debatable, but I prefer the current Python syntax, due to the >reduced number of implicit items (only the instance is implicit, as >compared with the instance, name, and instance references in prototype >syntax). Again, I'm not getting into the 'self' debate. The real issue is unification. If that were to require putting 'self' into *all* calling sequences, whether it was needed or not, that would be preferrable to the current mess. -- Dave From benn at cenix-bioscience.com Wed May 12 12:13:57 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 12 May 2004 18:13:57 +0200 Subject: logging package Message-ID: <40A24D45.8070600@cenix-bioscience.com> Hello, I can;t find this information in the docs so I'm hoping someone here may know. Is the logging package thread-safe? As a confirmation of what I mean by 'thread-safe', this means that if I have two threads running, both of which call (for example) objLogger.debug - does the logging package synchronize around the event notification (as in practice the root logger is a singleton)? Thanks, in advance for your help. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience PfotenhauerStrasse 108 D-01307 Dresden Germany Tel : +49 (351) 210 1300 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From edcjones at erols.com Wed May 12 20:10:07 2004 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 12 May 2004 20:10:07 -0400 Subject: Finding the name of a class Message-ID: <40a2be14$0$3014$61fed72c@news.rcn.com> Is there a function or method that returns the name of a class or class instance? class X(object): pass X.amethod() or X().amethod() should return the string "X". X().__class__ returns "<class '__main__.X'>" which I could parse. Ugh. Or I could use module pyclbr. Ugh**2. From nav+posts at bandersnatch.org Sun May 9 22:53:26 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 09 May 2004 22:53:26 -0400 Subject: Anyone seen this? References: <mailman.372.1084105243.25742.python-list@python.org> Message-ID: <m3hdupm1qx.fsf@tanelorn.bandersnatch.org> "Andy Baker" <andy at andybak.net> writes: > http://www.getty.edu/art/collections/objects/o1271.html > Obviously a Microsoft consiracy! Cute! The funny thing is I attended a class last year with someone from the Getty Institute, and they're using an open-source (though copyrighted) document indexing and search engine from U Mich called DLXS (dlxs.org). It's written in object oriented Perl. We're using it in one of our sites, and sometimes I have to troubleshoot the beast. Every time I get close to the code I shudder. 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 seefeld at sympatico.ca Wed May 19 10:11:30 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 19 May 2004 10:11:30 -0400 Subject: using the C API to access objects derived from builtin classes In-Reply-To: <mailman.64.1084948369.6949.python-list@python.org> References: <mailman.48.1084889922.6949.python-list@python.org> <tVpqc.50410$8L3.24856@newssvr29.news.prodigy.com> <a3qqc.34397$325.832599@news20.bellglobal.com> <mailman.54.1084896272.6949.python-list@python.org> <bYsqc.40326$325.880367@news20.bellglobal.com> <mailman.59.1084911074.6949.python-list@python.org> <0Jxqc.49474$325.1002917@news20.bellglobal.com> <mailman.64.1084948369.6949.python-list@python.org> Message-ID: <i_Jqc.52006$325.1218818@news20.bellglobal.com> Thomas Heller wrote: >>But back to the other issue: isn't there any text that explains >>when I should be using PyDict_GetItem and when PyObject_GetItem >>and what they are doing byhind the scene ? > 7. Concrete Objects Layer > > The functions in this chapter are specific to certain Python object > types. Passing them an object of the wrong type is not a good idea; if > you receive an object from a Python program and you are not sure that > it has the right type, you must perform a type check first; for > example, to check that an object is a dictionary, use > PyDict_Check(). The chapter is structured like the ``family tree'' of > Python object types. yeah, I did read that. The inconsistency (or even error, I would argue) is in the interpretation of 'is a'. PyDict_Check reports 'true' when called on my 'Dictionary' object, yet the PyDict_* API only applies to the slice representing the base class. I don't think that is correct, it is at least very surprising. The API only supports two extremes: * the object's type is an *exact* match for a built-in type, thus a highly optimized API can be used to access its methods. * the object's type is unknown, it may or may not support a certain 'protocol', i.e. for all method invocations a full method lookup has to be done. That sounds good for the pre 2.2 world, where built-in types and user-defined types were distinct sets. Regards, Stefan From hadi at nojunk.com.au Fri May 14 12:38:17 2004 From: hadi at nojunk.com.au (Hadi) Date: Sat, 15 May 2004 02:38:17 +1000 Subject: beginner's question References: <c82d51$78s$1@lust.ihug.co.nz> <Xs3pc.34385$dr1.943764@news20.bellglobal.com> <Ny3pc.34409$dr1.944419@news20.bellglobal.com> Message-ID: <c82s64$f66$1@lust.ihug.co.nz> Sean, I appreciate for your help. Your script works fine. I have one last question. What do I have to modify on the script, so the script will work for more than one line? Because the file-1 has about 500 lines. This is for my Machine Learning assignment which I use this for the Naive Bayes classifier for the spam mail classification. Thank you again and I would appreciate very much one more help from you. Regards, Halit your script: exicon = ["our", "halit", "of", "words", "to", "be", "compared"] # open the source and destination files src = file("file-1.txt") # open for reading dst = file("file-2.txt", 'w') # open for writing # Hadi: does file1 contain one or more lines? This only works for one line. # For more lines, you'll need to do further processing ... # # Make a list of the words in src. We split the line at each comma, and # remove any excess whitespace from around the word words = [w.strip() for w in src.readline().split(',')] # Now we see if the words are in our list and write the results to dst for w in words: dst.write("%s, "%(w in lexicon)) # Python will eventually close the files for you, or you can do it explicitly src.close() dst.close() From greg at invalid.invalid Mon May 31 14:40:47 2004 From: greg at invalid.invalid (Greg Krohn) Date: Mon, 31 May 2004 18:40:47 GMT Subject: Best way to put out a small package for public scrutiny and use? In-Reply-To: <slrncbmuhs.1ec.kenneth.m.mcdonald@g4.gateway.2wire.net> References: <slrncbmuhs.1ec.kenneth.m.mcdonald@g4.gateway.2wire.net> Message-ID: <P_Kuc.16813$Tn6.446@newsread1.news.pas.earthlink.net> Kenneth McDonald wrote: > I've created a small (and I believe, very useful) package to ease the > creation and use of regular expressions. I'd like to make it available, > (though the first release will be aimed mostly at finalizing > functionality, not at being a polished project.) I don't want to use > SourceForge, as I don't use CVS, and I'm not yet ready (if ever) > to open up my home Subversion server to public access. If this > was just a single file, I'd simply post it in this newsgroup to > start with, but as it incorporates a couple of files, I need to post > the directory somehow. Any thoughts as to the best way to make > this package available? > > Thanks, > Ken > zip file, tarball? From davidf at sjsoft.com Thu May 13 11:52:13 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 13 May 2004 17:52:13 +0200 Subject: decompyle with Python 2.3 support In-Reply-To: <1785310633.20040513025447@smtp.myrealbox.com> References: <1785310633.20040513025447@smtp.myrealbox.com> Message-ID: <40A399AD.5050008@sjsoft.com> Adal Chiriliuc wrote: > Hi. > > I've added Python 2.3 support to decompyle. All I did was to > add the new header ID of .pyc files and to remove some obsolete > op-codes (which are not present in opcode.py). > > There are files which it can't decompile but it usually works. > > If you're interested you can download it here: > http://adal.eu.org/decompyle.php > > Regards, > Adal Chiriliuc > You're a hero! I was wishing someone would do this. Hopefully this will convince crazy-compilers to start releasing their source again... David From olli at secnetix.de Tue May 11 07:26:50 2004 From: olli at secnetix.de (Oliver Fromme) Date: 11 May 2004 11:26:50 GMT Subject: Inverse of int(s, base)? References: <2gac73Fk1ooU1@uni-berlin.de> <ad052e5c.0405102113.2de5d7dc@posting.google.com> <7xhdungzpr.fsf@ruckus.brouhaha.com> Message-ID: <2gbrjqFvso5U1@uni-berlin.de> Paul Rubin <http://phr.cx at nospam.invalid> wrote: > danb_83 at yahoo.com (Dan Bishop) writes: > > [...] > > That works (for positive integers), but it might be more efficient to > > not create a new string each time through the loop. An alternative is: > > > > def str_base(n, base=10): > ... > > Similarly: > > def str_base(n, base=10): > results = [] > sign,n = ('','-')[n < 0], abs(n) > while n: > n, r = divmod(n, base) > results.append(str_digits[r]) > results.reverse() > return sign + ''.join(results) Cool, thanks both of you! Using divmod() is a good idea. Is creating strings really that expensive in Python? I'm surpised that you're saying that modifying a list and then calling reverse() and join() is more efficient. I thought that the overhead of compound objects such as lists is more expensive than creating strings, which I thought where rather "cheap and simple". I work with strings a lot (in scripts for administration, CGI programs etc.). And since strings are immutable, I often have to create new ones. Now do you suggest I should reconsider my approach and rather try to work with lists in general, and only convert them back to strings for output at the very end? Best regards Oliver -- Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 Munich Any opinions expressed in this message may be personal to the author and may not necessarily reflect the opinions of secnetix in any way. (On the statement print "42 monkeys" + "1 snake":) By the way, both perl and Python get this wrong. Perl gives 43 and Python gives "42 monkeys1 snake", when the answer is clearly "41 monkeys and 1 fat snake". -- Jim Fulton From bignose-hates-spam at and-benfinney-does-too.id.au Tue May 25 02:51:06 2004 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 25 May 2004 16:41:06 +0950 Subject: lists or tuples References: <40b2e203$1_1@news.iprimus.com.au> Message-ID: <slrncb5sca.21a.bignose-hates-spam@rose.localdomain.fake> On Tue, 25 May 2004 07:51:37 +1000, mr_vocab wrote: > hey what is the many dif with them why bothere using tuples and how do > you edit a list??? You just answered your own question. Tuples are immutable. Lists are mutable. That's one of the primary reasons to have these two separate sequence types. Learn more about sequence types in Python: <http://www.python.org/doc/current/tut/node7.html> or, better, work through the whole tutorial to learn a lot about Python: <http://www.python.org/doc/current/tut/> -- \ "I went to a garage sale. 'How much for the garage?' 'It's not | `\ for sale.'" -- Steven Wright | _o__) | Ben Finney <http://bignose.squidly.org/> From miki.tebeka at zoran.com Wed May 19 02:38:36 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 19 May 2004 08:38:36 +0200 Subject: Have added ulaw handling to wave.py -- whom to give it to? In-Reply-To: <67032014.0405181242.20fc7d8f@posting.google.com> References: <67032014.0405181242.20fc7d8f@posting.google.com> Message-ID: <40AB00EC.5030707@zoran.com> Hello Eric, > Hi, I've made small changes to the Python 2.2 wave module to allow > ..wav files with ulaw content to be read and written. I'm wondering how > to give it back to the Python community, is this something for this > newsgroup, or Python-Dev perhaps? http://sourceforge.net/tracker/?group_id=5470&atid=305470 HTH. Miki From dmq at gain.com Fri May 21 08:08:20 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 21 May 2004 05:08:20 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <uavpa017n6dpmlr9ib25rrj6mu423v6j0b@4ax.com> <2h55ajF9alv2U1@uni-berlin.de> Message-ID: <5upra0ljhuc0ulpo11775hrruhatgs4a4v@4ax.com> On Fri, 21 May 2004 13:45:52 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: >David MacQuigg wrote: >> I'm still waiting for that one simple example that you say will do it >> all, and do it right. > >I don't think you should be trying to cram all the features >of OOP into a single example. I agree. Digestible chunks is the right approach. Animals_1.py is the first example of classes, including data, methods, instance variables, and inheritance. Thats a pretty large chunk, but what makes it digestible is the student's prior knowledge of modules, functions, and all forms of data. Animals_2a1.py (the current version) adds more levels to the hierarchy, a special method __init__, static methods, bound and unbound methods, the odd scoping rule for class variables, and _private variables. This is all the basics that students will need if they will be writing their own classes. There probably won't be an Animals_3, but instead, "level 3" will be a bunch of examples to illustrate various techniques, like the robust programming that JM has been pushing, and maybe some topics from chapters 21 - 23 of Learning Python. >Also, I worry that the zoo topic will seem contrived. Why >not base your examples on some real problems from your >audience's subject area? Given the goals of the level one and two examples ( cover all the basic features in two simple examples ) I think any example will be contrived. The level 3 examples will be the right place to introduce real circuit design problems. -- Dave From peter at engcorp.com Sat May 15 08:21:48 2004 From: peter at engcorp.com (Peter Hansen) Date: Sat, 15 May 2004 08:21:48 -0400 Subject: NIC adress of incoming socket. In-Reply-To: <40a5e12e$0$2277$afc38c87@news.easynet.fr> References: <40a4f772$0$2280$afc38c87@news.easynet.fr> <naWdnRu54vmoBTjdRVn-hw@powergate.ca> <40a5e12e$0$2277$afc38c87@news.easynet.fr> Message-ID: <CpSdnTXrVp3AljvdRVn-sw@powergate.ca> RosalieM wrote: > I saw in dhcpd config for bootp that you give the adress of the nic. How > can i be sure that in my lan it is the right computer (my dhcp server) that > answers to my client and not another compromised machine ? Can i ask python > some information from ethernet level in an ip connection? Basically, no. Use external utilities to solve whatever the problem is. I'd suggest that if you might have compromised machines on your own LAN which are answering in place of your real DHCP server, you have rather big problems to solve, and you'd be best involving a network administrator with a good understanding of security issues. -Peter From rstephens at vectron.com Sun May 2 20:52:34 2004 From: rstephens at vectron.com (Ron Stephens) Date: 2 May 2004 17:52:34 -0700 Subject: Book reviews Message-ID: <a5415304.0405021652.7b0bbbe@posting.google.com> You might want to take a look at my reviews of Python books at http://www.awaretek.com/book.html From jepler at unpythonic.net Tue May 18 12:42:03 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 18 May 2004 11:42:03 -0500 Subject: error converting list to tuple In-Reply-To: <40AA1A40.9090404@sympatico.ca> References: <40AA1A40.9090404@sympatico.ca> Message-ID: <20040518164202.GL14843@unpythonic.net> You can't use a list in all the places you can use a tuple. The most frequently encountered difference is that you can't use lists as keys in dictionaries. >>> t = () >>> l = [] >>> {t: None} {(): None} >>> {l: None} TypeError: list objects are unhashable Jeff From cookedm+news at physics.mcmaster.ca Thu May 13 16:51:48 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 13 May 2004 16:51:48 -0400 Subject: Help with Distutils References: <slrnca77ma.5il.johan@svedberg.pp.se> <oiqcn1-0ki.ln1@wintermute.g2ctech> <slrnca7g67.5il.johan@svedberg.pp.se> <hhvcn1-0ki.ln1@wintermute.g2ctech> Message-ID: <qnkbrksuk2j.fsf@arbutus.physics.mcmaster.ca> At some point, Jorge Godoy <godoy at ieee.org> wrote: > On Qui 13 Mai 2004 15:39, Johan Svedberg wrote: > >> Well, the reason is that I've told setup.py to install a bunch of >> templates in <prefix>/share/myapp/templates/ and I want to make sure >> that myapp can find these no matter what <prefix> is. > > I see somebody suggested that you use __file__, from the module. > > Another option --- I'm using it --- is to have a config file and have > distutils to call a postinstall script (requires Python 2.3+) to update the > directory in such a config file. Of course, you have to able to find the config file, but that's a smaller kettle of fish. I suppose you could put the config file in your modules directory (like I suggested), and have your other data files sitting outside (in /usr/share/whatever). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From klappnase at web.de Sat May 22 17:03:54 2004 From: klappnase at web.de (klappnase) Date: 22 May 2004 14:03:54 -0700 Subject: Tkinter: update_idletasks References: <mailman.110.1085067858.6949.python-list@python.org> <c8kd79$vkt$1@news-reader4.wanadoo.fr> <mailman.159.1085178672.6949.python-list@python.org> Message-ID: <a7a67196.0405221303.37e7a2d4@posting.google.com> Jeffrey Barish <jeffbarish at starband.net> wrote in message news:<mailman.159.1085178672.6949.python-list at python.org>... > Ah. I had a hunch that might be the case. However, that is not the > behavior that I am seeing. First, in response to your questions: (1) I > am on Linux (there are other platforms?); (2) I am using Python 2.3; > (3) it is difficult to extract a piece of the code, but I will attempt > to describe more clearly what I am doing. There is a button with a > handler. In the handler I use popen3 to launch a program that takes a > long time to execute. I monitor its progress in a while loop by > reading a status line that it produces on stderr. The status line > provides information about percentage complete; I use that information > to update the MessageBar in my GUI. When the status line indicates > that the process is done, I exit the while loop and return from the > button handler. I tried running update_idletasks on the MessageBar in > the while loop. I tried running it on the root window, even though the > information you provided indicated that it doesn't matter what class > owns the method -- and my experience certainly does not contradict that > statement. In every case, only the MessageBar updates. Well, that's > not entirely true. I also move a tag in a text widget; the previously > and newly tagged text redraws. The only technique I have found that > permits the main window to update is to run most of the handler in a > separate thread. The problem I am having with that approach is that > the MessageBar then flashes in an annoying way (the background seems to > go to white at every update and then gets redrawn to gray -- which > happens only when the while loop is in its own thread). Any other > thoughts would be much appreciated. I've been using a Tkinter filehandler for similar tasks and didn't have the problems you describe. Here's a pseudo-code snippet to illustrate what I did: from Tkinter import * import os, fcntl, popen2 def button_callback(self, event): #the function that's bound to the button #dialog window with progress bar: self.pw = ProgressWindow.ProgressWindow() selectedfiles = ' '.join(tracklist) normalizecmd = 'exec normalize -m ' + selectedfiles self.pp = popen2.Popen4(normalizecmd) self.mkfilehandler(self.pp, self.getprogress) def mkfilehandler(self, popen4object, function): #creates the filehandler fileobject = popen4object.fromchild filedescr = fileobject.fileno() fcntl.fcntl(filedescr, fcntl.F_SETFL, os.O_NONBLOCK) tkinter.createfilehandler(fileobject, READABLE, function) def getprogress(self, fileobject, event_type): message = self.pp.fromchild.read() if message == '': # process has finished # this could be checked with "if self.pp.poll() != -1:" either tkinter.deletefilehandler(self.pp.fromchild) <...clean up stuff here...> self.pp = None else: <...parse the output messages, extract progress values, etc....> # update the progress bar (update_idletasks() is called from it's set() method): self.pw.set(value=progress) I hope this helps Michael From winexpert at hotmail.com Mon May 17 14:51:02 2004 From: winexpert at hotmail.com (David Stockwell) Date: Mon, 17 May 2004 18:51:02 +0000 Subject: Generators: section 9.10 of the python tutorial Message-ID: <BAY2-F114VYDZPOmH1Y0001bbf2@hotmail.com> Hi Matteo, Thanks for the tip. The syntax seems a bit out there, but I'll definitely take a look and try that out too. Thanks again, David ------- Cell: http://cellphone.duneram.com/index.html Cam: http://www.duneram.com/cam/index.html Tax: http://www.duneram.com/index.html >From: Matteo Dell'Amico <della at toglimi.linux.it> >To: python-list at python.org >Subject: Re: Generators: section 9.10 of the python tutorial >Date: Thu, 13 May 2004 19:14:24 GMT > >David Stockwell wrote: > >>What does this error mean? Does it mean we can't use yield in our code? >>Is yield a form of a 'return' ?? >> >>class9.py:71: Warning: 'yield' will become a reserved keyword in the >>future >> File "class9.py", line 71 >> yield data[index] >> ^ >>SyntaxError: invalid syntax > >Yes, you can use yield. It's different from "return", but I guess I >couldn't explain it better then the tutorial. :-) >You are probably using python2.2. If you want to create generators, you >need this line at the start of your python program: > >from __future__ import generators > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page ? FREE download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ From usenet_spam at janc.invalid Mon May 17 21:43:43 2004 From: usenet_spam at janc.invalid (JanC) Date: Tue, 18 May 2004 01:43:43 GMT Subject: HTTP 1.1 pipelining References: <4860c084.0405170736.13c6e8b4@posting.google.com> <c8b30d$cc6$1@bagan.srce.hr> Message-ID: <Xns94ED25EE5B20FJanC@213.118.38.102> Ivan Voras <ivoras at __geri.cc.fer.hr> schreef: > I don't think this is how HTTP/1.1 pipelining works. It is still a > request-response protocol - the only "pipelining" is in the fact that it > doesn't require a separate connection session for each request-response > pair. "Pipelining" != "Connection: Keep-Alive" <http://www.mozilla.org/projects/netlib/http/pipelining-faq.html> -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From segphault at sbcglobal.net Sun May 23 10:28:22 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sun, 23 May 2004 14:28:22 GMT Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <pan.2004.05.23.14.24.47.540278@sbcglobal.net> On Sat, 22 May 2004 22:53:01 -0700, simo wrote: > One thing that might attract me from Python to Prothon is if it had > proper private medthods - i.e. not just name mangling like __myDef > which can be overridden using _myClass__myDef (as the interpreter > does). > > Proper encapsulation is needed before the C++ brigade will take > P[y/ro]thon seriously as an OO language, oh and a machinecode compiler > ;-) check out ruby. It is very similar to python, but one of the many benefits it has over python, is ability to distinguish 'real' private, public, and protected variables/methods. Ruby does not allow multiple inheritance, and it supports a very powerful mixin system- it's OO mechanisms and syntax generally seem better than pythons. I dont understand why everybody seems to want a machinecode compiler. It wont make a high-level, dynamically typed language run any faster. --SegPhault From greg at cosc.canterbury.ac.nz Wed May 12 22:50:09 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 13 May 2004 14:50:09 +1200 Subject: Unification of Methods and Functions In-Reply-To: <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405060737.bd43802@posting.google.com> <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> Message-ID: <2gg633F2cg0sU1@uni-berlin.de> David MacQuigg wrote: > I could give you an example from IC Design, but for the course I > teach, I chose to use a similar hierarchy based on something everyone > would understand - a taxonomy of animals. Nothing in this example is > something you wouldn't find in a real program to model an integrated > circuit. Perhaps it would be better to give these people examples based on actual parts of an integrated circuit, then? If they can see an immediate, realistic use for what you're teaching, they're likely to grasp and remember it more easily. Cats and mammals have the potential to be just as boring and artificial-seeming as parts and suppliers. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tismer at stackless.com Thu May 27 18:05:13 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 28 May 2004 00:05:13 +0200 Subject: Why a class when there will only be one instance? In-Reply-To: <20040527215637.GA2389@alcyon.progiciels-bpi.ca> References: <40B3E861.29B033D5@shaw.ca> <20040527215637.GA2389@alcyon.progiciels-bpi.ca> Message-ID: <40B66619.60108@stackless.com> Fran?ois Pinard wrote: ... > It would be `self.' within the class itself, and the instance name > within foreign classes. This habit stresses the relations between the > parts of the program and eases a better understanding of the whole. Just a little observation: If you really want the class and the instance to be the same, well, you can take a module. In a sense, this *is* a class and the only instance. ciao - chris -- Christian Tismer :^) <mailto:tismer at stackless.com> Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From j_mckitrick at bigfoot.com Tue May 4 17:59:18 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 4 May 2004 14:59:18 -0700 Subject: Growing database? References: <mailman.237.1083673970.25742.python-list@python.org> <qnkhduwccdg.fsf@arbutus.physics.mcmaster.ca> Message-ID: <ec6dce8b.0405041359.526b6fb6@posting.google.com> > Depends on what db module shelve uses for its backend. For instance, > gdbm won't shrink a database file unless you specifically tell it to, > so if you have a lot of deletions it will grow. > > Easiest way to fix it is to copy all the objects from your shelve to a > new shelve. That makes sense. I wasn't sure how deletions worked, but your idea is a good one. I'm currently running on FreeBSD, so I am using the bsddb backend. From johnathan_doe at fastmail.com.au Mon May 24 03:54:33 2004 From: johnathan_doe at fastmail.com.au (Johnathan Doe) Date: Mon, 24 May 2004 17:54:33 +1000 Subject: Issues in compiling Python to machine code In-Reply-To: <pan.2004.05.23.14.10.59.799318@sbcglobal.net> References: <40b089a5$0$16599$5a62ac22@freenews.iinet.net.au> <pan.2004.05.23.14.10.59.799318@sbcglobal.net> Message-ID: <40b1aa35$0$16606$5a62ac22@freenews.iinet.net.au> > we have talked about this here before, I think. Native compilation wont > improve runtime speed of a dynamically typed language. Despite this, there > are actually a few projects out there endevouring to do it anyway. If you > want better speed from a python application, try a customized python > runtime engine like Psyco. That might be a good idea actually, to investigate Psyco and others. I'm not interested in speeding up Python as such, I'm just interested in being able to write system-level software in Python. I would like to be able to write an OS in Python for instance. Johnathan From missive at frontiernet.net Tue May 4 16:22:38 2004 From: missive at frontiernet.net (Lee Harr) Date: Tue, 04 May 2004 20:22:38 GMT Subject: [off] Zope - Please help me ! Postgre DA Field Types References: <mailman.234.1083654938.25742.python-list@python.org> Message-ID: <iYSlc.3534$FZ3.1485@news02.roc.ny> On 2004-05-04, fowlertrainer at anonym.hu <fowlertrainer at anonym.hu> wrote: > Hello ! > > Hello ! > > I want to continue the my project. > http://www.zope.org/Members/fowlertrainer > > I need to get all of the base field types with postgresql da. > http://www.zope.org/Members/spinwing/ZSQL_Results > Not exactly what you are looking for but... http://www.postgresql.org/docs/7.4/static/datatype.html Or maybe you could get something from the information_schema http://www.postgresql.org/docs/7.4/static/information-schema.html http://www.postgresql.org/docs/7.4/static/infoschema-datatypes.html http://www.postgresql.org/docs/7.4/static/infoschema-columns.html Probably best to ask on one of the postgres lists. From alloydflanagan at comcast.net Fri May 14 16:31:30 2004 From: alloydflanagan at comcast.net (A. Lloyd Flanagan) Date: 14 May 2004 13:31:30 -0700 Subject: How do I start from python sth like "MyExe.exe InFile"? References: <28bcfc204dec5fe9060a7b0d1b0fba47@localhost.talkaboutprogramming.com> Message-ID: <e838aa6e.0405141231.78c470e7@posting.google.com> "questioner" <bstoyanov at dspace.de> wrote in message news:<28bcfc204dec5fe9060a7b0d1b0fba47 at localhost.talkaboutprogramming.com>... > Hi folks, > > Id appreciate if you can help: > I want to start an exe which takes as an argument filename. What I tried > was: > > os.spawnl(os.P_NOWAIT,('processor.exe'),'filename.ext')) > > I also tried: > os.execl(r'DRIVE:\WINNT\system32\cmd.exe', > '/k',('processor.exe'),'filename.ext')) > but is simply the command line and stopped. > However I didnt achieve the expected result and got some number like: > 788. Since you specified os.P_NOWAIT in the spawnl() call, it didn't return an exit code, but rather the process ID of the spawned process. If you were expecting the exit code, you should be using os.P_WAIT. Other than that, we could really use more detail to help us answer this question. What exactly did the system do and print when you made the call? What did you expect/want it to do? From SeeBelow at SeeBelow.Nut Wed May 5 00:30:03 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 05 May 2004 04:30:03 GMT Subject: question: parameters for create_polygon() method References: <40984D5A.B819BF28@shaw.ca> <mailman.254.1083723811.25742.python-list@python.org> Message-ID: <40986DD6.F06FF651@shaw.ca> Andrew Bennetts wrote: > > On Wed, May 05, 2004 at 02:11:28AM +0000, SeeBelow at SeeBelow.Nut wrote: > > Tkinter's canvas object has the method create_polygon(). > > > > The docs say the parameters should be like: > > (x1, y1, x2, y2, x3, y3, .....) > > > > But it's often much better programming practice to have a list of > > tuples, each point being a tuple, like this: > > [(x1, y1), (x2, y2), (x3, y3),......] > > > > Is there a good way to manipulate my polygons in the latter form, but > > still use create_polygon() to draw them? > > create_polygon(*list_of_points) > > -Andrew. Thanks Andrew, but I don't understand it. What's that * thing? Is there a * operator that converts a list of tuples into one big tuple? Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From mailinglist at ltsai.com Sun May 30 20:19:23 2004 From: mailinglist at ltsai.com (Tsai Li Ming) Date: Mon, 31 May 2004 08:19:23 +0800 Subject: Redirect stdout & stderr (similar to a daemon) In-Reply-To: <1085934830.617304@yasure> References: <40b9cd69@news.starhub.net.sg> <yXeuAls/K3XG089yn@the-wire.com> <1085934830.617304@yasure> Message-ID: <40ba7a0d@news.starhub.net.sg> Donn Cave wrote: > Quoth mwilson at the-wire.com (Mel Wilson): > | In article <40b9cd69 at news.starhub.net.sg>, > | Tsai Li Ming <mailinglist at ltsai.com> wrote: > ... > |> # Redirect standard file descriptors. > |> os.dup2(si.fileno(), sys.stdin.fileno()) > |> os.dup2(so.fileno(), sys.stdout.fileno()) > |> os.dup2(se.fileno(), sys.stderr.fileno()) > | > | These modify the actual file objects represented by > | 'sys.stdin', etc. There's no coming back from that. > > There is, if I understand what you meant by that. Consider > > old0 = os.dup(0) > os.dup2(si.fileno(), 0) > > The original input stream is held open on some arbitrary > unit, which you may use at any point to restore it to standard > input. > > os.dup2(old0, 0) > os.close(old0) > > Donn Cave, donn at drizzle.com Thanks Donn, Why is there a need to close old0? Because of the extra file handle? Liming From skip at pobox.com Fri May 14 14:29:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 May 2004 13:29:26 -0500 Subject: Troubles with CSV file In-Reply-To: <g2s9a017l29upq7ggc75pqqd3bv73eumi2@4ax.com> References: <mailman.8.1084529146.4157.python-list@python.org> <g2s9a017l29upq7ggc75pqqd3bv73eumi2@4ax.com> Message-ID: <16549.4102.815917.59893@montanaro.dyndns.org> Dennis> ""read this, man"", 1 Dennis> start---| Dennis> end------| ie, an empty quoted string Dennis> unquoted--^^^^^^^^^ Dennis> comma-split--------| Dennis> unquoted------------^^^^ Dennis> start-------------------| Dennis> end----------------------| another empty quoted string Dennis> comma-split---------------| Dennis> unquoted-------------------^^ I'm not sure what "correct" interpretation of this should be since no separator was placed after the first '""' and before the second. Given that the input is ill-defined, just about any output could be considered "valid". ;-) Skip From olivier.scalbert at algosyn.com Sun May 9 15:30:49 2004 From: olivier.scalbert at algosyn.com (Olivier Scalbert) Date: Sun, 09 May 2004 21:30:49 +0200 Subject: perl to python Message-ID: <409e86e9$0$22811$a0ced6e1@news.skynet.be> Hello , What is the python way of doing this : perl -pi -e 's/string1/string2/' file ? Thanks Olivier From moughanj at tcd.ie Tue May 11 21:54:56 2004 From: moughanj at tcd.ie (James Moughan) Date: 11 May 2004 18:54:56 -0700 Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405060737.bd43802@posting.google.com> <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> Message-ID: <16752bcc.0405111754.35d0838a@posting.google.com> Antoon Pardon <apardon at forel.vub.ac.be> wrote in message news:<slrnca10tf.1i9.apardon at trout.vub.ac.be>... > Op 2004-05-10, James Moughan schreef <moughanj at tcd.ie>: > > David MacQuigg <dmq at gain.com> wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... > >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: > >> > >> >David MacQuigg <dmq at gain.com> wrote in message news:<4a9o90pbu122npgf4m2hrgg04g2j0ic6ka at 4ax.com>... > >> >> On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: > <snip> > >> >> Also, if you are calling > >> >> a function that has an instance variable ( .length ) and no instance > >> >> has been set by a prior binding, you would need to set __self__ > >> >> manually. > >> >> __self__ = foo; print FooLen() > >> > > >> >???!!!??? > >> > > >> >This is what I was talking about in my first post, global variables > >> >which change depending on where you are in the code... as I understand > >> >what you're saying, __self__ will have to be set, then reset when a > >> >method is called from within a method and the exits. And __self__ > >> >could presumably be changed halfway through a method, too. I'm sorry, > >> >I don't see this as being more explicit or simpler. > >> > >> The setting of __self__ happens automatically, just like the setting > >> of the first argument in a call from an instance. The user doesn't > >> have to worry about it. > > > > Explicit is better than implicit, especially in getting people to > > understand things. :) > > I'm a bit sick of this argument. There is a lot om implicity > going on in python. if obj belongs to cls then obj.method() > is syntactic sugar for cls.method(obj). > Well, it is... and it isn't. ``method'' could be bound to cls, cls's super-class, or to obj itself. > That looks like > a big implicite way to handle things in python. You could look at it like that. I'd say it's a way of making code generic, and hiding the workings of a subsystem; lots of good things in Python wouldn't be possible without this type of abstraction. > Likewise all those magical methods to emulate numerical > types or containers or sequences or all ways that allow > the python programmer to do things implicitely throught > the use of operators instead of through explicitely calling > the desired method. > > If implicit is such a negative thing to be avoided whenever > possible, python would look a lot different and I probably > wouldn't be using it. Sure; you have to have some understood conventions. In effect that's all any higher-level programming language than assembler is. IMO, in the case in point, the explicit self makes OO easier to undersstand; YMMV, of course, as it does with Dave. :) From akhilesh at it.iitb.ac.in Sat May 15 16:08:17 2004 From: akhilesh at it.iitb.ac.in (Akhilesh S. Shirbhate) Date: 15 May 2004 13:08:17 -0700 Subject: ORBit-Python problem :( Message-ID: <789bf36d.0405151208.2f5886e6@posting.google.com> I wrote a small CORBA program and am using ORBit-python. The IDL file was as below: --------------------------- module MESSAGING { typedef sequence<string> msgLines; struct msg { string fr; string to; msgLines body; }; interface mail { void submit (in msg message); }; }; --------------------------------- The server program is as below: --------------------------------- #!/usr/bin/python import CORBA class mail: msg = 0 def submit(self, msg): print "Message Recieved from:", msg.fr print "Message for:", msg.to for line in msg.body: print line self.msgs = self.msgs + 1; print "Message Served: ", self.msgs CORBA.load_idl("msg.idl") CORBA.load_idl("/usr/share/idl/name-service.idl") orb = CORBA.ORB_init((), CORBA.ORB_ID) poa = orb.resolve_initial_references("RootPOA") servant = POA.MESSAGING.mail(mail()) poa.activate_object(servant) ref = poa.servant_to_reference(servant) open("./msg-server.ior","w").write(orb.object_to_string(ref)) print "Wrote IOR to file", orb.object_to_string(ref) poa.the_POAManager.activate() orb.run() --------------------------------- After running the program, it gives the following errors: --------------------------------- Traceback (innermost last): File "./msg-server.py", line 14, in ? CORBA.load_idl("msg.idl") AttributeError: load_idl --------------------------------- If I change the CORBA.load_idl to CORBA._load_idl then the error comes at some other place... Namely below: --------------------------------- Traceback (innermost last): File "./msg-server.py", line 20, in ? servant = POA.MESSAGING.mail(mail()) NameError: POA --------------------------------- The CORBA module is dynamically loaded from the following file: /usr/lib/python1.5/site-packages/CORBAmodule.so I have installed orbit-python-0.3.0-1 on my machine. Please help me out.. I need help desperately to run the server :(( Thanx in advance :) From tjreedy at udel.edu Fri May 21 15:54:50 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 15:54:50 -0400 Subject: terminological obscurity References: <L6erc.519686$Pk3.412259@pd7tw1no> Message-ID: <c8lmqc$kpd$1@sea.gmane.org> "Elaine Jackson" <elainejackson7355 at home.com> wrote in message news:L6erc.519686$Pk3.412259 at pd7tw1no... > Some questions from a curious monkey. > > All tuple methods are also list methods, and most list methods are also tuple > methods; among those that are NOT also tuple methods, there are exactly two > ('count' and 'index') that do not involve mutation. Is there any special reason > why they AREN'T also tuple methods? Is history a special reason? Once upon a time, (before 2.2) tuples (and some other types) had no methods. Those it now has are generic object and sequence methods. Guido did not add the two non-mutating list methods because he does not consider them needed for tuples. That is related to his view that tuples are for hetero and not for homo sequences. Others have made the same observation you did. Google might reveal more, or some posts might be on the PyDev archives. ################################################################# > A question about terminology ('namespace'): > > >>> prince=tuple() > >>> king=[prince] > >>> del prince > > At this point, does the object formerly known as prince belong to the namespace > implemented by globals()? I personally do not think of objects as 'belonging' to a namespace. They 'exist' in a separate 'dataspace' and get non-exclusively associated with 0 or more names in 0 or more namespaces. If the above is the complete program up to that point, then the empty tuple is not directly associated with 'king', the only remaining name, but is associated with the first slot of king, king[0]. So pick your answer or reformulate your question. > More generally, is there a terminological way to > distinguish between (1) a function from a set of names into a set of objects, a namespace > and (2) the aforementioned set of objects? a dataspace ################################################################# > Is there a handy noun that refers to sameness of identity in the same way that > 'equality' refers to sameness of value? identity > ('Identicalness' is pretty clumsy, and > 'identity' is confusing, since it already has a meaning that is closely related > but needs to be kept distinct.) English words sometimes have similar but distinct meanings. In brief, my dictionary says 'identity': 1. sameness; 2. individuality. ################################################################# > A question about terminology ('name'): > > Suppose X is a container that contains n items (incidentally, is 'items' the > right term?) Yes (which is to say, I use it all the time ;-). >and i in an integer with 0<=i<=n. Does " X[i] " count as a 'name'? Only allegorically in that it does identify an item. In an expression context, 'X[i]' is an expression. To the left of '=', it is a 'target': names are a subset of targets. 'name' is pretty strictly defined as <alpha> <alnum>*. There are proposals to expand the set but that is another thread (and controversy). Terry J. Reedy From dmq at gain.com Tue May 25 06:26:40 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 03:26:40 -0700 Subject: Unification of Methods and Functions References: <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <mailman.188.1085259396.6949.python-list@python.org> <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> <ukp4b01o1lfgh2h4b3e0qc40a9bc2ck30c@4ax.com> <slrncb65g7.o6k.apardon@trout.vub.ac.be> Message-ID: <un66b09rhhvkmopa4pqpogubids856pmvg@4ax.com> On 25 May 2004 09:46:46 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote: >Op 2004-05-24, David MacQuigg schreef <dmq at gain.com>: >> On Mon, 24 May 2004 14:39:11 +1200, Greg Ewing >><greg at cosc.canterbury.ac.nz> wrote: >>>We don't see static methods as clutter, because for the >>>most part we don't see them (i.e. we don't normally use >>>them). It would be no great loss if they were dropped, >>>too. >> >> I would see it as a loss. The next best alternative is to move the >> static method outside of the class, and that puts an arbitrary >> restriction on how I can structure my programs. If the person writing >> the program feels that the function belongs in the class, let's not >> say it can't be done because either a) The syntax doesn't allow it. or >> b) We assume he is wrong in thinking his function belongs inside his >> class. >> >> My perspective may be different, because I have not yet absorbed the >> Python traditions, and I don't have any instictive avoidance of static >> methods. > >I never felt the need for static methods, and I still don't think >of my self as having absorbed the python traditions. Maybe the >questions is, where do you get your instinct from to use static >methods? When I write methods in a class, some of them have instance variables, and some do not. Some have global variables. Some have both globals and instance variables. The methods without instance variables are "static methods". I have no instinct acquired from Java or some other language. I just write whatever method is needed for the task at hand. Saying I should avoid static methods seems to me like an arbitrary restriction. Class methods are a little different. I've never felt the need for one, although I just received a contribution from one of the readers of this thread - a program using class methods to solve the inventory problem in Animals_2. It seems to me that class methods provide syntax sugar for a very special need, while static methods provide a way to implement *any* method that doesn't require an instance variable. I may be not fully understanding the need for class methods. -- Dave From Chris.Hornberger at blackrock.com Wed May 12 15:50:14 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 15:50:14 -0400 Subject: Why is a None appearing in my output? Message-ID: <ABADC7F2A1794A4C94657344DC1050930648BB39@BRDEL-EXCH02.na.blkint.com> You're not returning a value, simply holding it or printing stuff out. Return your value inside the function call. Thusly: def SomeFunction( someVar ): returnVal = 0 # do stuff return returnVal -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of David Stockwell Sent: Wednesday, May 12, 2004 3:47 PM To: python-list at python.org Subject: Why is a None appearing in my output? Hello, I'm a fairly new user of python. I am going through the tutorial on the python.org website and observed a weird thing around the 6.0 modules area. (http://docs.python.org/tut/node8.html) My python version: Python 2.2.3 (#1, Feb 26 2004, 14:37:42) [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 I entered the following text into a 'module file' and saved it: def fib6(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b else: print "done b[",b,"], n[",n,"], a[", a,"]" print "fib6:", fib6(50), "---" print "next" I then run it and get the results: fib6: 1 1 2 3 5 8 13 21 34 done b[ 55 ], n[ 50 ], a[ 34 ] None --- next The question I'm having is what is causing the 'None' to print? The example tutorial doesn't have the None, but when I run I am seeing it and I do not see what causes that. I added the 'else on the while and the "---" stuff to try to figure out what the None means. but i have no clue ... Thanks David _________________________________________________________________ Getting married? Find tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married -- http://mail.python.org/mailman/listinfo/python-list From lbates at swamisoft.com Tue May 11 14:52:21 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 11 May 2004 13:52:21 -0500 Subject: Cash Register References: <d1bd056c.0405111032.3b2c411f@posting.google.com> Message-ID: <2a6dnVpE-sR5Tj7dRVn-vg@comcast.com> Let's see: 1) If user inputs text, program crashes (not good) Probably should use raw_input and put float() inside a try block. 2) I can't figure out how program ever stops (e.g. b is set to 1 and never reset to exit the while b!=0 loop). 3) Sales is mispelled in the last print statement 4) Use inplace incrementing (e.g. v+=s, s+=a) instead of s=s+a, v=v+s 5) What is t variable used for? Good Luck. "Ryan Q." <RQuinn15 at optonline.net> wrote in message news:d1bd056c.0405111032.3b2c411f at posting.google.com... > It works, i'm just posting it hoping someone could do better. > > print '' > print ' *** CASH REGISTER ***' > print ' PRESS 0 AND THEN ENTER TO TOTAL' > b = 1 > t = 0 > v = 0 > while b != 0: > a = 1 > s = 0 > print '' > while a != 0: > a = input(' ITEM $ ') > s = s + a > print ' TOTAL $',s > v = v + s > cash = input(' CASH $ ') > change = cash - s > print ' CHANGE $',change > print ' ' > print ' TOTAL SALES $ ',v From chuck at smtl.co.uk Fri May 28 06:02:03 2004 From: chuck at smtl.co.uk (Chuck Amadi) Date: Fri, 28 May 2004 11:02:03 +0100 Subject: a python script which will parse an email message Message-ID: <200405281002.i4SA23gr010678@sevenofnine.smtl.co.uk> Hi Skip and all . I have downloaded the module (mboxutils.py) from Spambayes project's mboxutils module: Thus created my script mailbox.py Had a look at especially the getmbox() function. And tried to use as So . #!/usr/bin/env python #Import statement used to import external modules import mboxutils #Existing file a Unix-style mailbox for msg in mboxutils.getmbox("/var/spool/mail/chucka"): print msg['subject'] print msg['body'] I need just the Subject and Body of the all mail messages in the above Mail folder Runs but no output So I know its' done something as when I use another user mailbox it produces an error permission denied . So basically how do I see the output result and thus I can process it to One File. Im digesting the mboxutils.py but I assume that as an external module I just load it using the import statement as above Cheers Chuck From donn at u.washington.edu Tue May 25 12:03:29 2004 From: donn at u.washington.edu (Donn Cave) Date: Tue, 25 May 2004 09:03:29 -0700 Subject: terminological obscurity References: <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> <1085378050.309299@yasure> <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <donn-F5877E.11513724052004@nntp1.u.washington.edu> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> Message-ID: <donn-10607D.09032925052004@nntp1.u.washington.edu> In article <1l25b0damv22nmja2na0i3k55e0p3jsef4 at 4ax.com>, Arthur <ajsiegel at optonline.com> wrote: ... > Well for one, before new style classes, it was easier to think of an > "instance" as in some sense a pseudo data type. Instances of > different classes - even with no hierarchical relationship - were more > conceptually homogenous. > > But with everything subclassable, 2 different classes, each derived > from object, are conceptually distinguished more similarly to the way > in which a str and int are distinguished. Really makes no difference at all - not just insignificant, really _no_ difference. A truly heterogeneous sequence may be full of references to the _same_ object (e.g., (1, 1, 1)), and a truly homogeneous sequence may have objects as different as None and a module. It's not about properties of the objects, considered in isolation. > GvR> I always think of the type of a list as "list of T" while I > GvR> think of a tuple's type as "tuple of length N with items of > GvR> types T1, T2, T3, ..., TN". So [1, 2] and [1, 2, 3] are both > GvR> "list of int" (and "list of Number" and "list of Object", of > GvR> course) while ("hello", 42) is a "2-tuple with items str and > GvR> int" and (42, "hello", 3.14) is a "3-tuple with items int, > GvR> str, float". > > He sort of stacks the cards by making his tuples of hetereogenous > type, and his list easily described as a list of T. And thereby > sidesteps all the ambiguities inherent in the ten word edict. Except > that at the Object level, we are at lists of Objects and tuples of > Objects. It detracts little from the point of the above quote, but > this quote then becomes substantially weaker as support for his 10 > worder. Guess he may have overestimated his audience. If you're interested in the history of this matter, it may help to know that Guido did not invent the tuple. It has been around in computer programming languages since Lisp. You can actually find precisely parallel descriptions of the concept in that context, down to the unnecessary use of different data types to emphasize the heterogeneity. Lisp and its relatives have both a tuple and a list type, but the list is a `real list', not a 1-dimension array as in Python but a recursive data structure. In Python, this data structure can be represented using a tuple: t = (0, None) t = (1, t) t = (2, t) ... def print_list(tail): value, tail = tail if tail: print_list(tail) print value Guido's "mistake" is that unification of all these sequence types leaves the distinctions less obvious. Donn Cave, donn at u.washington.edu From asdf at asdf.com Sun May 2 14:39:44 2004 From: asdf at asdf.com (asdf sdf) Date: Sun, 02 May 2004 18:39:44 GMT Subject: Newbe-books In-Reply-To: <O3Zkc.488$vz5.260@nwrdny01.gnilink.net> References: <Uldkc.29554$Qc.1128956@twister1.libero.it> <ekr2905p04fe3a667aejluqq4gb0fit5af@4ax.com> <O3Zkc.488$vz5.260@nwrdny01.gnilink.net> Message-ID: <Qfblc.59034$Jh7.50678@newssvr25.news.prodigy.com> > > Ditto. I learned from the tutorial and DejaNews. I bought _Programming > Python_, because I liked _Programming Perl_ so much, but I haven't had > much use for it. I'm evaluating _Learning Python_ as a training aid. > It's not bad, so far. I'll probably give it to our next hire. followup on my previous comment. in Learning Python, Lutz discusses Tkinter at some length. This is understandable for historical reasons, but wxPython would be the better choice. If LP had a couple of pages on threads and a useful discussion of wxPython, then Learning Python would totally rock! The sun is setting on Tkinter.) (are you out there, Mark? an idea for the third edition?) From greg at cosc.canterbury.ac.nz Wed May 19 21:03:48 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 20 May 2004 13:03:48 +1200 Subject: alternatives to making blocks like { } or other ?? In-Reply-To: <slrncalqqf.8f2.grante@grante.rivatek.com> References: <c8do0u$9fb$1@news.atman.pl> <jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com> <c8e5sh$109b$1@news.atman.pl> <slrncalqqf.8f2.grante@grante.rivatek.com> Message-ID: <2h2efmF7uqqaU1@uni-berlin.de> Grant Edwards wrote: > (he didn't know what recursion was, since BASIC > didn't have it) That's not quite true. Recursive GOSUBs worked fine in most versions of BASIC. There just weren't any local variables or parameter passing, making recursion somewhat awkward to use... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From apardon at forel.vub.ac.be Fri May 14 08:29:32 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 May 2004 12:29:32 GMT Subject: Unification of Methods and Functions References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <mmo7a0d17d0oigka5icevb9qj3ogudtvai@4ax.com> Message-ID: <slrnca9etd.1i9.apardon@trout.vub.ac.be> Op 2004-05-13, David MacQuigg schreef <dmq at gain.com>: > On Thu, 13 May 2004 10:56:58 -0400, "Terry Reedy" <tjreedy at udel.edu> > wrote: > >>"Antoon Pardon" <apardon at forel.vub.ac.be> wrote in message >>news:slrnca6d58.1i9.apardon at trout.vub.ac.be... >>> One could argue that all forms of methods and functions are unified. >>> It is just that python does some magic so that the method you >>> access from an object is not the actual function but the curried >>> function with the object. >> >>My view is similar: in Python, a method is a dressed up (wrapped) function. >>'Unification of methods and functions' reads to me like 'unification of >>dressed-up bodies and naked bodies'. What would that mean? > > By unification, I mean making the calling sequence identical for all > methods and functions. It already is. It is just that the function you have defined within the class, is not the function you call through the object. > No more special syntax for lambda functions, All right I understand that. > static methods, etc. No time wasted on these topics in a text like > Learning Python. A simpler presentation of OOP, based on what > students already know at this point - functions, modules, and global > variables. A method is just a function. The special calling form for methods is not object specific. With a little extra work you can have exactly the same calling form for classes with no methods. >>One thing I >>like about Python is that there is only function-body syntax and not a >>separate, slightly different method-body syntax. To me, having only one >>type of code body *is* unification. So it is hard for me to see what is >>being proposed. > > The one fundamental difference between methods and functions is the > presence of instance variables in methods. No it is not. The instance variables you speak of within a method are just the instance variables of a parameter. It can work just as well with a function that is written outside the class. you just need to wrap it somewhat if you want the same calling sequence but that is all and this wrapping can happen outside the class too. > You can hide that > difference with the self.var trick. You can hide it even further by > not using 'self', but some other word that looks just like the other > variable names in the function. None of this removes the actual > difference, or makes learning about instance variables any easier for > the student. Maybe you should start with classes without methods then. Just class Whatever: pass. Now you can make objects of this class, give them instance variables and write a function that expects a whatever object as first argument en let it play with the instance variables of the argument. If you wish you can call that first argument self it doesn't really matter. There is nothing method or function specific here. > The choice of how to identify instance variables is a minor issue. I > think it is actually better not to *hide* the instance variables, but > to *highlight* them. Ruby uses $var for instance variables. Prothon > uses a leading dot, which is quite visible in most code editors. > > The real issue is not self.var vs .var It is the complexity resulting > from having different calling sequences. There really aren't different calling sequences, just to different related function. Lets consider the two following functions. def addf(a, b): return a + b def addc(a): def addh(b): return a + b return addh Now you can use both to add two numbers, but the calling sequence will be different: You call addf(n1, n2), but you call addc(n1)(n2). The seconde is called the curried version of the first. Now if I know I will need to add 2 to al lot of numbers I can do the following: add2 = addc(2) and now when I need to add 2 to a number I can just call add2(n). So now I have a function that has the value 2 bound to it. In a way it has become a method of 2. We can do that even explicitly class Int(int): pass two = Int(2) add2 = addc(two) two.add = add2 >>> two, add2(5), two.add(6), addf(two, 7) (2, 7, 8, 9) The only thing that is happening is that if you write a function within a class, python transforms it into the curried version and does the rest of the things implicitely that I have done above explicitly. > Compare the 96-page > presentation of OOP in Learning Python, 2nd ed. to what I have written > at http://ece.arizona.edu/~edatools/Python/Prototypes.doc > In 7 pages, I can present the basics of OOP. Adding examples and > exercises will probably bring this to 30 pages. The key to this > simplification is not having to deal with unnecessary complexities, > like lambda functions, static methods, etc. > >>Introducing a syntax like '.var' that would only be >>meaningful in a method and not a function would be dis-unification. > > Actually, .var could be used in a function outside a class, just as > you can now use self.var in the current function syntax. Before using > a function with .var, the global variable __self__ must be set. This > is normally done by calling the function from an instance. Before > using a function with self.var, the first argument must be set. This > is normally done by calling the function fom an instance. > To say that adding an instance variable to a function breaks unity is > like saying that adding a global variable to a function breaks unity. It does in some sense. I also could have written the add2 function as follows self = 2 def add2(n): return self + n I don't think that would have been a good idea. Having __self__ being a global variable is disaster waiting to happen. What if a method calls another method, what if you use threads? > Adding an instance variable to a function simply makes the function > dependent on an external variable. Same with a global. But currently in python "self" is not an external variable, it is just the first argument of the function. Manipulating an argument is different from manipulating an external variable. -- Antoon Pardon From greg at cosc.canterbury.ac.nz Sun May 23 22:39:11 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 14:39:11 +1200 Subject: Unification of Methods and Functions In-Reply-To: <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> References: <16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><slrnca6d58.1i9.apardon@trout.vub.ac.be><mailman.516.1084460227.25742.python-list@python.org><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <mailman.188.1085259396.6949.python-list@python.org> <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> Message-ID: <2hd5ihFaefmmU1@uni-berlin.de> David MacQuigg wrote: > Nobody seems to understand that lambda functions, static methods, etc. > are clutter. On the contrary, lambda has long been regarded as a wart for various reasons. The best way to fix it is probably to just drop it altogether. Nothing essential would be lost. We don't see static methods as clutter, because for the most part we don't see them (i.e. we don't normally use them). It would be no great loss if they were dropped, too. In neither case is it necessary to fundamentally redesign the language to fix these, even if they are regarded as problems. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From fgeiger at datec.at Mon May 3 12:43:16 2004 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 3 May 2004 18:43:16 +0200 Subject: PyOpenGL demo in wxPython demo crashes References: <c74oir$jkt$1@newshispeed.ch> <fZqdnQpsEb2P3AvdRVn_iw@powergate.ca> <mailman.210.1083590542.25742.python-list@python.org> Message-ID: <c75ssn$c52$1@newshispeed.ch> Thank you, Mike, I installed Numarray 0.9 and that made the demo work (BTW, I had dropped glut32.dll into my system32, not glut.dll - sorry for that typo). Kind regards Franz "Mike C. Fletcher" <mcfletch at rogers.com> schrieb im Newsbeitrag news:mailman.210.1083590542.25742.python-list at python.org... > Try installing Numarray. When the 2.0.1.07 binary was built the > packager had Numarray installed, and for some god-unknown (and > frustrating) reason just having the package installed appears to create > a (pointless extra) dependency on Numarray when you link to Numpy. > > Everything else sounds fine, > Mike > > Peter Hansen wrote: > > > F. GEIGER wrote: > > > ... > > >> P.S.: Python 2.3.2 on Win2k, wxPython 2.4.2.4u, PyOpenGL (from > >> PyOpenGL-2.0.1.07.py2.3-numpy23.exe), glut.dll (from GLUT 3.7.6) > >> copied into > >> \WINNT\System32. > > > ... > > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ > > > From bart_nessux at hotmail.com Sat May 1 13:45:33 2004 From: bart_nessux at hotmail.com (bart_nessux) Date: Sat, 01 May 2004 13:45:33 -0400 Subject: calling functions at the same time In-Reply-To: <4093de02$0$17252$a1866201@newsreader.visi.com> References: <c6udda$qpv$1@solaris.cc.vt.edu> <1095ijdb5jotvf1@corp.supernews.com> <c6unuq$d0f$1@solaris.cc.vt.edu> <kNIkc.1367$U75.564@edtnps89> <4093d389$0$17262$a1866201@newsreader.visi.com> <r4idnSA-J8HtSw7dRVn-hQ@powergate.ca> <4093de02$0$17252$a1866201@newsreader.visi.com> Message-ID: <c70nom$c2n$1@solaris.cc.vt.edu> Grant Edwards wrote: > In article <r4idnSA-J8HtSw7dRVn-hQ at powergate.ca>, Peter Hansen wrote: > > >>>>You can't get greater then 1ms accuracy when measuring a time >>>>on todays machines, and that will be less when measuring time >>>>over a network... >>> >>>Not sure what you mean by "todays machines", but on a >>>Pentium-class machine running Linux, you get approx 1us >>>resolution with calls to time.time(): >> >>Keep in mind the difference between "accuracy" and >>"resolution" (or "precision"). > > > I do. > > Not only do you get 1us resolution, you get packet timestamp > _accuracy_ to well under 1ms according to tests I've run > comparing packet timestamps against an oscilloscope trace. > > Delta-T accuracy of calls to time() are accurate to 1us as > well. Absolute accuracy depends on how you set your system > clock. Running NTP with in-kernel FLL control of the system > tick will generally allow you to maintain absolute accuracies > of under 100us. > > >>I think Knio is probably right that, unless you are running on >>a realtime OS, you won't be able to guarantee anything better >>than 1ms accuracy, and quite probably not even that. > > > Under Linux, I can guarantee you the answer you get back from > time.time() is accurate to 1us. However, it is a multitasking > system, and there are other things running. While it's easy to > _determine_ exactly when you called time.time(), it's difficult > to _control_ the point in time when you call time.time(). When > your task does get a chance to run, and you do get to call > time.time(), you'll generally get a result accurate to 1us. > > If I do a busy-wait loop with nothing else running, I've been > able to accurately measure pulsewidths of a few microseconds > under Linux using the gettimeofday() call (which I believe is > what time.time() calls. > > As soon as there are other ready tasks, the accuracy of the > measurement quickly deteriorates to tens of millisconds due to > scheduling latencies. > Thanks to all for the tips and advice. I experimented with threading... it works, but I don't fully understand it so I'm not using it. I ended up using ntp on 4 hosts (side by side on the network) to do the pings. I wrote some socket server/client scripts so that all four hosts can start pinging together. I understand this approach and it's working well. Thanks again, Bart From NAVMSE-EXCHANGESERVER at meier-ag.ch Mon May 3 00:06:03 2004 From: NAVMSE-EXCHANGESERVER at meier-ag.ch (NAV for Microsoft Exchange-EXCHANGESERVER) Date: Mon, 3 May 2004 06:06:03 +0200 Subject: Norton AntiVirus detected and quarantined a virus in a message yo u sent. Message-ID: <4DB0D2D59DFF1C4B98C8ECF23DA5F2BA04BF76@exchangeserver.intern.meier-ag.ch> Recipient of the infected attachment: Eichenberger K?thi\Inbox Subject of the message: Mail System (info at meier-ag.ch) One or more attachments were quarantined. Attachment data30326.zip was Quarantined for the following reasons: Virus W32.Netsky.Q at mm was found in message.eml .scr. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1853 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040503/e858a628/attachment.bin> From gerrit.muller at embeddedsystems.nl Fri May 7 02:07:15 2004 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Fri, 07 May 2004 08:07:15 +0200 Subject: Python Resources In-Reply-To: <109l91isml27qe4@corp.supernews.com> References: <109l91isml27qe4@corp.supernews.com> Message-ID: <c7f92j$hb5$1@news.tue.nl> Oten > > if you have Python Links in your favourites Post them as well > http://www.extra.research.philips.com/natlab/sysarch/PythonLinks.html > > Someone who loves Python > but it would be nice to have your e-mail address in human readable format. In that way you would get the answers directly, without getting a lot of near emtpy messages in this newsgroup. regards, Gerrit -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From lf.van.geest at quicknet.nl Sun May 30 10:47:04 2004 From: lf.van.geest at quicknet.nl (Leo) Date: 30 May 2004 07:47:04 -0700 Subject: Show the review state of an item in Plone Message-ID: <e5f09805.0405300647.77feccf@posting.google.com> I have the following problem: When looking at a document, we would like to see what the review state of that document is. I set out to make a custom document_view page template based on the default page template, together with some code from the folder_contents page template. I got the following code from folder_contents: <td class="private" tal:define="review_state python:getInfoFor(item, 'review_state', '')" tal:content="structure python:test(review_state, review_state, ' ')" tal:attributes="class python:test(review_state, 'state-'+review_state, 'state-private')" i18n:translate="">  </td> and pasted somewhere after the H1 of the document_view page template to read: <h2 tal:define="review_state python:getInfoFor(here, 'review_state', '')" tal:content="structure python:test(review_state, review_state, ' ')" tal:attributes="class python:test(review_state, 'state-'+review_state, 'state-private')" i18n:translate="">  </h2> that is, I changed the 'td' to 'h2' and 'item' to 'here'. After saving the customized page template and navigating to a document in Plone I got the following error: Site error This site encountered an error trying to fulfill your request. The errors were: Error Type NameError Error Value name 'getInfoFor' is not defined Request made at 2004/05/30 16:44:04.453 GMT+2 I am using Plone 2 (the Windows binary distribution). Any help is apreciated. Leo. From usr at bin.com Sun May 16 05:34:24 2004 From: usr at bin.com (Josh Gilbert) Date: Sun, 16 May 2004 05:34:24 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> <du7hdum415y.fsf@amadeus.cc.tut.fi> <slrnca3t0e.2asc.kirk@eyegor.jobsluder.net> <Xns94E78860DF4B5duncanrcpcouk@127.0.0.1> <8gisf1ihvc.fsf@galapagos.bx.psu.edu> <flEoc.18388$V97.9433@newsread1.news.pas.earthlink.net> <8g4qqik8zd.fsf@galapagos.bx.psu.edu> <Iahpc.1023$H_3.264@newsread1.news.pas.earthlink.net> Message-ID: <c87ckl$3baqt$1@swen.emba.uvm.edu> It's in the python man page: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xread-lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. When I use sys.stdin.readline I don't need to use to -u flag. You can also use raw_input() to get data from stdin. This also appears to strip out the newline. Josh Gilbert. Andrew Dalke wrote: > Scott Schwartz >> No effect, because that's not the problem. > > Ahh, you're right. I keyword matched "buffer" and thought you meant > the system buffer and not Python's. > > Andrew > dalke at dalkescientific.com From me at privacy.net Wed May 5 16:12:56 2004 From: me at privacy.net (Alejandro =?iso-8859-1?Q?L=F3pez-Valencia?=) Date: 5 May 2004 20:12:56 GMT Subject: VIM and tab to space migration References: <c5bg1k$25vq$1@news.wplus.net> <c5c138$i91$1@news.service.uci.edu> <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <mailman.266.1083757569.25742.python-list@python.org> <40992866$0$12738$636a15ce@news.free.fr> <mailman.279.1083781602.25742.python-list@python.org> <c7bh99$239b8$1@ID-99513.news.uni-berlin.de> Message-ID: <c7bhs5$244vb$1@ID-99513.news.uni-berlin.de> On 2004-05-05, Alejandro L?pez-Valencia wrote in <c7bh99$239b8$1 at ID-99513.news.uni-berlin.de>: > On 2004-05-05, Brian Quinlan wrote in <mailman.279.1083781602.25742.python-list at python.org>: >> Christophe Cavalaria wrote: >> >>> Try adding that line at the end of each modified file : >>> >>> # vim:sw=4:softtabstop=4:expandtab >>> >>> It tells vim all the commands it should automatically run when it opens the >>> file and it should get you the correct behaviour for 4 spaces no tab >>> indentation. >> >> Thanks for the suggestion but modifying all my files is a pretty ugly >> solution. Not that I'm above using it if there is no better way :-) > I use these settings myself, but just now after posting, I realized that it is far better to set the preferences on a per-buffer basis, so I change my advice to the following: $ mkdir -p .vim/ftplugin $ cd .vim/ftplugin $ vim python_pep8.vim .... $ cat python_pep8.vim if exists("b:did_python_pep8") finish else let b:did_python_pep8=1 endif set tabstop=4 set shiftwidth=4 set softtabstop=4 set expandtab set textwidth=80 This way, you can open a python file and a file with a different syntax on two buffers of the same vim session. And this is *really* all there is to it. Cheers -- Alejandro L?pez-Valencia qenqhy ng rgo qbg arg qbg pb http://dradul.tripod.com/ The limits of my language are the limits of my world. (L. Wittgenstein) From tismer at stackless.com Thu May 27 21:37:13 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 28 May 2004 03:37:13 +0200 Subject: Why a class when there will only be one instance? In-Reply-To: <KPENJIMKHJPNKOLFIHBNOEMMCKAA.vineet@eswap.com> References: <KPENJIMKHJPNKOLFIHBNOEMMCKAA.vineet@eswap.com> Message-ID: <40B697C9.4020806@stackless.com> Vineet Jain wrote: >>Just keep track of the state you want to preserve and >>you want to re-initialise, and then call the different parts >>from outside. Easy. > > > If I went with just functions and not classes then I could pass > a variable (class instance) which can be used by users to store some > state information between calls. I would also use the same variable to > expose global variables. Even simpler. Please see the compile.__doc__ You compile the code, and then you execute it with the exec statement. Simplest apporach: You have a file, and you use execfile (see its doc) then you can execfile(filename, globals, locals), so you just pass the dict which is used as the globals. Before executing, you put a special version of __builtins__ into the globals dict, and you select only builtin functions that you want to allow, or customized versions. This is rather safe. At least, a novice programmer cannot break through, easily. > How would you write a custom evaluator? > Is the evaluator that comes with python written in c? > How difficult would it be? Absolutely simple. Just use what Python has, and remove some builtins :-) > How can I restrict the code that the user can run so that he can write > only to his sub directory and that he does not crash the system somehow? See above, start with execfile. Later, you can refine, after you got more used to this. You build a customized __builtins__ module. You insert that into a fresh dict for the globals. Then you execfile the user's code in that, and pick the results he left in the globals. > Thanks for your help. You're welcome. I think you are set -- chris -- Christian Tismer :^) <mailto:tismer at stackless.com> Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jens-nospam at t-online.de Tue May 25 12:47:21 2004 From: jens-nospam at t-online.de (Jens Lippmann) Date: Tue, 25 May 2004 18:47:21 +0200 Subject: Slice assignment for strings? References: <c8vre2$ruk$04$1@news.t-online.com> <10b6t4hi6t1kjdb@news.supernews.com> Message-ID: <c8vt59$cru$00$1@news.t-online.com> > Strings are immutable objects, so you can't change them in > any way. ok, thanks! From j_mckitrick at bigfoot.com Sat May 22 17:32:59 2004 From: j_mckitrick at bigfoot.com (j_mckitrick) Date: 22 May 2004 14:32:59 -0700 Subject: Problem with PyGTK/Glade2 ComboBox vs ComboEntryBox References: <ec6dce8b.0405211022.7e5ba4b@posting.google.com> <40AF5FDD.7030604@draigBrady.com> Message-ID: <ec6dce8b.0405221332.65ddfed0@posting.google.com> > Ah this has changed in gtk 2.4 > http://developer.gnome.org/doc/API/2.2/gtk/gtk-migrating-GtkComboBox.html > The docs on pygtk.org are out of date, mutter... > Are you sure (your) pygtk supports the newer model? I have no idea. I have what I believe to be the latest pygtk - 2.2.0. This has been frustrating me for a while. Is there a workaround? From rick.ratzel at scd.magma-da.com Thu May 6 16:58:27 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Thu, 06 May 2004 15:58:27 -0500 Subject: changing exceptions in C code In-Reply-To: <mailman.325.1083870464.25742.python-list@python.org> References: <mailman.325.1083870464.25742.python-list@python.org> Message-ID: <409aa6f3$0$46510$39cecf19@news.twtelecom.net> If you're simply interested in adding info to the printed traceback, then this would be easier: result = PyObject_CallObject(callable, arglist); if (!result) { fprintf(stderr, "(in callback)"); PyErr_Print(); } PyErr_Print() is just printing to stderr...you should be able to do the same. If you're really needing to prepend to the actual traceback object though, then your approach is probably the way to go. -Rick Ratzel Thomas Heller wrote: > I'm calling into Python code from C with PyObject_CallObject(). If the > python function raises an exception, the above code returns NULL, and I > want to print out the exception with PyErr_Print(). > > For whatever reasons, I want to prepend a short string "(in callback)" > to the error message itself: > > result = PyObject_CallObject(callable, arglist); > if (!result) { > Extend_Error_Info("(in callback)"); > PyErr_Print(); > } > > I figured out this code for the Extend_Error_Info function: > > void Extend_Error_Info(char *fmt, ...) > { > va_list vargs; > PyObject *tp, *v, *tb, *s; > > va_start(vargs, fmt); > s = PyString_FromFormatV(fmt, vargs); > va_end(vargs); > if (!s) > return; > > PyErr_Fetch(&tp, &v, &tb); > PyErr_NormalizeException(&tp, &v, &tb); > PyString_ConcatAndDel(&s, PyObject_Str(v)); > Py_DECREF(v); > PyErr_Restore(tp, s, tb); > } > > Does this look ok by the experts? > > TIA, > > Thomas > > From fowlertrainer at anonym.hu Thu May 27 08:10:47 2004 From: fowlertrainer at anonym.hu (fowlertrainer at anonym.hu) Date: Thu, 27 May 2004 14:10:47 +0200 Subject: How to define a name of attachment in email with python ? In-Reply-To: <40B5C4EF.4050303@anonym.hu> References: <40B5C4EF.4050303@anonym.hu> Message-ID: <40B5DAC7.9010909@anonym.hu> fowlertrainer at anonym.hu wrote: > I want to set the name of the attachment in an python-generated email. > > This is needed, because the another site we want to get this name, and > repack the attachments by name (an ID). > > Some programming languges (components) are allow to set this. > (See Delphi/Indy/MessagePart) > > fp=open(plist[i], 'rb') > mdata=MIMEAudio(fp.read(),'mpeg') > fp.close() > msg.attach(mdata) > ???? msg['filename']='xxx' > > Can anyone help in this problem ? > > Thanx for it: > FT > I help to me - I found some information in Delphi mail headers :-) : The solution is this: fp=open(sf, 'r') mdata=MIMEText(fp.read(),'plain','iso-8859-2') fp.close() mdata.add_header('content-disposition', 'attachment', filename=GetFileName(sf)) msg.attach(mdata) Thanx for me. FT From Mike at DeleteThis.Geary.com Wed May 12 12:00:34 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Wed, 12 May 2004 09:00:34 -0700 Subject: How to batch download files from web page? References: <wyioc.26539$DI7.25553@newssvr22.news.prodigy.com> Message-ID: <10a4ih314jb1031@corp.supernews.com> > I wish to download hundreds of files from the University of Iowa > sound archive. Doing it manually would be a daunting task > especially since the files are each a few mega bytes long. Is there > a standard way of using Python for such a task? I have a fair > amount of programming experiance but very little of it relates > to networks. > > For those who are intrested the University of Iowa's sound archive > may be found at http://theremin.music.uiowa.edu/MIS.html The easiest way to download the individual files is with urllib.urlretrieve(). You can parse the HTML files using either htmllib.HTMLParser or the HTMLParser module, combined with urllib.urlopen(). If you do this Google search: urlopen htmlparser The first several matches have some nice code samples showing how to find the links in a web page. Add urlretrieve() to download the files and you'll be off and running. -Mike From slawek at cs.lth.se Sun May 23 06:11:17 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Sun, 23 May 2004 12:11:17 +0200 Subject: Freeze and Resume execution In-Reply-To: <20040523101619.GH1916@zoran.com> References: <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> <20040523101619.GH1916@zoran.com> Message-ID: <20040523115548.DF2E.SLAWEK@cs.lth.se> On Sun, 23 May 2004 12:16:20 +0200 "Miki Tebeka" <miki.tebeka at zoran.com> wrote: #>>> I'd like to use generators but can't see any "nice" way of doing #>>> it. #>> That would be the approach I would take. What can't you see with #>> using yield this way? #> The output function is way down the call stack. The function that #> handles the "freezing" and need to be saved is about 3-5 stack #> frames up (depends on the scenario). #> Propagating the output return value all the way back is tedious and #> error prone. This is why I'd like to use raise/catch and not "if #> error ..." I must admit I don't really understand what your problem is, so my solution may not be what you are looking for. However, maybe it will be useful: ********************************************************************** def generator(): i = 0 while 1: i += 1 yield i class A: def __init__(self): self.gen = generator() def work(self): i = 0 while True: print self.gen.next() i += 1 if i > 5: raise ValueError a = A() def x(): a.work() def y(): x() def z(): for i in range(5): try: y() except ValueError: print "do something with this exception" ********************************************************************** -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Get the facts first - you can distort them later! From peter at engcorp.com Wed May 12 23:48:56 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 May 2004 23:48:56 -0400 Subject: Google and Python usage In-Reply-To: <qnkk6zhujsb.fsf@arbutus.physics.mcmaster.ca> References: <qnkk6zhujsb.fsf@arbutus.physics.mcmaster.ca> Message-ID: <t62dndgNZ6u3bT_dRVn-hA@powergate.ca> David M. Cooke wrote: > Everybody says Google uses Python, but I've never seen it... until I > came across this, for the Google AdWords support page: > > https://adwords.google.com/support/bin/topic.py?topic=102 > > Is that a .py I spy? I guess so, but in any case the usual use of Python attributed to Google is not something you *would* see, as it's always been said to be on the back end, collecting and indexing the sites in the first place, not on the front end. Nice to see their use of it is growing even beyond that... -Peter From maney at pobox.com Mon May 10 13:17:31 2004 From: maney at pobox.com (Martin Maney) Date: Mon, 10 May 2004 17:17:31 +0000 (UTC) Subject: Is Perl *that* good? References: <c6ich0$c5mee$1@ID-205437.news.uni-berlin.de> <iL3jc.232$Yc.2330@news4.e.nsc.no> <108q51j4dscn7dc@corp.supernews.com> <knbjc.267$id.3998@news2.e.nsc.no> <pan.2004.04.26.20.50.19.843510@hotmail.com> <87fzaqmm8t.fsf@strauser.com> <38ec68a6.0404262308.50029919@posting.google.com> <mailman.49.1083084698.25742.python-list@python.org> <pan.2004.04.27.18.15.56.169064@hotmail.com> <noydnQuaxutgNxPdRVn-hw@powergate.ca> <roy-55BC22.15022827042004@reader2.panix.com> <yuqdnUy5QZcuOxLdRVn-vg@powergate.ca> Message-ID: <c7odfb$b9p$1@wheel2.two14.net> Peter Hansen <peter at engcorp.com> wrote: > This is actually the first time in recent years that I can recall > that someone has complained about having to make up a new variable > (which is as good as free) to hold the result of a match. If That's an odd way of characterizing it, since this is one of the common forms of the FAQ more often discussed in terms of assignment-as-operator, which used to come up about every week or so back when I had the time to read more than an eclectic sampling of the traffic here. The throwaway wrapper class is probably the least bad solution - at least it can be used in thread-safe manner (1), unlike one simply awful hack that's in the cookbook. (1) use it as a wrapper that's instaniated locally and not shared, which is the closest analog of how the code would go if operator= were available, IMO&E. The bloody awful cookbook recipie is the one that gains a little more convenience at the cost of a single globally shared hidden variable. -- Self-pity can make one weep, as can onions. -- Fodor From Joseph.V.Laughlin at boeing.com Mon May 10 14:18:00 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Mon, 10 May 2004 11:18:00 -0700 Subject: polymorphism w/out signatures? Message-ID: <67B3A7DA6591BE439001F273623335120287722E@xch-nw-28.nw.nos.boeing.com> Knuth. Joe Laughlin > -----Original Message----- > From: Roy Smith [mailto:roy at panix.com] > Sent: Monday, May 10, 2004 11:12 AM > To: python-list at python.org > Subject: Re: polymorphism w/out signatures? > > > Peter Hansen <peter at engcorp.com> wrote: > > Or is there some way that the following code can > > possibly fail with a TypeError, for any reason > > whatsoever? > > > > someName = [someName] > > It's a bit contrived (and also not exactly what you asked for), but > consider something like: > > class foo: > def __getattr__ (self, name): > return 1 + "" > > def barf (self): > self.someName = [self.someName] > > f = foo () > f.barf () > > which produces this when you run it: > > Roy-Smiths-Computer:tmp$ ./try.py > Traceback (most recent call last): > File "./try.py", line 11, in ? > f.barf () > File "./try.py", line 8, in barf > self.someName = [self.someName] > File "./try.py", line 5, in __getattr__ > return 1 + "" > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > The general point is that when catching exceptions, it's > usually best to > include as little code in the try block as you can, to make > sure you're > catching the exception you think you are. Especially in a highly > dynamic language like Python, it's sometimes difficult to > think of all > the possible ways code can fail. > > Was it Knuth who said, "I've only proven that my program is > correct, I > havn't actually tested it"? Or was that Dijkstra? > -- > http://mail.python.org/mailman/listinfo/python-list > From cookedm+news at physics.mcmaster.ca Mon May 17 16:42:15 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 17 May 2004 16:42:15 -0400 Subject: Sqlite syntax References: <mailman.17.1084816067.6949.python-list@python.org> Message-ID: <qnkfz9yzsyg.fsf@arbutus.physics.mcmaster.ca> At some point, "firephreek" <firephreek at earthlink.net> wrote: > Is there some documentation out there that actually lists the Sqlite > syntax? You mean the SQL dialect it speaks? http://sqlite.org/lang.html > Or even better, one that crosses over and talks about how it works with > python? Like all the other DB interfaces. See the pysqlite homepage for specifics. > Sqlite seems quite the nifty little thing, but for some reason, I can't > seem to get a list of tables in my databases through a python > prompt. >From http://sqlite.org/lang.html#createtable, all the tables are listed in the sqlite_master table, so >>> import sqlite >>> cx = sqlite.connect("db") >>> cu = cx.cursor() >>> cu.execute('''SELECT * FROM sqlite_master''') [('table', 'TEST', 'TEST', 3, 'CREATE TABLE TEST (V VARCHAR, I INTEGER)')] > And since the databases aren't 'centralized' there's no way of knowing > what databases I have floating around is there? Use 'ls' :-). Each database is a separate file. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From me at privacy.net Wed May 26 07:47:24 2004 From: me at privacy.net (Duncan Booth) Date: 26 May 2004 11:47:24 GMT Subject: Cleaner idiom for text processing? References: <f2403000.0405251739.2a77b11d@posting.google.com> <c91got$vpi$00$1@news.t-online.com> <Xns94F559D4C3451duncanrcpcouk@127.0.0.1> <c91pft$rl0$04$1@news.t-online.com> Message-ID: <Xns94F5821692826duncanrcpcouk@127.0.0.1> Peter Otten <__peter__ at web.de> wrote in news:c91pft$rl0$04$1 at news.t-online.com: >> However, I'm not sure I trust either of these solutions. I know that >> intuitively it would seem that both zip and izip should act in this >> way, but is the order of consuming the inputs actually guaranteed >> anywhere? > > I think an optimization that changes the order assumed above would be > *really* weird. When passing around an iterator, you could never be > sure whether the previous consumer just read 10 items ahead for > efficiency reasons. Allowing such optimizations would in effect limit > iterators to for loops. Moreover, the calling function has no way of > knowing whether that would really be efficient as the first iterator > might take a looong time to yield the next value while the second > could just throw a StopIteration. If a way around this is ever found, > checking izip()'s arguments for identity is only a minor complication. > What happens if someone works out that izip can be made much faster by consuming its iterators from right to left instead of left to right? That isn't nearly as far fetched as reading ahead. Passing the same iterator multiple times to izip is a pretty neat idea, but I would still be happier if the documentation explicitly stated that it consumes its arguments left to right. From danb_83 at yahoo.com Sun May 23 18:07:22 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 May 2004 15:07:22 -0700 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: <ad052e5c.0405231407.37ddba21@posting.google.com> wjb131 at web.de (Wolfgang Buechel) wrote in message news:<4629559b.0405101330.286ddb32 at posting.google.com>... > Hi, > > I want to iterate over all 2x2 matrices with elements in range 0..25 > (crypto-stuff). > > To produce them, first I wrote a fourfold nested for loop: ... > Then I had a look in comp.lang.python and found: > > > for (a,b,c,d) in [(x,y,z,t) for x in range(M) > for y in range(M) > for z in range(M) > for t in range(M)] : > matr = [[a,b],[c,d]] This may be shorter, but it's slower. Your old code took "only" 1.5 seconds to run on this computer, but the new way takes 3.5 seconds. What you *can* do to make your code faster (if you don't change matr once it's created) is to precompute the 676 possible matrix rows. ELEMENT_RANGE = range(26) MATRIX_ROWS = [[x, y] for x in ELEMENT_RANGE for y in ELEMENT_RANGE] for row1 in MATRIX_ROWS: for row2 in MATRIX_ROWS: matr = [row1, row2] That takes only 532 ms -- almost 3 times faster than the original. From lutz-horn at web.de Wed May 26 10:34:00 2004 From: lutz-horn at web.de (Lutz Horn) Date: Wed, 26 May 2004 16:34:00 +0200 Subject: Saving recursive objects to disc. cPickle wan't work. References: <20040526142220.GA2289@matijek.v10a.ath.cx> Message-ID: <os929c.a64.ln@subdomain.example.com> Hi, * Alex Polite <m4 at polite.se> [26 May 2004 14:22:21 GMT]: > I need to put recursive data structures on disc and found out that > cPickle doesn't like recursion. Hm, the documentation of Python 2.3.2, Section 3.14.1 "Relationship to other Python modules" states that recursive objects, which are defined as "objects that contain references to themselves" can't be handled by marshal, but that pickle and cPickle should be fine: "pickle stores such objects only once, and ensures that all other references point to the master copy". What exactly are your problems? Regards Lutz -- pub 1024D/6EBDA359 1999-09-20 Lutz Horn <lutz-horn at web.de> Key fingerprint = 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 sub 2048g/EA8CFEDE 2000-03-09 From apardon at forel.vub.ac.be Tue May 11 03:41:34 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 May 2004 07:41:34 GMT Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405060737.bd43802@posting.google.com> <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> Message-ID: <slrnca10tf.1i9.apardon@trout.vub.ac.be> Op 2004-05-10, James Moughan schreef <moughanj at tcd.ie>: > David MacQuigg <dmq at gain.com> wrote in message news:<889t90tdl9o9t25cv5dj6k5rnktuce0jin at 4ax.com>... >> On 8 May 2004 07:07:09 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >> >David MacQuigg <dmq at gain.com> wrote in message news:<4a9o90pbu122npgf4m2hrgg04g2j0ic6ka at 4ax.com>... >> >> On 7 May 2004 06:31:51 -0700, moughanj at tcd.ie (James Moughan) wrote: >> <snip> >> >> Also, if you are calling >> >> a function that has an instance variable ( .length ) and no instance >> >> has been set by a prior binding, you would need to set __self__ >> >> manually. >> >> __self__ = foo; print FooLen() >> > >> >???!!!??? >> > >> >This is what I was talking about in my first post, global variables >> >which change depending on where you are in the code... as I understand >> >what you're saying, __self__ will have to be set, then reset when a >> >method is called from within a method and the exits. And __self__ >> >could presumably be changed halfway through a method, too. I'm sorry, >> >I don't see this as being more explicit or simpler. >> >> The setting of __self__ happens automatically, just like the setting >> of the first argument in a call from an instance. The user doesn't >> have to worry about it. > > Explicit is better than implicit, especially in getting people to > understand things. :) I'm a bit sick of this argument. There is a lot om implicity going on in python. if obj belongs to cls then obj.method() is syntactic sugar for cls.method(obj). That looks like a big implicite way to handle things in python. Likewise all those magical methods to emulate numerical types or containers or sequences or all ways that allow the python programmer to do things implicitely throught the use of operators instead of through explicitely calling the desired method. If implicit is such a negative thing to be avoided whenever possible, python would look a lot different and I probably wouldn't be using it. -- Antoon Pardon From valia02004 at yahoo.fr Fri May 14 10:02:09 2004 From: valia02004 at yahoo.fr (Valia) Date: 14 May 2004 07:02:09 -0700 Subject: is it a daemon? how to create such a thing... Message-ID: <b8470501.0405140602.4e1a9712@posting.google.com> hello all, here is something i would like to do, i think this can be done with a daemon or something like named pipe or even a daemon waiting its input from named pipe? do not know. please can you help me and tell is this a good way to do it ? and also maybeme some starting points (it is still too confused for me to google anything) or simple examples. - i have a huge pairs list, (a python dict), some kind of replacements[a] -> 'a value', - i had small scripts that use this 'replacements dict' to do many processing, by now they all read(line) it at each execution. but it is far too slow for my needs. so i wonder if i could have some kind of process/script which would load this list once and then wait for the smaller scripts theirs queries about replacements pairs and answer them. i imagine this have to do with daemon programming but i'm brand new to it, and also i just need the simpler piece of code to do that (it is for a quick experiment, my aim is not to create an apache server framework :) ) (and i'm only concerned by a linux version) From chris.cavalaria at free.fr Fri May 14 15:55:01 2004 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Fri, 14 May 2004 21:55:01 +0200 Subject: PEP: import version References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> Message-ID: <40a52416$0$22119$636a15ce@news.free.fr> Manlio Perillo wrote: > Hi. > I'm a new user of Python but I have noted a little problem. > Python is a very good language but it is evolving, in particular its > library is evolving. > This can be a problem when, ad example, a module change its interface > or its implementation in a fundamental way (an example: wxPython). > This, I think, can be resolved by allowing an user to explicitly say > what version of a module it wants (sush as version numbers in Linux > shared objects). > > A possible syntax is this: > import wxPython version '2.4' I would say that the fault is on wxWindow and their constantly mutation API. A good API should be compatible whit older programs with each minor revision ( with only a few changes here and there if needed ) and would get a new name for each major revision. From zhimin at iss.nus.edu.sg Tue May 11 05:04:20 2004 From: zhimin at iss.nus.edu.sg (Choo Zhi Min) Date: Tue, 11 May 2004 09:04:20 +0000 (UTC) Subject: Cannot import Python 2.3.3 RPM GPG key Message-ID: <loom.20040511T110020-113@post.gmane.org> Hi, I apologize in advance if this is not the right place to ask Python RPM related question. I don't know which is the right mailing list to ask. I was trying to verify Python 2.3.3 RPM packages on Fedora 1. I downloaded the key from http://www.python.org/ftp/python/2.3.3/rpms/KRUD-GPG-KEY, but rpm --import gave error when importing the keys. I used gpg --import and also got the same problem. Is the key ok? Where can I get a good one? Thank you. # su - # wget http://www.python.org/ftp/python/2.3.3/rpms/KRUD-GPG-KEY # rpm --import KRUD-GPG-KEY error: KRUD-GPG-KEY: import read failed. # gpg --import KRUD-GPG-KEY gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: invalid radix64 character 2d skipped gpg: no valid OpenPGP data found. gpg: key 95CCBCFF: no valid user IDs gpg: this may be caused by a missing self-signature gpg: Total number processed: 1 gpg: w/o user IDs: 1 cheers, Zhimin From hungjunglu at yahoo.com Fri May 14 21:19:49 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 14 May 2004 18:19:49 -0700 Subject: PEP: import version References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> <mailman.517.1084462055.25742.python-list@python.org> <c80bsk$q8m$1@news.nems.noaa.gov> <mailman.532.1084478808.25742.python-list@python.org> <c80v79$h2o$1@news.nems.noaa.gov> <e838aa6e.0405140617.6b9a2f4f@posting.google.com> <c82sjs$qvm$1@news.nems.noaa.gov> Message-ID: <8ef9bea6.0405141719.fafbbab@posting.google.com> Christopher Barker <Chris.Barker at noaa.gov> wrote in message news:<c82sjs$qvm$1 at news.nems.noaa.gov>... > A. Lloyd Flanagan wrote: > > Using multiple versions in one program sounds like a recipe for > > disaster to me, even with some sort of language support. Also, we > > shouldn't make the normal single-version case more complex or less > > efficient to support a case that should be extremely rare. > > However, you may be right that this is a recipe for disaster, and the > user of that module simply needs to test with the version they are > using,a nd if it fails, get an updated version of the module, so that > the whole program is using the same versions of everything. It all depends on the specific problem. The need for heteroversion applications becomes important in client-server architecture. For various reasons (business, technical, or otherwise), clients may not be updated immediately with each new release. Thus, the server needs to handle requests with legacy I/O formats and/or with legacy business logic. If well-done, heteroversion components can ensure a smooth transition in upgrades. In long-running server processes, you really would like to be able to switch dynamically between different versions during runtime. In principle, if a package is well-written as a heteroversion application, then you could do something like: import myPackage myPackage.use_version('2.3') ... do tasks a la version 2.3 myPackage.use_version('2.4') ... do tasks a la version 2.4 Traditionally, Windows DLLs have a rudimentary way of implementing heteroversion features: by creating more and more API interfaces, while preserving the old code to make them backward-compatible. Thus a new DLL is supposed to work in new and old versions of the OS. Although theoretically sound, in practice this approach requires high-degree of discipline. Therefore you get the well-known "DLL hell problem". Microsoft has kind of decided that disk space is no longer a concern, and has opted for independent assemblies for each version in the DotNet world. Price to pay: if there is a bug that is carried over several versions, you'll probably have to (1) work it through the source code files of each version, creating branches (2) release upgrades for different older versions. Instead of developing software in time dimension alone, you now have a two-dimensional problem. This two-dimensional problem should be well-known to people that release software packages in multiple versions. There is no perfect solution, no free lunch. Each approach (single heteroversion application, or multiple versioned packages) has its own benefits and problems. But if the heteroversion approach is wanted, there are ways to do it. Inheritance polymorphism is just one of the tools. regards, Hung Jung From E.A.M.Huijbers at REMOVEstudent.tue.nl Thu May 20 16:34:13 2004 From: E.A.M.Huijbers at REMOVEstudent.tue.nl (Rico Huijbers) Date: Thu, 20 May 2004 22:34:13 +0200 Subject: free psp host In-Reply-To: <2h4ijhF8g1alU1@uni-berlin.de> References: <2h4ijhF8g1alU1@uni-berlin.de> Message-ID: <c8j4jk$6mh$1@news.tue.nl> lenk wrote: > Hi all > > Where can I find ? > > thanks > Paint Shop Pro? I wasn't aware that application required hosting :P From heikowu at ceosg.de Tue May 18 08:31:02 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 18 May 2004 14:31:02 +0200 Subject: how to keep one instance??? In-Reply-To: <200405180732.i4I7W5wR019032@mailin.webmailer.de> References: <200405180732.i4I7W5wR019032@mailin.webmailer.de> Message-ID: <200405181431.02197.heikowu@ceosg.de> Am Dienstag, 18. Mai 2004 09:31 schrieb BruceKL WhoH: > So, how to prevent the other instance from running? and how could the > second instance pass some information to the first one? Any helps are > appreciated. If it's Python object instances you're talking about, a little __new__ magic can do exactly what you want. import weakref class Test(object): __classCache = {} def __new__(cls,filename): inst = None if filename in cls.__classCache: inst = cls.__classCache[filename]() if inst is not None: return inst inst = object.__new__(cls) cls.__classCache[filename] = weakref.ref(inst) return inst def __init__(self,filename): print "I was constructed using:", filename Try this code for yourself. HTH! Heiko. From avera at coes.org.pe Wed May 5 10:35:39 2004 From: avera at coes.org.pe (Alberto Vera) Date: Wed, 5 May 2004 09:35:39 -0500 Subject: OT: software like VNC Message-ID: <000c01c432ae$3cd7a400$1603a8c0@pc22> Hello: Do you know another software that works like VNC or PCAnywhere? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040505/e48dcbce/attachment.html> From davidf at sjsoft.com Fri May 28 04:10:27 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 28 May 2004 10:10:27 +0200 Subject: ANN : ConfigObj 3.0.0 - Simple config file parsing In-Reply-To: <8089854e.0405260620.230f8319@posting.google.com> References: <8089854e.0405260620.230f8319@posting.google.com> Message-ID: <c96s5f$car$1@ctb-nnrp2.saix.net> Fuzzyman wrote: > There have been a couple of config file 'systems' announced recently, > that focus on building more powerful and complex configuration files. > ConfigObj is a module to enable you to much more *simply* access > config files. > > This is version 3, which is a big overhaul. It extends ConfigObj to > reading config files with sections and various other simplifications. > I find ConfigObj extremely easy to use and use it for reading config > files and data persistence...... > > http://www.voidspace.org.uk/atlantibots/pythonutils.html#configobj > > (also the home of caseless and listparse modules) > > INTRODUCTION and EXTRACT from docs > > ConfigObj > > ConfigObj allows you to read, modify and create config files in python > with basically single line commands. > If you give it a filename it will read the config automatically and > you can access or change the values by treating it like a dictionary. > ConfigObj 3 is a major upgrade to ConfigObj - it will now read and > write config files with sections (like windows INI files) as well as > various other improvements and simplifications. > > > ConfigObj has the following advantages over other configuration > systems : > Ease of use > Multiple (list) values for keywords > Easy to create, modify *and* write files > Easy to hand edit/create the config files > comments are preserved > quoting is optional > will understand various different keyword/value dividers > > Because the programmers interface is the same as the Python > dictionary, ConfigObj is also extremely useful for data persistence. > The fact that it can store lists and all the files it creates are > easily 'human readable' is a big plus for this. Most functionality can > be achieved with dictionary like syntax. > > So it implements a system that is easy for your users to use and easy > for you to examine the files that it creates. > Feedback on this module, including the documentation, is very much > welcomed. Questions, criticism, comments, bug reports and suggestions > all welcomed. > Just as an aside, we've just written a config system for our app that I think is quite interesting and am planning to release when I get time. Some of the goals are the same as ConfigObject: easy for either a human or a computer to read / edit the files. Some are different. Particularly it handles hierarchical config tries in a nice pythonic syntax. For example you can specify things like this: app1.title = "Title of app" app1.font.face = "Arial" Or like this: app1: title = "Title of app" font.face = "Arial" You can also copy bits of the tree if you like: app1: title = "Title of app" subtitle = "Red" font: face = "Arial" size = 16 style = "normal" app2: title = "Other title" subtitle = app1.subtitle font = app1.font: size = 18 The module will automatically remember where an element is defined and save changed values to the same location. It will also save new values to an appropriate location (e.g. app2.newvalue would appear in the app2 section). I think the hierarchical aspect of configuration is important ; it lets you do things like Mozilla's generic prefs interface etc. It also gives plugins / customizations to an app an easy way to add their own preferences. If anyone is interested in this module, post a reply... David From jfabiani at yolo.com Mon May 10 16:07:18 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 10 May 2004 20:07:18 GMT Subject: newbie question - remove a module from ram In-Reply-To: <m3llk0kwln.fsf@pc150.maths.bris.ac.uk> References: <4AAnc.6791$dH5.4946@newssvr27.news.prodigy.com> <_9Lnc.77749$Dn1.42154@fe2.texas.rr.com> <c7nvr1$fsc$01$1@news.t-online.com> <LJMnc.77976$Dn1.10841@fe2.texas.rr.com> <vAOnc.65750$nG5.54169@newssvr25.news.prodigy.com> <m3llk0kwln.fsf@pc150.maths.bris.ac.uk> Message-ID: <409FE167.9050106@yolo.com> Michael Hudson wrote: > john fabiani <jfabiani at yolo.com> writes: > > >>Paul McGuire wrote: >> >>>So then what if he follows up with: >>> del sys.modules["random"] >>>Are there any other dangling references to this module that would >>>stymie the >>>garbage collector (assuming that the OP hasn't saved off his own reference >>>to the module)? >>>-- Paul >>> >> >>I think I follow: but doesn't the garbage collector decide what is to >>be done? Assuming that there were no dangling references wouldn't >>the ram be available for re-use? > > > Well, that depends on vagaries of your allocator, but probably. > > Why are you so worried about the RAM your modules take up? > > Cheers, > mwh > Well I guess I don't have an example that I can bring up. It's just an after thought that if I create a large program that everything is being stored in ram (or swap). At some point I'll run out of ram and the more I limit the stuff I load and can't release the better. In the windows world I release(). When I monitor the ram usage (task manager) I can see the ram usage lower when I release(). I keep thinking about all the forms and the associated code I load in my windows programs. If I kept all the forms in ram I'd run out quickly. Of course I work with accounting packages.... John From jeanmarc.ranger at smisrd.com Thu May 6 09:57:15 2004 From: jeanmarc.ranger at smisrd.com (Jean-Marc Ranger) Date: 6 May 2004 06:57:15 -0700 Subject: Improvement ? References: <fc73edd3.0405051112.668aaf25@posting.google.com> <109ih0s4i7ugk40@corp.supernews.com> Message-ID: <fc73edd3.0405060557.4af78672@posting.google.com> > Also, you got very lucky with your backslashes: > > >>> "C:\SomeDirectory\.\AnotherDirectory" > 'C:\\SomeDirectory\\.\\AnotherDirectory' > >>> "C:\someDirectory\.\anotherDirectory" > 'C:\\someDirectory\\.\x07notherDirectory' Oopps.... I need to be more careful. Those names are obviously dummies, but I could have got stuck by that one easily. Thanks for spotting it. And thanks everyone for the hints. Jean-Marc From hungjunglu at yahoo.com Sun May 30 11:52:53 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 30 May 2004 08:52:53 -0700 Subject: "Private" Member Variables References: <c97r0b$jqq$1@news01.intel.com> <h8rgb0ptjmh4dgup1esgqk6mgihe37ebba@4ax.com> Message-ID: <8ef9bea6.0405300752.3855298b@posting.google.com> Alan Gauld <alan.gauld at btinternet.com> wrote: > > There is very rarely any good reason to provide getXXX/setXXX > type accessor functions, even in C++ > Accessor methods are often needed in simple-generic programming in C++/Java/C#. (With the coming of actual generics in Java/C#, accessors/properties will be even more common. C++ does get away a little bit because it has weakly-typed templates.) There is an asymmetry between data member and function members in C++/Java/C#. Whereas in Python you have virtual data fields, in C++/Java/C# you DON'T. You only have virtual functions. This is a gigantic limitation. In Python, you write a parent class to access child-class attributes all the time. In fact, you often use statements like: if hasattr(self, 'tax'): self.total_price = self.price + self.tax in the parent class, where the 'tax' attribute exists only for a taxable child class. Similarly, getters/setters are necessary in mix-in classes in Java/C#. To me, one main reason for getters/setters is the lack of virtual data fields. You NEED to use accessor methods to emulate virtual data fields. > Exposing your data via accessor functions is still exposing it > (albeit with control over read/write access). In C++/Java/C#, very often it's not a matter of choice, but a matter of need. Without accessor methods, you have no way of writing generic programs like: (a) a parent class accessing data fields of a child class (b) a mix-in class accessing data fields of the main class (Mix-ins are achieved by containment plus possible delegation, that's the way how multiple inheritance works in Java/C#). regards, Hung Jung From bjg at network-theory.co.uk Mon May 10 04:49:25 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 10 May 2004 09:49:25 +0100 Subject: python -c strangeness References: <c7n6io$f1r$1@news2.netvision.net.il> Message-ID: <87llk0650q.fsf@network-theory.co.uk> Miki Tebeka <miki.tebeka at zoran.com> writes: > [09:10] - adp86: python -c 'import sys; for i in range(3): print i' > File "<string>", line 1 > import sys; for i in range(3): print i > ^ > SyntaxError: invalid syntax Simple statements can be separated with a semicolon, but a compound statement (e.g "for") must begin on a new line. See the language reference manual for the full grammar of Python. -- Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/ From DennisR at dair.com Sun May 2 10:28:11 2004 From: DennisR at dair.com (Dennis Reinhardt) Date: Sun, 02 May 2004 14:28:11 GMT Subject: Newbie: Create Executable from single script file References: <39cbe663.0405010157.781b8610@posting.google.com> Message-ID: <%z7lc.43722$bM2.42632@newssvr29.news.prodigy.com> > from my script (and of course the modules that are imported), I just > want to have my single script file run on a machine without python. Is See http://www.spamai.com/hello.php for a Windows project to say "Hello" in Python. The method can be applied to other projects. -- Dennis Reinhardt DennisR at dair.com http://www.spamai.com?ng_python From ajsiegel at optonline.com Sat May 22 07:12:33 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 22 May 2004 11:12:33 GMT Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> Message-ID: <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> On Sat, 22 May 2004 07:21:06 -0000, "Donn Cave" <donn at drizzle.com> wrote: >Quoth Grant Edwards <grante at visi.com>: >... >| I think the fact that Python lists can be heterogogenous is one >| of the most brilliantly useful things in the language, but >| apparently we're not supposed to use lists like that. Since >| tuples aren't mutable, I'm completely at a loss as to how we're >| supposed to deal with mutable heterogenous sequences. > >You'll have to either try to understand what people mean, or ignore >them. Either will work better than the above. A heterogeneous >sequence can mean at least two things, not because there's anything >ambiguous about "heterogeneous" on its own, but because of the way >it's applied to the sequence. The notion that this is a distinctive >difference between lists and tuples is ridiculous if you take one >of those meanings, sensible if you take the other. Your choice. I think I am perfectly capable of making sense of the explanation that uses the unambigous words heterogenous and homogenous in the context of this discussion. But the ambiguous word in the previous sentence, IMO, is "explanation". Because in the end - I am repeating myself - I find, with emphasis given these words - a tautolofgy parading as an explanation. Art From flowinlife at hotmail.com Thu May 6 04:29:21 2004 From: flowinlife at hotmail.com (Simon Brown) Date: 6 May 2004 01:29:21 -0700 Subject: Enumerating machines on the local network? Message-ID: <dc1895a6.0405060029.70546e9f@posting.google.com> Hi, I am a python newbie. I intend to create a small program that enumerates all the machines on a computer network. How would i go about it? Does anyone know about some specific packages that i would need? any links or tutorials? And is a cross-platform solution possible? Thanks From myles at geocities.com Thu May 20 04:01:15 2004 From: myles at geocities.com (Myles) Date: 20 May 2004 01:01:15 -0700 Subject: Problem using StringIO file object References: <mailman.100.1085022042.6949.python-list@python.org> Message-ID: <a4638b9b.0405192305.73e7eccd@posting.google.com> "Joshua Burvill" <josh at mri.com.au> wrote in message news:<mailman.100.1085022042.6949.python-list at python.org>... > file_handle.write(zpt_code) Okay, you've written to your file object, so your current "file position" is at the end of the buffer, ready for more writes - reading from it now will only produce an empty string. You need to reset your file position to the beginning of the buffer. > ftp=FTP(printserver_ip) > ftp.login("","") > ftp.set_pasv(0) > I'd try putting in a file_handle.seek(0) here, so that your ftp object can read from the beginning of the buffer > val=ftp.storlines("STOR " + portname, file_handle) and another file_handle.seek(0) here so the read can also produce data. > return val, file_handle.read() Regards, Myles. From snrkiwi-lists at yahoo.com Sat May 29 18:57:42 2004 From: snrkiwi-lists at yahoo.com (Stephen Roderick) Date: Sat, 29 May 2004 18:57:42 -0400 Subject: Failing connection with MySQLdb on Mac OS X Message-ID: <975703D4-B1C3-11D8-A984-000A95AA5CB4@yahoo.com> Getting weird error, and I was wondering if anyone had any suggestions. My system appears to satisfy all MySQLdb prerequisities in terms of python, mysql, etc. Also, phpMyAdmin works fine with mysql, leading me to believe that my installation of MySQLdb is at fault. Any ideas? TIA For file test1.py (for appropriate values of user and passwd, and database location exists) import MySQLdb db = MySQLdb.Connect ( host="localhost", user="yyy", passwd="xxx", db="location" ) Error is : Traceback (most recent call last): File "test1.py", line 3, in ? db="location" ) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/site-packages/MySQLdb/__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/site-packages/MySQLdb/connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/site-packages/MySQLdb/connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) _mysql_exceptions.InternalError: (-1, 'connection is closed') From threeseas-AT at earthlinkDOT.net Sat May 15 15:56:44 2004 From: threeseas-AT at earthlinkDOT.net (Threeseas) Date: Sat, 15 May 2004 19:56:44 GMT Subject: tkinter problem ... In-Reply-To: <mailman.246.1083708071.25742.python-list@python.org> References: <mailman.246.1083708071.25742.python-list@python.org> Message-ID: <0Cupc.7649$zO3.6324@newsread2.news.atl.earthlink.net> Adelein and Jeremy wrote: > I just recently posted about this very same problem. In fact, I had > dug a lot deeper, and even "fixed" the problem for my platform > (RedHat 8.0/9.0), but I am left very unsatisfied. The fix I use is > incredibly crufty, requiring an environment variable to be set so > that the proper library path is used - every time I want to run > python. I never received a response to my post, and I am tempteed to > believe that there is a bug, but as I have not read *every* bit of > documentation, config file notes, and source code, I am not going to > go claiming so. Oh and by the way, IDLE still won't work correctly - > my fix simply allows me to import Tkinter in the interpreter (not > even in a script). > > I know there must be a better way, because I have never experienced > any problems with tkinter/idle/python before v2.2, so I am ignorant > of something, and I am even ignorant of what that something is. Or > maybe it really is that there is a usability bug in that the > installer assumes it knows where tcl and tk libraries are, instead of > looking. But I just don't know enough to say so authoritatively, and > your problem may be different than mine (as may be your platform). > > Strangely, I have seen on this list some saying that tk is dying off, > and that we should use wxPython. But tk is usable by Tcl, Perl, Java, > Scheme, and a few others, and I doubt that wxPython has that going > for it, so I remain incredulous. Also, IDLE is written for tk, not > for wxPython. Your problem is definitely what the previous respondant > said, viz., you are either missing the tk library interface file (eg, > tklib.so or tklib.dll), or your Python can't find it. I hope for your > own sanity that the problem is the former only and not the latter, as > this has caused me a lot of grief lately. > > I wish you better luck, and request that whatever the problem, you > post back with specifics about it and its solution should you find > such a solution. > > - Jeremy I too have run into this problem and in my search for the answer or a solution I went to IRC freenode #python. The response I received was of arrogance and ignorance as one in the power to do so, kick ban me. This only goes to show that python is attracting some real assholes in power play positions, who don't really have any idea about the subject matter. Programming is the act of automating complexity so as to make it easy for the user to use and reuse the complexity. Programming is a very recursive act as shown in any programming language above machine language. And it is by this recursive nature of the programming objective that suggest that the solution to getting a code development tool up (ironically) and properly operational should be one much simpler than pulling teeth, for which it apparently becomming a programming contridiction. From griebel at konzept-is.de Fri May 14 01:48:29 2004 From: griebel at konzept-is.de (Dr. Peer Griebel) Date: Fri, 14 May 2004 07:48:29 +0200 Subject: Speed up properties?! Message-ID: <40A45DAD.2020906@konzept-is.de> Hi, I have a class with some properties. I would like to verify that only valid values are assigned to the properties using assert. Therefore I code setters and getters and use property() to convert these to have a real property. Since the verification is only performed in __debug__ runs the property() is quite a lot of overhead. I tried to circumvent it. This is my result so far: class C(object): def __init__(self): self._x = 5 if not __debug__: self.x = property(self._x, self._x) def getX(self): return self._x def setX(self, v): assert 0 <= v <= 5 self._x = v if __debug__: x = property(getX, setX) o = C() def test(): o.x if __name__=='__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") print t.timeit() As you can see, in non __debug__ runs the accesses of the x property do not result in calls to getX or setX. There I can get a speedup of 2! But to be honest: I don't like this aproach. So is there some better, cleaner way? Peer From bostjan.jerko at mf.uni-lj.si Thu May 27 03:21:44 2004 From: bostjan.jerko at mf.uni-lj.si (=?iso-8859-2?q?Bo=B9tjan_Jerko?=) Date: Thu, 27 May 2004 09:21:44 +0200 Subject: PyML and OneAgainstRest Message-ID: <87n03utjw7.fsf@bostjan-pc.mf.uni-lj.si> Hello ! I am trying to use PyML and libsvm and when running training I get the error message: noStats in constructor Traceback (most recent call last): File "pyml_svm_ucenje.py", line 9, in ? r = mc.cv(d) File "/usr/lib/python2.3/site-packages/PyML/assess.py", line 136, in cv r = trainTest(classifier, data, trainingPatterns, testingPatterns, File "/usr/lib/python2.3/site-packages/PyML/assess.py", line 383, in trainTest return subClassifier.test(testingSet, *options, **args) File "/usr/lib/python2.3/site-packages/PyML/assess.py", line 48, in test res.L[i] = res.classLabels[res.Y[i]] The code I am using is: d=datafunc.DataSet("svm_data") s=svm.SVM (ker.Polynomial (2)) mc = multi.OneAgainstRest (svm.LinearSVM()) r = mc.cv(d) Any ideas what should I do? Regards, B. From fperez528 at yahoo.com Sat May 15 00:37:17 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 14 May 2004 22:37:17 -0600 Subject: Idea: PYTHONPATH_VER References: <mailman.1.1084512462.4157.python-list@python.org> <XN2dnfblSP3wNDndRVn-uQ@powergate.ca> Message-ID: <c846pu$7q9$1@peabody.colorado.edu> Peter Hansen wrote: > Having missed the discussion preceding, I'm probably off the mark, > but in my experience just about everything that can be solved with > PYTHONPATH can be handled with a .pth file as well, and I haven't > had any need to use PYTHONPATH for quite some time as a result. How do you handle the fact that .pth files are only read from certain places, and not others? This problem has me currently rather stuck with gross hacks: packages like Numeric, which rely on a .pth file instead of being a 'true' python package (with __init__.py), are very problematic. I am trying to share Numeric from an NFS mounted directory for multiple clients, located at /usr/local/lib/python. It was installed there via 'setup.py install --home=/usr/local'. The problem is that python does NOT scan this directory for .pth files, even if it is listed in PYTHONPATH. .pth files only have an effect for directories in sys.prefix, I think. I have actually come to HATE with a vengeance packages which rely on .pth files, because of this behavior of python of not including them for anything in PYTHONPATH. So I would really appreciate pointers from someone who has successfully solved this, since it's quite likely that I'm just misusing the system. Thanks in advance, Fernando From jbors at mail.ru Tue May 25 15:36:12 2004 From: jbors at mail.ru (=?koi8-r?Q?=22?=Dmitry Borisov=?koi8-r?Q?=22=20?=) Date: Tue, 25 May 2004 23:36:12 +0400 Subject: programming video manipulation In-Reply-To: <E1BShfY-0005Oe-00.jbors-mail-ru@f16.mail.ru> Message-ID: <E1BShie-000OH2-00.jbors-mail-ru@f25.mail.ru> Oops, typo. http://pymedia.sourceforge.net > For video manupulation you may try pymedia( http://pymedia.sourceforge.org ). From ptmcg at austin.rr._bogus_.com Wed May 5 19:26:02 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 05 May 2004 23:26:02 GMT Subject: error handling in Python References: <3064b51d.0405050741.43d11aa0@posting.google.com> Message-ID: <eKemc.56235$hR1.42473@fe2.texas.rr.com> <beliavsky at aol.com> wrote in message news:3064b51d.0405050741.43d11aa0 at posting.google.com... > > I do NOT want to use the try/except idiom to stop the program if there > is a problem reading data. > Unlike FORTRAN, exceptions in Python do not necessarily stop the program - they only do so if not handled. In your case, you know just where read_data() is called from, so you can catch a thrown exception and do the appropriate cleanup/retry/shutdown/ignore-and-continue, all without having to figure out what "special" value to put in the return code to indicate a failure. You also don't have to clutter up your read_data() argument list with error codes, error descriptions, I/O status, etc. - put that stuff in attributes of the thrown exception, and leave your read_data() arguments to deal with the read_ing of data. Don't try to hack around try-except's mechanisms for invoking exception code, by using magic return codes ("if zero, that means success; if greater than zero, that's a warning; less than zero is an error") and exception-only method arguments. Cleaning this stuff out of your method signature is a *good* thing, and let's you focus on the functional task, while try-except offers a clear, robust, supported mechanism for signalling, um, let's not call them "failures", how about "alternative return paths"? :) -- Paul From amireallyfat at yahoo.com.au Fri May 28 00:58:29 2004 From: amireallyfat at yahoo.com.au (mr_vocab) Date: Fri, 28 May 2004 14:58:29 +1000 Subject: why learn References: <40b58695_1@news.iprimus.com.au> <Kaqtc.338$hG1.6@read3.inet.fi> Message-ID: <40b6c6f0_1@news.iprimus.com.au> great thanks for your help (all) "Timo Virkkala" <a at a.invalid> wrote in message news:Kaqtc.338$hG1.6 at read3.inet.fi... > mr_vocab wrote: > > > hey i finished working through alot of python stuff and no a fair bit bout > > it > > now what can i do with it??? > > If you're interested in game programming, try making a simple (or complex) game: > http://www.pygame.org/ > > -- > WT From jean at simpleconfusion.com Fri May 21 20:04:31 2004 From: jean at simpleconfusion.com (Jean) Date: 21 May 2004 17:04:31 -0700 Subject: Server/OS/Dev environment Message-ID: <bf4bc58f.0405211604.6b461e7@posting.google.com> Hi. I am new to Python, but very eager to learn. I've browsed many postings and found conflicting opinions on the best backend and development setup. In fact, I am more confused now that when I first began investigating this problem. I need to create web pages with MySQL as the primary data source. What would be the best server set up for this? RH? Windows? mod_python? Spyce? Some other templating mechanism? To develop such a site, should I be using Vim? Idle? Or Windows gui software? Install MySQL & Python on Windows? Stick with Linux? A multitude of choices is great for the gurus, but not necessarily so for a newbie... Thanks for any comments, Jean From della at toglimi.linux.it Wed May 26 17:09:44 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 26 May 2004 21:09:44 GMT Subject: Update with pickle In-Reply-To: <y21tc.41582$tb4.1325901@news20.bellglobal.com> References: <AoIsc.27189$tb4.933533@news20.bellglobal.com> <GYJsc.72376$Qc.2938525@twister1.libero.it> <LoKsc.27890$tb4.968272@news20.bellglobal.com> <aSMsc.42$Rp4.28350@monger.newsread.com> <gaPsc.29315$tb4.1059921@news20.bellglobal.com> <OpUsc.2509$Hf.1455264@newshog.newsread.com> <ljWsc.39527$tb4.1256693@news20.bellglobal.com> <y21tc.41582$tb4.1325901@news20.bellglobal.com> Message-ID: <sI7tc.22267$Wc.780951@twister2.libero.it> Nicolas Fleury wrote: > I just added a feature request on sf to have an updating load function > in pickle. My preferred solution for now might still be the copy of > __dict__ (I could copy slots also), it's simple and not intrusive (using > proxies is, even if less a hack). However, the cleanest solution would > be to implement your solution, but I have no idea how to do it for now. Leif is essentially proposing a non-transparent proxy, while the cookbook recipe I pointed out is a transparent proxy (i.e. you are using a proxy, but you can access it just as if it was the original object). If I understood correctly, you want something like this: >>> pickle.dump(42, 'file') >>> foo = foo2 = 'foo' >>> pickle.update(foo, 'file') >>> foo 42 >>> foo2 42 Well, it's not possible: variables are just names attached to objects, and while you can assign a name to an object, you *can't* change the object's type, or replace an object with another one. And I think that copying __dict__ is a hack: it wouldn't work, for instance, with builtin types, when __slots__ are used, or when you are using properties. With a proxy you could do something like this: >>> foo = proxy(foo) (use foo just as before) >>> pickle.dump(foo._obj, 'file') and then resume the file with >>> foo._obj = pickle.load('file') A transparent proxy is a clean way to do it: through delegation, it would work with any kind of object, changes in code are localized in the load/save part, and the rest of the application wouldn't even notice. -- Ciao, Matteo From bdecker at flowcom.com.au Tue May 4 00:44:12 2004 From: bdecker at flowcom.com.au (bdecker at flowcom.com.au) Date: Tue, 4 May 2004 04:44:12 +0000 (UTC) Subject: list as a base class in Python 2.1 In-Reply-To: <20040504125913.GC15311@flowcom.com.au> References: <20040504125913.GC15311@flowcom.com.au> Message-ID: <20040504143032.GE15311@flowcom.com.au> Nevermind, I founf the UserList module. * bdecker at flowcom.com.au <bdecker at flowcom.com.au> [2004-05-04 02:54:07 +0000]: > Hello, > > > With python2.2 I am able to define a class based on the 'list' type as > follows: > > class sample(list): > ... > > But this doesn't work under python 2.1. Is there still a way to simply > use the list type as a base class under python 2.1? > > > > Ben From dygimailNo at SPAMpoczta.fm Fri May 14 19:11:11 2004 From: dygimailNo at SPAMpoczta.fm (Krzysztof Szynter) Date: 14 May 2004 23:11:11 GMT Subject: looping over the files in a directory References: <kE5pc.476427$oR5.129809@pd7tw3no> <pan.2004.05.14.16.17.33.273871@freelance-developer.com> <40a4fba5$1@nntp0.pdx.net> Message-ID: <Xns94E9F12809260dygimailpocztafm@127.0.0.1> Scott David Daniels <Scott.Daniels at Acm.Org> wrote in news:40a4fba5$1 at nntp0.pdx.net: > This is purposely left a bit elliptical to leave you some work in > case this is a homework assignment. Sorry for that, but what does mean 'a bit elliptical' in this sentence? Is it a kind of circumlocution? -- Krzysztof Szynter :'''. :. : * Dygi GG 1027078 :...' ..... : : : ..... . . . . . ..... http://newbie.friko.pl : : :.... : : : :.... :: :: :.. : :.... dygimail(at)poczta(dot)fm :...' :.... : ': :.... : : :..' : :.... From wweston at att.net Sun May 9 21:30:00 2004 From: wweston at att.net (wes weston) Date: Mon, 10 May 2004 01:30:00 GMT Subject: What's the difference? In-Reply-To: <409EB546.B8367374@shaw.ca> References: <409EB546.B8367374@shaw.ca> Message-ID: <sWAnc.37581$Ut1.1080794@bgtnsc05-news.ops.worldnet.att.net> SeeBelow at SeeBelow.Nut wrote: > between this: > > name = "C" > > and this: > > name = StringVar() > name.set("C") > > I hope someone can explain that to me. > > Thanks, > > Mitchell Timin > Mitchell, >>> dir(Tkinter.StringVar) ['__del__', '__doc__', '__init__', '__module__', '__str__', '_default', 'get', 'set', 'trace', 'trace_variable', 'trace_vdelete', 'trace_vinfo'] >>> Tkinter.StringVar.__doc__ 'Value holder for strings variables.' >>> dir("C") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> wes From s.brennan at cox.net Wed May 12 22:15:52 2004 From: s.brennan at cox.net (Shane) Date: Thu, 13 May 2004 02:15:52 GMT Subject: Python and Windows.Forms In-Reply-To: <87n08qrpcv.fsf@pobox.com> References: <mailman.350.1074089447.12720.python-list@python.org> <87n08qrpcv.fsf@pobox.com> Message-ID: <sTAoc.67180$sK3.3272@nwrddc03.gnilink.net> Hey folks, I'm new to Python and programming in general and I'm having a blast. I was curious if it was possible to use Windows.Forms; I'm interesting in porting a C++ program a friend wrote for me to Python and would like to use a similar GUI (its fairly simple). I've noticed ActiveState has a .NET plugin for Python... http://www.activestate.com/Products/Visual_Python/?_x=1 ...but I'm not sure that is what I am looking for and I'm stuck with Borland C# Builder Personal Edition anyway for financial reasons. One thing that threw me for a loop was that when I used ActivePython (ActiveStates Python IDE, I like it so far) to run a script I wrote, it gives me a Windows.Forms input box when I call raw_input as opposed to the regular console input message you get in the basic interactive window that comes with a standalone Pythin installation. What's going on there? Can I harness that a little more? Shane Brennan From __peter__ at web.de Thu May 13 05:24:31 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 May 2004 11:24:31 +0200 Subject: __dir__ References: <tyffza4pvo5.fsf@pcepsft001.cern.ch> Message-ID: <c7vesg$fvu$01$1@news.t-online.com> Jacek Generowicz wrote: > Is there some way of affecting the way dir finds the information it > presents? > > For example, supposing a hypothetical __dir__ magic method: > > class collection: > def __init__(self, myname, names): > self.names = names > self.myname = myname > def __dir__(self): > return ['%s(%s)' % (self.myname,n) for n in self.names] > > class thingy: > def __init__(self, *names): > self.it = collection('it', names) > > thing = thingy('this', 'that', 'theother') > > dir(thing) > > ['__doc__', '__init__', '__module__', 'it(this)', 'it(that)', > ['it(theother)'] > > > In other words, I would like some attributes of an instance to inject > some information into the output of dir ... to change the way their > names are perceived by dir. > > Any ideas ? >>> class C: ... __members__ = ["Is this evil?", "So what"] ... >>> dir(C) ['__doc__', '__members__', '__module__'] >>> dir(C()) ['Is this evil?', 'So what', '__doc__', '__members__', '__module__'] >>> However, __members__ is marked as deprecated and, even more important, I don't know what the side effects of the above may be. Highly unrecommended. Peter From tjreedy at udel.edu Fri May 21 18:56:59 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 18:56:59 -0400 Subject: TypeError: unsubscriptable object. References: <494182a9.0405211340.49873a72@posting.google.com> Message-ID: <c8m1ft$3vt$1@sea.gmane.org> "Balaji" <balaji at email.arizona.edu> wrote in message news:494182a9.0405211340.49873a72 at posting.google.com... > class Stack: > > def __init__(self,expr): Note: tabs get eaten by some newsreaders. > self.stackP=[] > self.stackF=1 ... > def peekF(self): > rval = 0 # useless line > rval= self.stackF[-1] > return rval # return self.stackF[-1] would be easier to read See the potential problem? (If not, add 'print type(self.stackF)' to the top of this function.) > def stackManagement(self,expr): ... > self.a+= self.peekF() which now seems quite possible. ... > s.stackManagement(e1) > ---------------------------------------------- > I'm getting the following error TypeError: unsubscriptable object... which means you tried to subscript an unsubscriptable object > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "generation.py", line 175, in stackManagement > self.stackManagement(expr.left) > File "generation.py", line 176, in stackManagement > self.stackManagement(expr.right) > File "generation.py", line 199, in stackManagement > self.a+= self.peekF() > File "generation.py", line 168, in peekF > rval= self.stackF[-1] in the line immediately above. Terry J. Reedy From klachemin at home.com Wed May 26 15:47:30 2004 From: klachemin at home.com (Kamilche) Date: 26 May 2004 12:47:30 -0700 Subject: Inclusion Guards Necessary? Message-ID: <889cbba0.0405261147.3835adef@posting.google.com> Are inclusion guards necessary to prevent multiple modules from importing the same shared module multiple times? --Kamilche From Mike at DeleteThis.Geary.com Fri May 7 22:20:28 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 7 May 2004 19:20:28 -0700 Subject: Iterating Dictionaries in a Function References: <f092b750.0405071723.29731923@posting.google.com> Message-ID: <109ogvcilcvviaa@corp.supernews.com> > def findx(st): > d = {'a': 1, 'rty': 4, 'er': 2} > for item in d.keys(): > print item > if cmp(item.upper(),st.upper()) == 0: > print d[item] > return d[item] > else: > return st p.s. In my other message I explained the bug in your code. Now let's talk about the design a bit. Generally, you're *much* better off if you can let the dict itself handle the lookup rather than iterating through it yourself. In a large dict this will be much faster. It looks like you want to do a case-insensitive lookup in the dict. The way to handle this would be to convert keys to uppercase or lowercase when you enter them into the dict, and do the same with values that you look up. Here's your test case modified to work this way: def findx(st): d = {'a': 1, 'rty': 4, 'er': 2} try: item = d[st.lower()] except: print 'Item not found:', st else: print 'Item found:', st, item return item findx('a') findx('ER') findx('foo') Which prints: Item found: a 1 Item found: ER 2 Item not found: foo -Mike From info at aes-italia.it Wed May 26 12:33:38 2004 From: info at aes-italia.it (Annalisa Rea (AES Tel. 0775 830930)) Date: Wed, 26 May 2004 18:33:38 +0200 Subject: Trovato virus nel messaggio "Delivery (info@aes-italia.it)" Message-ID: <21B5C6C8D16ED511843F0050DA7C7DF20E4EB0@ITER01> Symantec AntiVirus ha trovato un virus in un allegato inviato da (python-list at python.org <python-list at python.org>) a info at aes-italia.it. Per garantire che i destinatari possano utilizzare i file inviati, eseguire una scansione dei virus, ripulire eventuali file infetti e inviare di nuovo l'allegato. Allegato: message.pif Nome virus: W32.Netsky.Q at mm Azione intrapresa: Ripulisci non riuscito : Quarantena riuscito : Stato file: Infetto -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1628 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040526/c41509e6/attachment.bin> From pinard at iro.umontreal.ca Thu May 27 18:41:17 2004 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 27 May 2004 18:41:17 -0400 Subject: Why a class when there will only be one instance? In-Reply-To: <40B66619.60108@stackless.com> References: <40B3E861.29B033D5@shaw.ca> <20040527215637.GA2389@alcyon.progiciels-bpi.ca> <40B66619.60108@stackless.com> Message-ID: <20040527224117.GA5158@alcyon.progiciels-bpi.ca> [Christian Tismer] > Fran?ois Pinard wrote: > >It would be `self.' within the class itself, and the instance name > >within foreign classes. This habit stresses the relations between the > >parts of the program and eases a better understanding of the whole. > Just a little observation: If you really want the class and the > instance to be the same, well, you can take a module. In a sense, > this *is* a class and the only instance. Indeed, and for programs which are more than small, this is a very natural way to proceed. On the other hand, for programs which are not so big, it is often quite practical to keep everything in a single file, and there, short of having many modules, sole instances of a few classes are still an attractive way for organising the code. It might be worth noting, as a kind of counter-argument, that abusing of classes may decrease legibility instead of increasing it. As usual in such things, sense of measure, and good taste, are always welcome! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From nicksjacobson at yahoo.com Sat May 1 06:08:07 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 1 May 2004 03:08:07 -0700 Subject: Help with C API References: <f8097096.0404302152.38dd1eae@posting.google.com> <c6vfmv$grq$1@news1.tilbu1.nb.home.nl> Message-ID: <f8097096.0405010208.3fbc8e2d@posting.google.com> vincent wehren <vincent at visualtrans.de> wrote in message news:<c6vfmv$grq$1 at news1.tilbu1.nb.home.nl>... > Nick Jacobson wrote: > ... > > I'd like to do the reverse: take an C array (say, with 100 elements) > > and copy its elements into a Python list. But I don't know where to > > start...there's no PySequence_Fast_INSERT or even PySequence_Insert > > function, for example. Can I create an empty list in the API or > > should I just pass one in from Python? > > > > Can someone please help with this? Thanks in advance!! > > > > --Nick > > http://docs.python.org/api/listObjects.html is probably a good start > > Regards, > Vincent Wehren Thank you! This is what I ended up writing: static PyObject *ex_arytopylist(PyObject *self, PyObject *args) { PyObject *seq = NULL, *fitem = NULL; double dbar[] = { 1, 2, 3 }; int i, seqlen = sizeof(dbar) / sizeof(double); seq = PyList_New(0); if (!seq) return NULL; for (i=0; i < seqlen; i++) { fitem = PyFloat_FromDouble(dbar[i]); if (!fitem) { Py_DECREF(seq); return NULL; } if (PyList_Append(seq, fitem)) { Py_DECREF(fitem); Py_DECREF(seq); return NULL; } Py_DECREF(fitem); } return Py_BuildValue("O", seq); } My only question is, since PyList_New(0) and Py_BuildValue both increment the ref count of seq, is it garbage collected properly? Or perhaps I should just write: return seq; Thanks! From loic at fejoz.net Thu May 6 10:40:31 2004 From: loic at fejoz.net (Yermat) Date: Thu, 06 May 2004 16:40:31 +0200 Subject: Scope rule pecularities In-Reply-To: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> Message-ID: <c7dium$ruv$1@arcturus.ciril.fr> Antoon Pardon wrote: > [...] > a1 = Int(14) > a2 = Int(15) > b = Int(23) > > print a1, a2 > > def foo(): > > a1 += b > a2.__iadd__(b) > > foo() > > print a1, a2 > > > Now the a1 += b line doesn't work, it produces the following error: > > UnboundLocalError: local variable 'a1' referenced before assignment. > > The a2.__iadd__(b) line however works without trouble. > > > Now I think I understand what is causing this, but I think this > kind of thing shouldn't happen. If a += b is just syntatic sugar > for a.__iadd__(b) then the first should be acceptable where the > second is acceptable. > Here we are again ! Do you mind to try : def foo(): global a1, a2 a1 += b a2.__iadd__(b) Note also that the second line were not executed so you can't know if it were working... -- Yermat From mwh at python.net Mon May 17 13:54:32 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 17 May 2004 17:54:32 GMT Subject: This program makes Python segfault - no other does References: <pan.2004.05.17.10.17.01.120134@but.no.spam> <mailman.11.1084805883.6949.python-list@python.org> <pan.2004.05.17.16.42.48.115195@but.no.spam> Message-ID: <m33c5zgcrs.fsf@pc150.maths.bris.ac.uk> Juho Saarikko <sorry at but.no.spam> writes: > I did, that's why the print lines are there. I'm sorry I didn't think to > include the info from the start... Anyway, here's gdb stacktrace, if > anyone's interested. The problem is not in unQuoteBytea, which works fine > untill it tries to discard some temporary variables, at which point, > kaboom. That would seem to indicate either line #2 or #3, but this is the > first time I've used a debugger, so I might be quite wrong. > > #0 0x400c4c1b in free () from /lib/libc.so.6 > #1 0x400c4aa3 in free () from /lib/libc.so.6 > #2 0x0807ff2e in PyObject_Free (p=0x81d7240) at Objects/obmalloc.c:774 > #3 0x0807f5a6 in PyMem_Free (p=0x81d7240) at Objects/object.c:2111 > #4 0x4023a2d4 in unQuoteBytea (sin=0x81dd2ec ">nemo wrote:") at libpqmodule.c:417 Oh look, this is clearly inside the libpq extension module! What evidence do you have for a bug in Python itself? Cheers, mwh -- . <- the point your article -> . |------------------------- a long way ------------------------| -- Christophe Rhodes, ucam.chat From BruceWhoHKL at gawab.com Tue May 18 03:31:46 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Tue, 18 May 2004 15:31:46 +0800 Subject: how to keep one instance??? Message-ID: <mailman.127.1572214292.32708.python-list@python.org> Hi, can anyone tell me how to keep only one instance in memory? I write a python script,an editor, so if user click the .txt files, it will run. But if user click the same .txt file again , user will get another instance. So, how to prevent the other instance from running? and how could the second instance pass some information to the first one? Any helps are appreciated. ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-18 From klappnase at web.de Wed May 19 10:02:36 2004 From: klappnase at web.de (klappnase) Date: 19 May 2004 07:02:36 -0700 Subject: Tree control with TKinter References: <q6tqc.8301$Wc.302087@twister2.libero.it> <c8f3e9$5dt$1@news-reader1.wanadoo.fr> Message-ID: <a7a67196.0405190602.d188fba@posting.google.com> Eric Brunel <eric_brunel at despammed.com> wrote in message news:<c8f3e9$5dt$1 at news-reader1.wanadoo.fr>... > Marco Terzuoli wrote: > > Hi, > > I would like to implement a tree control inside a Python application. It > > should be similar to GTK's TreeStore widget, but I need it for TKinter. > > Any ideas? > > thanks > > Marco > > There is a tree widget in IDLE, which is part of all Python distribution. With > Python 2.1, it's located under Tools/idle in the Python installation directory > and is named TreeWidget.py. AFAIK, there's no documentation for it, but it is > quite easy to use and also includes an example application. > > There are many others alternatives around; Google is your friend. > > HTH Check out Gene Cash?s tree widget, it beats far Idle?s tree and all the others I have seen: http://home.cfl.rr.com/genecash/tree.html Regards Michael From segphault at sbcglobal.net Mon May 31 15:54:53 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 31 May 2004 19:54:53 GMT Subject: getting mimetype of a file Message-ID: <pan.2004.05.31.19.51.41.193959@sbcglobal.net> is there any way to determine the mimetype of a file using ruby? TIA --SegPhault From peter at engcorp.com Tue May 25 04:47:17 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 May 2004 04:47:17 -0400 Subject: why i In-Reply-To: <Xns94F45CB2C1E18duncanrcpcouk@127.0.0.1> References: <40b2e204$1_1@news.iprimus.com.au> <slrncb5s1p.21a.bignose-hates-spam@rose.localdomain.fake> <Xns94F45CB2C1E18duncanrcpcouk@127.0.0.1> Message-ID: <N9KdnVD1v92IlS7d4p2dnA@powergate.ca> Duncan Booth wrote: > The actual reason why everyone uses I and then J as the for loop indexes > was that Fortran, by default, assumed all variables starting with letters > from I-N were integer, and all other variable names were real. Integer > names starting with I was presumably chosen for its mnemonic value and the > other letters then follow on in sequence, presumably far enough for what > the original language designers thought was a reasonable 20:6 split real to > integer variables. Does the FORTRAN usage precede or follow the similar common use by mathematicians? My guess is that subscripts i, j, k have been used so for much longer than FORTRAN has existed, or computers for that matter. The idea that 'i' is mnemonic for 'integer' is interesting, though. If the mathematical field is really the origin, rather than FORTRAN, it would be interesting to know if that was how "they" picked it. Googling to little avail, the best I could find to help was Hilbert's 1900 address on "23 Mathematical Problems" which he gave to the Int'l Congress of Mathematics in Paris, proving a usage which predates FORTRAN by 50-some years. The interesting page maintained by Jeff Miller at http://members.aol.com/jeff570/mathsym.html makes no mention of the topic. -Peter From jjl at pobox.com Sun May 9 07:31:58 2004 From: jjl at pobox.com (John J. Lee) Date: 09 May 2004 12:31:58 +0100 Subject: ClientCookie/urllib2 with persistent connections? References: <409c08a1$0$129$a726171b@news.hal-pc.org> Message-ID: <87u0yp4z0x.fsf@pobox.com> Chuck Bearden <cbearden at hal-pc.org> writes: > My impression is that if I want to make several requests over a single, > persistent HTTP 1.1 connection, I must use httplib rather than urllib2 > or ClientCookies. Is that correct? Yes. > To put it another way, can I have cookie support over persistent > connections without having to code the cookie support myself? Yes. You can use httplib direct, and use a couple of little functions to link it up to ClientCookie. The request and response interfaces required are well-documented. Here is a clumsy cobbled-together hack, for HTTP only, which may even work ;-) No automatic redirection handling, proxy support, etc. The cookies bit is simple (thanks to ClientCookie :-), it's the rest that's messy. IIUC, the only problem is that urllib.addbase expects a readline method (as do some users of urllib2, no doubt), which httplib.HTTPResponse doesn't provide. So, urllib2.AbstractHTTPHandler.do_open() passes urllib.addinfourl the underlying socket object instead (the fp attribute of HTTPResponse), which does have a readline() method. In turn, that means that HTTPResponse's knowledge of the HTTP protocol is lost, and you can't do more than one request in a single connection. So, the code below passes the HTTPResponse itself to addinfourl, rather than just its fp attribute. I suppose the solution is to add a readline method to HTTPResponse (and whichever other methods HTTPResponse.fp has and addbase passes through). import httplib import ClientCookie class addbase: """Base class for addinfo and addclosehook.""" def __init__(self, fp): self.fp = fp self.read = self.fp.read if hasattr(self.fp, "readlines"): self.readline = self.fp.readline if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno if hasattr(self.fp, "__iter__"): self.__iter__ = self.fp.__iter__ if hasattr(self.fp, "next"): self.next = self.fp.next def __repr__(self): return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp) def close(self): self.read = None self.readline = None self.readlines = None self.fileno = None if self.fp: self.fp.close() self.fp = None class addclosehook(addbase): """Class to add a close hook to an open file.""" def __init__(self, fp, closehook, *hookargs): addbase.__init__(self, fp) self.closehook = closehook self.hookargs = hookargs def close(self): addbase.close(self) if self.closehook: self.closehook(*self.hookargs) self.closehook = None self.hookargs = None class addinfo(addbase): """class to add an info() method to an open file.""" def __init__(self, fp, headers): addbase.__init__(self, fp) self.headers = headers def info(self): return self.headers class addinfourl(addbase): """class to add info() and geturl() methods to an open file.""" def __init__(self, fp, headers, url): addbase.__init__(self, fp) self.headers = headers self.url = url def info(self): return self.headers def geturl(self): return self.url class SimpleURLOpener: def __init__(self, cookiejar, debuglevel=0): self.cj = cookiejar self._debuglevel = debuglevel self.conn = None self.host = None def open_connection(self, host): assert self.conn is self.host is None self.host = host self.conn = httplib.HTTPConnection(host) def close_connection(self): self.conn.close() self.conn = self.host = None def set_http_debuglevel(self, level): self._debuglevel = level def add_cookie_header(self, request): self.cj.add_cookie_header(request) def extract_cookies(self, response, request): self.cj.extract_cookies(response, request) def open(self, url_or_request): if isinstance(url_or_request, ClientCookie.Request): req = url_or_request else: req = ClientCookie.Request(url_or_request) self.add_cookie_header(req) self._do_request(req) r = self._do_open(req) self.extract_cookies(r, req) return r def _do_request(self, request): def _do_open(self, req): from urllib import splittype, splithost # bleah host = req.get_host() if not host: raise URLError('no host given') scheme, sel = splittype(req.get_selector()) sel_host, sel_path = splithost(sel) assert self.host == (sel_host or host) if request.has_data(): # POST data = request.get_data() if not request.has_header('Content-type'): request.add_unredirected_header( 'Content-type', 'application/x-www-form-urlencoded') if not request.has_header('Content-length'): request.add_unredirected_header( 'Content-length', '%d' % len(data)) if not request.has_header('Host'): request.add_unredirected_header('Host', self.host) self.conn.set_debuglevel(self._debuglevel) headers = dict(req.headers) headers.update(req.unredirected_hdrs) try: self.conn.request(req.get_method(), req.get_selector(), req.data, headers) r = self.conn.getresponse() except socket.error, err: # XXX what error? raise URLError(err) # Pick apart the HTTPResponse object to get the addinfourl # object initialized properly resp = addinfourl(r, r.msg, req.get_full_url()) resp.code = r.status resp.msg = r.reason return resp opener = SimpleURLOpener(ClientCookie.CookieJar()) opener.open_connection("python.org") r1 = opener.open("http://python.org/index.html") print "***********************************************************" print r1.read() req = ClientCookie.Request("http://python.org/download", headers={"Foo-Bar": "baz"}) r2 = opener.open(req) print "***********************************************************" print r2.read() opener.close_connection() John From me at privacy.net Wed May 26 04:10:27 2004 From: me at privacy.net (Duncan Booth) Date: 26 May 2004 08:10:27 GMT Subject: r'\' - python parser bug? References: <mailman.274.1085497902.6949.python-list@python.org> <8089854e.0405252339.18e0c59d@posting.google.com> Message-ID: <Xns94F55D228C7AAduncanrcpcouk@127.0.0.1> michael at foord.net (Fuzzyman) wrote in news:8089854e.0405252339.18e0c59d at posting.google.com: >>>> print r'c:\subdir\' > SyntaxError: EOL while scanning single-quoted string >>>> > >> When the parser sees a backslash inside >> a string literal, it always skips the next character. > In the above example the parser *only* skips the next character if it > is at the end of the string... surely illogical. The reason given is > effectively 'raw strings were created for regular expressions, so it > doesn't matter if the behaviour is illogical' (and precludes other > reasonable uses!!).......... > In a python string, backslash is an escape character which gives the next character(s) special meaning, so '\n' is a single newline character. If the escaped character isn't a known escape then the parser simply passes through the entire sequence. So '\s' is a two character string. In all cases at least one character following the backslash is parsed when the backslash is encountered, and this character can never form part of the string terminator. Raw strings are processed in exactly the same way as normal strings, except that no escape sequences are recognised, however the character following the backslash is still prevented from terminating the string, just as it would in any other string. This *useful*? behaviour allows you to put single and double quotes into a raw string provided that they are preceded by a backslash. print r'c:\subdir\'file' Raw strings aren't intended for writing DOS pathnames, they are actually targetted for regular expressions where this behaviour makes more sense. If you need a lot of pathnames in your program you could consider using forward slash as the directory separator (use os.path.normpath to convert to backslashes if you feel the need), or put all your paths in a separate configuration file where you can choose what quoting, if any to interpret. Also, provided you use os.path.join to concatenate paths you never actually *need* to include a trailing separator: DIR = r'c:\subdir' FILE = os.path.join(DIR, 'filename') ducks the entire issue cleanly. From asdf at asdf.com Tue May 4 12:31:47 2004 From: asdf at asdf.com (asdf sdf) Date: Tue, 04 May 2004 16:31:47 GMT Subject: Experience with vb2py? In-Reply-To: <c786cm$j2j$1@swifty.westend.com> References: <_Azlc.44378$r37.39639@newssvr29.news.prodigy.com> <c786cm$j2j$1@swifty.westend.com> Message-ID: <TzPlc.5194$Bc4.3019@newssvr27.news.prodigy.com> Peter Maas wrote: > asdf sdf wrote: > > > > > i have a large VB project lying around that may have to be upgraded. i > > would love to see it go to python. > > It's reasonable to ask for opinions but if you want to use it for > a large project you should experiment with it anyway. Create a little > hello world dialog and try to convert it. Populate it with more > complicated controls, add database and network connections and try to > convert it again. My bet is that vb2py won't do *all* of the work for > you. I once tried to convert a medium sized project (25 kloc) from > vb6 to vb.net and the migration assistant supplied by MS aborted after > a 3 hours run. Python and VB are much more different so I assume that > vb2py saves the low level typing work like converting loops, ifs and > defs which is very valuable but the high level conversions that require > to understand the code will probably be up to you. certainly a detailed investigation would be required before making any project committments. realistically, if a bunch of people are not already having success converting minor projects then it isn't ready for the big ones yet. vb2py is attempting something difficult. in my experience with conversion programs, everytime you scale it up, you shake out some test cases you never thought of. i'm sure that applies here too. From kveretennicov at yahoo.com Fri May 21 08:23:21 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 21 May 2004 05:23:21 -0700 Subject: "Extracting" a dictionary References: <mailman.20.1084820319.6949.python-list@python.org> <c8crm8$8hb$1@nntp.ilk.net> <5fd6ba56.0405200818.60b0259@posting.google.com> <c8inoe$n0c$05$1@news.t-online.com> Message-ID: <5155aad2.0405210423.59c4d085@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:<c8inoe$n0c$05$1 at news.t-online.com>... > > >>> class AttrDict: > ... def __init__(self, d): > ... self.__dict__.update(d) > ... > >>> d = AttrDict({"foo": 23, "bar": 42}) > >>> d.bar > 42 > >>> d.foo *= 2 > >>> d.__dict__ > {'foo': 46, 'bar': 42} > >>> del d.foo > >>> d.__dict__ > {'bar': 42} > >>> > > A standard trick, by the way. Can't think of the right google keywords right > now, so I use another standard trick and leave finding them as an excercise > to the reader :-) > > Peter http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 (Bunch class) http://www.norvig.com/python-iaq.html (Struct class) - kv From codeapocalypse at msn.com Sat May 15 01:30:42 2004 From: codeapocalypse at msn.com (Brian) Date: 14 May 2004 22:30:42 -0700 Subject: RELEASED Python 2.3.4, release candidate 1 References: <mailman.22.1084560936.4157.python-list@python.org> Message-ID: <ef3269df.0405142130.277935ef@posting.google.com> "Hornberger, Chris" <Chris.Hornberger at blackrock.com> wrote in message news: > PS... I have moral and ethical arguments against this. I believe it's > just plain WRONG to use a language like Python or Java or even C#/.NET > and RELY on platform specific "extensions". Nice troll. Let me guess, you haven't entered the job market yet? >From elsewhere in the thread you spoke: > Now that we're all done being offended because I used terms that were taken out of context.... I haven't found a non-foolish context for your comments yet. Perhaps you should take your drivel to an advocacy group? From demarchi at duke.edu Mon May 17 08:09:10 2004 From: demarchi at duke.edu (stormslayer) Date: 17 May 2004 05:09:10 -0700 Subject: benchmarks and questions for new python programmer References: <c5f75ecc.0405161733.4bc95347@posting.google.com> <10agki14qhts2c2@corp.supernews.com> Message-ID: <c5f75ecc.0405170409.59f8f54@posting.google.com> Thanks for all the help. Mike is correct -- the integer random number gen from the math library isn't all that good and is causing the slowdown. And thanks to Terry for math lib suggestions. You folks are great. I got a bunch of emails saying that one shouldn't benchmark languages this way, or do so without knowing the language really well, or that my code wasn't pythonish enough. You folks need to wake up and smell the compilers (or interpreters). The whole point of a tool such as a compiler or interpreter is to take reasonable code (and in this case, my algorithm is certainly that -- the fault wasn't in my code but in a python function) and generate reasonable program speeds. Sure, experts should be able to fiddle and get something more out of it, but the whole attraction of python for me is that it looks like pseudo code. If you can't write things the way you think, then it isn't much help to use python. It is still the case that unoptimized code in borland's C++ is 5x faster than python (and that's for a windows program w/ dialog boxes, etc. rather than a console app), and this is distressing, but I'll keep trying w/ python. Python is beautiful... Thanks again for all the help. sd From peter at engcorp.com Mon May 17 08:24:36 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 May 2004 08:24:36 -0400 Subject: NIC adress of incoming socket. In-Reply-To: <40a88d6b$0$2279$afc38c87@news.easynet.fr> References: <40a4f772$0$2280$afc38c87@news.easynet.fr> <naWdnRu54vmoBTjdRVn-hw@powergate.ca> <40a5e12e$0$2277$afc38c87@news.easynet.fr> <CpSdnTXrVp3AljvdRVn-sw@powergate.ca> <40a88d6b$0$2279$afc38c87@news.easynet.fr> Message-ID: <OpudndE6NrKYMjXd4p2dnA@powergate.ca> RosalieM wrote: > I saw that this could be a security issue. So i would like to prevent it. > And i would like to be able to do what dhcpd and tftp are able to do, to say > check the nic before sending files. But I wanted to write this program in > python as i found in google a dhcpd program writen in python. > > You mean that python cant do it ? I read that python can do everything > possible. Where did you read that? It needs to be corrected... From nav+posts at bandersnatch.org Tue May 4 15:38:37 2004 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 04 May 2004 15:38:37 -0400 Subject: how to add new print %b format to python? References: <slrnc8q9qp.htc.rs@frank.overlook.homelinux.net> Message-ID: <m3u0ywm18i.fsf@tanelorn.bandersnatch.org> Rusty Shackleford <rs at overlook.homelinux.net> writes: > You get the idea. I've written functions that return strings, so that > part is done, but where do I go to tinker with the python interpreter to > add this new format? I would look in Objects/stringobject.c, specifically the function called PyString_FromFormatV. Sorry this is a week late, but nobody else seems to have directly addressed your question. 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 FBatista at uniFON.com.ar Mon May 10 16:29:22 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 10 May 2004 17:29:22 -0300 Subject: How to read files written with COBOL Message-ID: <A128D751272CD411BC9200508BC2194D03383971@escpl.tcp.com.ar> [John Roth] #- What's the OS for the two languages? COBOL from mainframe #- to X86ish is very different from some flavor of Windows or Unix #- COBOL. COBOL RM-85 for x86 under SCO. #- Also, are we talking fixed or variable length records? And if #- variable, how are they structured? There're a lot of different structures, there're a lot of files. I was thinking of a function where I tell the COBOL file structure and it translates it to me. #- In either case, I think the struct module (under String Services) #- is what you're looking for. I think that if I must *build* the module that I'm looking for, I'll use the struct module. But that I can not use it directly without a lot of effort (that I'm willing to avoid: that's why I'm searching for something already done, :) . 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: <http://mail.python.org/pipermail/python-list/attachments/20040510/3edceac9/attachment.html> From aahz at pythoncraft.com Thu May 13 10:44:19 2004 From: aahz at pythoncraft.com (Aahz) Date: 13 May 2004 10:44:19 -0400 Subject: Scope rule pecularities References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <slrnca428q.1i9.apardon@trout.vub.ac.be> <2gg6qfF2hi98U1@uni-berlin.de> <slrnca6akg.1i9.apardon@trout.vub.ac.be> Message-ID: <c801k3$ahf$1@panix1.panix.com> In article <slrnca6akg.1i9.apardon at trout.vub.ac.be>, Antoon Pardon <apardon at forel.vub.ac.be> wrote: > >Well one could drop the immutability of certain classes instead. One >would then loose the immutabilty purity and gain the consistency >purity. In a choice between those two purities I would choose the >latter. That won't fly. What do you use for dict keys? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From jgardner at jonathangardner.net Sun May 2 02:55:21 2004 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: 1 May 2004 23:55:21 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <69cbbef2.0404281050.4dc3380e@posting.google.com> Message-ID: <6cc20cea.0405012255.5e352d27@posting.google.com> has.temp2 at virgin.net (has) wrote in message news:<69cbbef2.0404281050.4dc3380e at posting.google.com>... > # Define object 'foo' > foo = Object() > foo.a = 3 > foo.b = 3 > foo.multiply = lambda target:target.a*target.b > I think this is the syntactic sugar that is missing: anonymous functions come in one breed only: lambdas. This example fits neatly into a lambda function, but more complicated examples won't. For instance, you can't write: def foo.multiply(self): return self.a * self.b I would imagine an easy way to do this would be to have this be acceptable: foo.multiple = def(self): returns self.a * self.b This will create an anonymous function and store it in foo.multiple. I'll admit that classless OO programming looks neat. The only thing that I can't see an obvious way of doing is to share a value or method across multiple objects. For instance: class A: number = 0 def __init__(self): number += 1 def __del__(self): number -= 1 How would you share "number" across a similar class of objects? Also, it kind of renders the question, "What kind of object is this?" meaningless. There are no /kinds/ anymore, at least not built into the language. You can go ahead and create objects that are classes, and then make objects that have an attribute called "class", I guess. I do enjoy seeing different perspectives from other communities. It helps me get a new perspective with my own programming. From imbosol at aerojockey.com Mon May 3 12:31:21 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 3 May 2004 09:31:21 -0700 Subject: PEP 328 update References: <mailman.191.1083525640.25742.python-list@python.org> Message-ID: <60dfb6f6.0405030831.4983938a@posting.google.com> Aahz <aahz at pythoncraft.com> wrote in message news:<mailman.191.1083525640.25742.python-list at python.org>... > PEP 328 (``import`` changes) has been updated and is available at > http://www.python.org/peps/pep-0328.html > > Comments on the revised version are welcome. One area where feedback is > particularly desired is on the frequency of relative imports inside > packages in current code, both in absolute terms and as a percentage of > all imports. I have one app with an ornate package system that uses relative imports all over the place (it's pretty much 100% of package imports for that package). Also, in most of my typical freestanding unitary packages without subpackages, modules typically import sister modules relatively. So, for me, relative imports are very common. In light of this, I'll probably change them all to absolute imports. -- CARL BANKS From segphault at sbcglobal.net Mon May 10 17:05:19 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 10 May 2004 21:05:19 GMT Subject: What I don't like about wxPython References: <ec6dce8b.0405081140.16b8143d@posting.google.com> <e-qdnaru-auezgDdRVn-jA@powergate.ca> <oyfnc.2626$GL4.1289@fe2.columbus.rr.com> <slrnc9vmmu.7kl.grante@grante.rivatek.com> Message-ID: <pan.2004.05.10.21.01.18.430153@sbcglobal.net> On Mon, 10 May 2004 19:41:18 +0000, Grant Edwards wrote: > On 2004-05-09, Carl Banks <imbosol at aerojockey.invalid> wrote: > >>>> Just thought I'd play devil's advocate... >>>> >>>> I tried wxPython briefly, and it had some nice features. >>>> >>>> It has a huge list of dependencies. >>> >>> 1. Python. >>> 2. Windows. >> >> The Unix version requires at least Python, gtk, and wxlib. Gtk is >> technically three libraries: gtk, gdk, and glib. gdk depends on >> libpng, probably also libjpeg. The latest version has all kinds of >> i18n dependencies. > > Yup. Trying to get wxPython installed can be a pretty > frustrating experience. > > After spending a couple hours trying to get a 2.5 version of > wxPython installed on Mandrake 9.2, I finally gave up, wiped my > disk, and installed Mandrake 10.0. It still doesn't come with > wxPython 2.5, but it has enough of the required stuff that I > don't have to build 10-15 new packages to get there... indeed. I remember having some interesting problems getting it all to compile with slackware. These days, I take the easy way out: apt-get install libwxgtk2.5-python (just a little harmless debian promotion!) ;-D From paul at prescod.net Mon May 24 13:46:38 2004 From: paul at prescod.net (Paul Prescod) Date: Mon, 24 May 2004 10:46:38 -0700 Subject: Prothon should not borrow Python strings! Message-ID: <40B234FE.8030900@prescod.net> I skimmed the tutorial and something alarmed me. "Strings are a powerful data type in Prothon. Unlike many languages, they can be of unlimited size (constrained only by memory size) and can hold any arbitrary data, even binary data such as photos and movies.They are of course also good for their traditional role of storing and manipulating text." This view of strings is about a decade out of date with modern programmimg practice. From the programmer's point of view, a string should be a list of characters. Characters are logical objects that have properties defined by Unicode. This is the model used by Java, Javascript, XML and C#. Characters are an extremely important logical concept for human beings (computers are supposed to serve human beings!) and they need first-class representation. It is an accident of history that the language you grew up with has so few characters that they can have a one-to-one correspondance with bytes. I can understand why you might be afraid to tackle all of Unicode for version 1.0. Don't bother. All you need to do today to avoid the dead end is DO NOT ALLOW BINARY DATA IN STRINGS. Have a binary data type. Have a character string type. Give them a common "prototype" if you wish. Let them share methods. But keep them separate in your code. The result of reading a file is a binary data string. The result of parsing an XML file is a character string. These are as different as the bits that represent an integer in a particular file format and a logical integer. Even if your character data type is today limited to characters between 0 and 255, you can easily extend that later. But once you have megabytes of code that makes no distinction between characters and bytes it will be too late. It would be like trying to tease apart integers and floats after having treated them as indistinguishable. (which brings me to my next post) Paul Prescod From irmen at -nospam-remove-this-xs4all.nl Thu May 13 13:39:56 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 13 May 2004 19:39:56 +0200 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <c80800$ok9$1@panix1.panix.com> References: <mailman.513.1084456098.25742.python-list@python.org> <40a39511$0$560$e4fe514c@news.xs4all.nl> <c80800$ok9$1@panix1.panix.com> Message-ID: <40a3b2f6$0$568$e4fe514c@news.xs4all.nl> Aahz wrote: >>SimpleHTTPServer reports a wrong content-length of text files on >>windows The bug is still there in this release. Any change of getting >>my patch applied? > > > Not at this point, sorry. It's generally assumed that people who care > about the progress of release schedules are subscribed to python-dev; > perhaps that assumption should be challenged. That's unfortunate, I reported it even before 2.3.3 was released. Doesn't anybody use SimpleHTTPServer then? Well, more luck next time, I guess. --Irmen P.S. I don't really see why you mentioned python-dev, are you saying that bugs and patches have more chance of being included in a new Python version if the submitter is subscribed to python-dev and also announces the bugs/patches there? From donn at drizzle.com Sat May 22 03:21:06 2004 From: donn at drizzle.com (Donn Cave) Date: Sat, 22 May 2004 07:21:06 -0000 Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> Message-ID: <1085210465.206473@yasure> Quoth Grant Edwards <grante at visi.com>: ... | I think the fact that Python lists can be heterogogenous is one | of the most brilliantly useful things in the language, but | apparently we're not supposed to use lists like that. Since | tuples aren't mutable, I'm completely at a loss as to how we're | supposed to deal with mutable heterogenous sequences. You'll have to either try to understand what people mean, or ignore them. Either will work better than the above. A heterogeneous sequence can mean at least two things, not because there's anything ambiguous about "heterogeneous" on its own, but because of the way it's applied to the sequence. The notion that this is a distinctive difference between lists and tuples is ridiculous if you take one of those meanings, sensible if you take the other. Your choice. ... |> Am I missing something again? | | If so, then I guess we both are. It's lucky you two have found each other. Donn From marklists at mceahern.com Sat May 22 09:07:01 2004 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 22 May 2004 08:07:01 -0500 Subject: cannot import csv In-Reply-To: <425cc8d1.0405220458.9668650@posting.google.com> References: <425cc8d1.0405220458.9668650@posting.google.com> Message-ID: <1085231221.3606.49.camel@dev.internal> What version Python are you using? csv was introduced with 2.3 (I think). // m On Sat, 2004-05-22 at 07:58, mir nazim wrote: > hi, > i m unable to import csv module. > it says: > > ImportError: no module named csv. > > plz help me. > > is csv module not a part of standard dist? From gael.pegliasco at free.fr Tue May 11 05:50:40 2004 From: gael.pegliasco at free.fr (gael.pegliasco at free.fr) Date: Tue, 11 May 2004 11:50:40 +0200 Subject: error handling In-Reply-To: <c7p559$6nq$05$1@news.t-online.com> References: <c7p559$6nq$05$1@news.t-online.com> Message-ID: <40a0a2a9$0$31944$626a14ce@news.free.fr> Frank Bechstein a ?crit : > I hope somebody could tell me how i can make a python script handling > errors i want that if a error is arise that the script starts all over > from then beginning and not that is is printing the error. > > thank u for helping me! I think exception can help you in this task, you can find documentation and examples in the tutorial at this url : http://www.python.org/doc/2.3.3/tut/node10.html Ga?l, From timr at probo.com Sat May 15 23:37:34 2004 From: timr at probo.com (Tim Roberts) Date: Sat, 15 May 2004 20:37:34 -0700 Subject: Python and Windows.Forms References: <mailman.350.1074089447.12720.python-list@python.org> <87n08qrpcv.fsf@pobox.com> <sTAoc.67180$sK3.3272@nwrddc03.gnilink.net> <PIydnS3kI_d-Qj7dRVn_iw@comcast.com> <40p8a0ht7uh599e5bkmacblojr1acdsc08@4ax.com> <ij8pc.127698$G_.21879@nwrddc02.gnilink.net> Message-ID: <5foda055796ui1putjgobd28pl8r8q9mh7@4ax.com> Shane <s.brennan at cox.net> wrote: > >Sorry Tim, I first learned programming with C# so when I said >Windows.Forms I meant any generic Windows form, and especially common >dialogs. My mistake! I'm glad I made though since Marijan Tadin pointed >out that python .NET link that I wasn't aware of (see his reply). Thanks >again... Interesting that this newsgroup is able to answer not only the question you ASKED, but the question you MEANT to ask... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ny_r_marquez at yahoo.com Thu May 27 10:02:36 2004 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 27 May 2004 07:02:36 -0700 Subject: Transparent PNG and PIL References: <8a27e309.0405260724.5a9c1fdc@posting.google.com> <mailman.332.1085598451.6949.python-list@python.org> Message-ID: <8a27e309.0405270602.6d0e8f59@posting.google.com> "Fredrik Lundh" wrote: > if you have an 8-bit palette image (mode "P"), you can specify the > transparency color (as a color index) when you save the image: > > im.save(filename, transparency=0) Not quite so simple. I tried this: >>> image = Image.open("Some.png") #This file has transparency set correctly. >>> image.mode 'P' >>> image.info {'transparency': 0} >>> image.save("SomeT.png", trasparency=0) >>> When I open the new image with Paintshop it seems to think that the image has trasparency set, but when I request to see it, nothing is shown. What is more, when I open the image with PIL I see this: >>> image2 = Image.open("Test.png") >>> image2.mode 'P' >>> image2.info {} So it seems to have lost the transparency. The PIL handbook doesn't mention transparency as an option of the save method for PNG files. It only mentions that the open method sets the transparency info property for transparent palette images. From aahz at pythoncraft.com Sun May 9 23:18:48 2004 From: aahz at pythoncraft.com (Aahz) Date: 9 May 2004 23:18:48 -0400 Subject: list comprehension References: <c7mii9$988$1@lust.ihug.co.nz> <c7mk94$6of$1@panix2.panix.com> <c7ml6k$c88$1@lust.ihug.co.nz> Message-ID: <c7msao$h2f$1@panix1.panix.com> In article <c7ml6k$c88$1 at lust.ihug.co.nz>, Guy Robinson <guy at NOSPAM.r-e-d.co.nz> wrote: > >This works I was just wondering if something could be written more >concisely and hopefully faster: > >s = "114320,69808 114272,69920 113568,71600 113328,72272" >e = s.split(' ') >out ='' >for d in e: > d =d.split(',') > out +='%s,%d ' %(d[0],-int(d[1])) >print out Performance I can understand (which Shalabh addressed quite nicely), but why do you care about compressing the source code? This is simple, straightforward, and easy to read; surely that's more important than saving a few bytes? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From jjl at pobox.com Sun May 16 08:51:12 2004 From: jjl at pobox.com (John J. Lee) Date: 16 May 2004 13:51:12 +0100 Subject: liburl cant load webpage with Javascript References: <c80oqk$t7$1@news2.rz.uni-karlsruhe.de> <5b3fd64f.0405140017.3d3a6538@posting.google.com> Message-ID: <87zn88mt6n.fsf@pobox.com> gatti at dsdata.it (Lorenzo Gatti) writes: > Uwe Mayer <merkosh at hadiko.de> wrote in message news:<c80oqk$t7$1 at news2.rz.uni-karlsruhe.de>... [...] > > I had a closer look at the html source and discovered a lot of Javascript, > > including Cookies. [...] > Mozilla is a web browser, and it implements cookies, DOM for HTML > pages, and a Javascript interpreter with objects representing browser > automation. > It's unlikely and inappropriate for low level HTTP implementations > like wget and liburl to have that kind of support for advanced web [...] JavaScript support is rare, but many libraries and tools support cookies (including wget and my library, ClientCookie -- essentially a drop-in replacement for urllib2). For JS, see my FAQ here (under "Embedded script is messing up my web-scraping. What do I do?"): http://wwwsearch.sourceforge.net/bits/GeneralFAQ.html > In the specific case of "IOError: connection refused, Error Code 111", > however, the failure seems to happen at a lower protocol level: wrong [...] Right. John From jacek.generowicz at cern.ch Tue May 25 03:42:04 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 May 2004 09:42:04 +0200 Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> Message-ID: <tyfd64tlzqr.fsf@pcepsft001.cern.ch> "Mark Hahn" <mark at prothon.org> writes: > Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely > once you get to 3.7e19 you are in floating point territory. I can't imagine > counting anything up to 10**19. Aaaargh ! Please don't do this. Please don't make language design decisions on the basis of your lack of imagination. It's a very good way of designing a crap language. From eriksp at attbi.nospam.com Fri May 28 05:40:41 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 28 May 2004 09:40:41 GMT Subject: Installing Python Docs Message-ID: <tODtc.4008$4A6.60@attbi_s52> When I try to view a topic for help in the command line, I get and error that says the topic and keyword documentation are not available. Then it syas to set the environment variable 'PYTHONDOCS' to indicate their location. How do you set environment variables? I looked in the tutorial but couldn't find anything. And And doesn't python come with those files already installed if you install everything? From M.Waack at gmx.de Fri May 14 11:11:50 2004 From: M.Waack at gmx.de (Mathias Waack) Date: Fri, 14 May 2004 17:11:50 +0200 Subject: smtplib - missing message References: <23ae7099.0405140440.341a6244@posting.google.com> <reKdnYb-JcNqVDndRVn-gQ@powergate.ca> Message-ID: <m64fn1-or3.ln1@valpo.de> Peter Hansen wrote: > msg = "Subject: test\n\nPlease display me." Better use the mime classes from package "email": msg = MIMEText("Please display me.").as_string() Mathias From hungjunglu at yahoo.com Mon May 3 11:11:12 2004 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 3 May 2004 08:11:12 -0700 Subject: Jabber for distributed computing Message-ID: <8ef9bea6.0405030711.7ab7c1ec@posting.google.com> Hi, Has anyone tried this approach? Although a bit esoteric, it seems to make sense. After all, cluster computers do seem like chatters. It'll be nice to use Jabber also for the administrative part. One question is: when exchanging really long messages (say, 100MB), is there a problem? (That is, does it make unnecessary copies somewhere along the way?) Also, which server is good for Windows, and which one is easy (and free) to setup as something to play with? Any recommendations? (I tried once, but the installation was complicated.) regards, Hung Jung From Holger.Joukl at LBBW.de Wed May 26 03:03:36 2004 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Wed, 26 May 2004 09:03:36 +0200 Subject: Python find Message-ID: <OF2C85D3E0.FB545610-ONC1256EA0.00263C4F-C1256EA0.0026AA15@lbbw.sko.de> >Some questions I have for now: > >- How can one get the filesystem name from python (e.g. for testing >'find -fstype nfs') ? We are using a statvfs extension module here whose statvfs function returns the filesystem type, as opposed to os.statvfs. I can post the code if you haven?t found a simpler solution by now. G Holger Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From dlissett0 at yahoo.com Thu May 13 02:11:28 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 12 May 2004 23:11:28 -0700 Subject: make faster Richards benchmark Message-ID: <6748553f.0405122211.5be5a150@posting.google.com> I'd appreciate any suggestions on how to make faster Python implementations of Richards benchmark. Perhaps there are obvious problems that can be corrected? http://www.lissett.com/ben/bench1.htm From SeeBelow at SeeBelow.Nut Fri May 21 12:20:06 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Fri, 21 May 2004 16:20:06 GMT Subject: Pyrex - The speed of Python with the clarity of C? Message-ID: <40AE2C4E.CE1CE6C0@shaw.ca> I just read "about Pyrex" at http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/version/Doc/About.html It seems that it is not compiled into machine code, as C would be, and therefore it does not offer the only valid reason for using C, which is for an increase in execution speed. The word "speed" does not appear on the above web page. Am I wrong about this? Perhaps I don't understand how Pyrex works. At ANNEvolve we are beginning to use Python, and we are learning how to call C functions, which is a requirement for us, because neuroevolution code often must run for many hours, even when it is pure C. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From kenneth.m.mcdonald at sbcglobal.net Mon May 31 14:32:28 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 31 May 2004 18:32:28 GMT Subject: Best way to put out a small package for public scrutiny and use? Message-ID: <slrncbmuhs.1ec.kenneth.m.mcdonald@g4.gateway.2wire.net> I've created a small (and I believe, very useful) package to ease the creation and use of regular expressions. I'd like to make it available, (though the first release will be aimed mostly at finalizing functionality, not at being a polished project.) I don't want to use SourceForge, as I don't use CVS, and I'm not yet ready (if ever) to open up my home Subversion server to public access. If this was just a single file, I'd simply post it in this newsgroup to start with, but as it incorporates a couple of files, I need to post the directory somehow. Any thoughts as to the best way to make this package available? Thanks, Ken From davidf at sjsoft.com Wed May 12 10:21:26 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 12 May 2004 16:21:26 +0200 Subject: distutils question In-Reply-To: <q_-dnb6-0p-ljT_dRVn-gQ@is.co.za> References: <q_-dnb6-0p-ljT_dRVn-gQ@is.co.za> Message-ID: <c7tbgp$1ua$1@ctb-nnrp2.saix.net> tcronj wrote: > Hi, > > I've written a disutils setup scripts to create a binary win32 > installation package. All works fine but I have 2 questions. > (usage: python setup.py bdist --formats=wininst) > > > 1.) The is application is commandline driven. I want the distribution > .exe to copy certian .py files into a spesified or current directory, > rather than into the site-packages/package directory. > This should be exaplined in the distutils documentation > 2.) How do I specify that only .pyc files gets distributed. (I want to > hold on to the source until the money is in the bank :) See https://sourceforge.net/tracker/?func=detail&atid=305470&aid=793070&group_id=5470 Its a patch I submitted to add a remove-source option (it may need some reworking... let me know if you need an updated Python 2.3.3 version) David From usenet_spam at janc.invalid Sun May 2 22:10:04 2004 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 May 2004 02:10:04 GMT Subject: Path ... where is my application's home dir? References: <mailman.81.1083164606.25742.python-list@python.org> <Xns94D9B0A6BEE74duncanrcpcouk@127.0.0.1> <c6ovte$5im$1@biggoron.nerim.net> <p8WdnYsB5t5PmQ3dRVn-hw@powergate.ca> <Xns94DB3B44C6806JanC@213.118.38.102> <ef6em1-3ft.ln1@home.rogerbinns.com> Message-ID: <Xns94DE2A65D8213JanC@213.118.38.102> "Roger Binns" <rogerb at rogerbinns.com> schreef: > You can compare with Google where you can see their worldwide figures > for March: http://www.google.com/press/zeitgeist.html > They have 22% for Windows 98, which seems to take proportionally > from the figures in my stats. At least, they are pretty close to my guess... :-) > Of course we don't know what percentage of people configure their > browsers to lie. And: - what percentage of people have a PC and no internet access... - what percentage have a PC & internet at work but aren't allowed to use it for visiting your site (or other non-work-related sites). - etc. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From romanschlegel at hotmail.com Wed May 5 03:50:41 2004 From: romanschlegel at hotmail.com (Roman Schlegel) Date: 5 May 2004 00:50:41 -0700 Subject: cvs2svn.py can't access cvs db Message-ID: <fa50eff1.0405042350.60ab4bf2@posting.google.com> I am trying to get my data from the cvs to the new svn repository, both on a sparc solaris 5.8 system. - The python package 2.3.3 is from http://sunfreeware.com - bsddb3-4.2.4 from http://pybsddb.sourceforge.net - Berkeley DB 4.2.52 from http://www.sleepycat.com - Subversion 1.0.2 from http://subversion.tigris.org - CVS 1.11 Not even a dump from an existing cvs repository works: $ cvs2svn.py --dump-only --dumpfile test.dump /path/to/my/repos Traceback (most recent call last): File "cvs2svn.py", line 3211, in ? main() File "cvs2svn.py", line 3201, in main ctx.default_branches_db = Database(DEFAULT_BRANCHES_DB, 'n') File "cvs2svn.py", line 192, in __init__ self.db = anydbm.open(filename, mode) File "/usr/local/lib/python2.3/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.3/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.3/site-packages/bsddb3/__init__.py", line 293, in hashopen d.open(file, db.DB_HASH, flags, mode) bsddb._db.DBInvalidArgError: (22, 'Invalid argument -- DB_TRUNCATE illegal with locking specified') ... If I run "run-tests.py", the output is as follows: $ run-tests.py -v CMD: cvs2svn.py <TIME = 0.916313> PASS: run-tests.py 1: cvs2svn with no arguments shows usage CMD: cvs2svn.py "--bdb-txn-nosync" "-s" "main-svnrepos" "/opt/cvs2svn/test-data/main-cvsrepos" <TIME = 9.206150> /opt/cvs2svn/cvs2svn.py said: Traceback (most recent call last): File "/opt/cvs2svn/cvs2svn.py", line 3211, in ? main() File "/opt/cvs2svn/cvs2svn.py", line 3202, in main convert(ctx, start_pass=start_pass) File "/opt/cvs2svn/cvs2svn.py", line 2969, in convert _passes[i](ctx) File "/opt/cvs2svn/cvs2svn.py", line 2878, in pass5 os.unlink(SVN_REVISIONS_DB) OSError: [Errno 2] No such file or directory: 'cvs2svn-revisions.db' FAIL: run-tests.py 3: conversion of filename with a space ... Thanks for your input From me at privacy.net Thu May 6 04:36:53 2004 From: me at privacy.net (Duncan Booth) Date: 6 May 2004 08:36:53 GMT Subject: Is IronPython open source or not ? References: <c7cehg$stq$1@news.ust.hk> Message-ID: <Xns94E161AF32E0Eduncanrcpcouk@127.0.0.1> "CHEN Benfeng" <bfchen at ust.hk> wrote in news:c7cehg$stq$1 at news.ust.hk: > I am interested in IronPython and want to have a study on the source > code. But I cannot find any download link in the homepage of IronPython. > The source code has not been released, so all the information is what you find on the homepage. You might also be interested in my 'Python on .Net' talk from this year's ACCU conference. Although I haven't seen IronPython any more than anyone else, I was working on a similar port and I believe I used similar solutions to many of the issues. See http://www.suttoncourtenay.org.uk/duncan/accu for the slides and background paper for my talk. From wjb131 at web.de Mon May 10 17:30:46 2004 From: wjb131 at web.de (Wolfgang Buechel) Date: 10 May 2004 14:30:46 -0700 Subject: nested for loop Message-ID: <4629559b.0405101330.286ddb32@posting.google.com> Hi, I want to iterate over all 2x2 matrices with elements in range 0..25 (crypto-stuff). To produce them, first I wrote a fourfold nested for loop: M=26 for a in range(M): for b in range (M): for c in range (M): for d in range (M): matr = [[a,b],[c,d]] (dosomething) Then I had a look in comp.lang.python and found: for (a,b,c,d) in [(x,y,z,t) for x in range(M) for y in range(M) for z in range(M) for t in range(M)] : matr = [[a,b],[c,d]] Is there a shorter (and probably, with respect to exec time, faster) way to write such a 4for loop? (I want to scan 3x3, 4x4 matrices too (;-) -- Wolfgang From timr at probo.com Wed May 26 03:40:30 2004 From: timr at probo.com (Tim Roberts) Date: Wed, 26 May 2004 00:40:30 -0700 Subject: Problem with uudecode References: <pan.2004.05.25.16.42.14.955307@but.no.spam> Message-ID: <84i8b09mq875ik2as9kacp37t6q1461i9s@4ax.com> Juho Saarikko <sorry at but.no.spam> wrote: >I made a Python script which takes Usenet message bodies from a database, >decodes uuencoded contents and inserts them as Large Object into a >PostGreSQL database. However, it appears that the to last few bytes >of uudecoded data are always mangled. Take a look of this hexdump output: > >Originals (decoded with Pan, each line is from a different file): >000c2c0 e1bf 00ff 2541 a9e4 a724 d9ff >0011a10 ff54 00d9 >00093e0 fb4f a80d ffd9 c200 ffef 00d9 > >Decoded by the script: >000c2c0 e1bf 00ff 2541 a9e4 a724 d0ff >0011a10 ff54 00d8 >00093e0 fb4f a80d ffd9 c200 ffef 00d8 > >As you can see, one of the last two bytes gets altered in all cases. As others have pointed out, it's really the last byte that is getting altered. > for k in range(n+1, message.ntuples): ># print "Decodind row " + str(k) > s = message.getvalue(k, 0) > if s[:3] == "end": > n = k + 1 > break > try: > body.append(binascii.a2b_uu(s)) > except: > try: > bytes = (((ord(s[0])-32) & 63) * 4 + 3) / 3 > body.append(binascii.a2b_uu(s[:bytes])) > except: > print "Broken attachment in message " + str(id) > conn.query("ROLLBACK") > return Your computation of the number of bytes in the uuencoded string will come up one short: you're not accounting for the length byte. That will have exactly the effect you describe. You lose the last encoded character, which means you'll miss the last 6 bits of the file. Change it to this: bytes = (((ord(s[0])-32) & 63) * 4 + 3) / 3 + 1 However, you should not need to wrap the first binascii.a2b_uu call with try/except at all. What is happening that causes the error in the first place? I suspect if you fix the root cause, you could eliminate the except clause altogether. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From shalabh at cafepy.com Sun May 9 21:40:56 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 09 May 2004 18:40:56 -0700 Subject: list comprehension In-Reply-To: <c7ml6k$c88$1@lust.ihug.co.nz> References: <c7mii9$988$1@lust.ihug.co.nz> <c7mk94$6of$1@panix2.panix.com> <c7ml6k$c88$1@lust.ihug.co.nz> Message-ID: <c7mmd7$9a2$1@sea.gmane.org> Guy Robinson wrote: > This works I was just wondering if something could be written more > concisely and hopefully faster: > s = "114320,69808 114272,69920 113568,71600 113328,72272" > e = s.split(' ') > out ='' outl = [] > for d in e: > d =d.split(',') > out +='%s,%d ' %(d[0],-int(d[1])) outl.append(s) # where s is the string you construct out = ' '.join(outl) > print out > > Guy > It's faster to collect strings in a list and join them later than to concatenate strings one by one. Also, do you have to convert d[1] to int? If you are sure that it is always a positive integer, you can do '%s,-%s' % (d[0],d[1]). In fact you could even try to replace ',' with ',-' instead of splitting the string at all. Of course it depends on what the format of your incoming string is. -- Shalabh From peter at engcorp.com Wed May 26 09:46:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 09:46:15 -0400 Subject: Bad interpreter In-Reply-To: <c9245j$pbo$05$1@news.t-online.com> References: <pan.2004.05.26.10.53.22.466189@sntteam.org> <Vs2dnYk8pZhf5yndRVn-gw@powergate.ca> <c9245j$pbo$05$1@news.t-online.com> Message-ID: <leSdnVb_NqE6AindRVn-ig@powergate.ca> Benjamin Niemann wrote: > Peter Hansen wrote: >> Remove the hidden CR character which you got at the end of the >> lines by moving the file to a Windows system and editing it. ;-) >> >> This one is pretty tricky to figure out the first few times... > > Should be the other way 'round: If you edit the file under Windows (e.g. > with Notepad), (invisible) CRs are added. We're saying the same thing. You call them invisible, I call them hidden, and we're both saying they got added when he edited the file under Windows. If he were to open the file in, say, "vi" instead, on Linux, it would display the ^M endings, no doubt, at least if he entered ":set list" to display invisible characters. > One way to fix this on a Linux/UNIX system would be: > tr -d '[\r]' <script.py >fixed_script.py Good idea. -Peter From kirk at eyegor.jobsluder.net Tue May 11 09:25:06 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Tue, 11 May 2004 13:25:06 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <slrnca0ub4.1bdc.kirk@eyegor.jobsluder.net> <Xns94E6836B575B3duncanrcpcouk@127.0.0.1> Message-ID: <slrnca1l2k.1rer.kirk@eyegor.jobsluder.net> On 2004-05-11, Duncan Booth <me at privacy.net> wrote: > Kirk Job-Sluder <kirk at eyegor.jobsluder.net> wrote in > Your code might have been a bit shorter if you had used the existing > facility in Python for editing files in place. The code below is completely > untested, so I can all but guarantee it doesn't work, but you get the idea: > > #!/usr/local/bin/python > import getopt,sys,os,re > import fileinput Thanks! Learn something new every day. I would argue that length of code is less an issue than the nasty exec statement. From NAIGIMSESRIMAIL at gims.com Mon May 17 11:22:46 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Mon, 17 May 2004 17:22:46 +0200 Subject: ALERT - GroupShield ticket number OB31_1084807359_ESRIMAIL_3 was generated Message-ID: <B06B8FEF47ACD7119E720040F42845910322A383@ESRIMAIL> Action Taken: The message was blocked because of its subject. To: python-list at python.org <python-list at python.org> From: hoel at gl-group.com <hoel at gl-group.com> Sent: -894738432,29637666 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1821 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040517/b3e675bb/attachment.bin> From kveretennicov at yahoo.com Wed May 12 11:32:17 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 12 May 2004 08:32:17 -0700 Subject: Urllib.urlencode question? References: <p%hoc.113536$Jy3.54431@fed1read03> Message-ID: <5155aad2.0405120732.646a98d4@posting.google.com> "Sean Berry" <sean_berry at cox.net> wrote in message news:<p%hoc.113536$Jy3.54431 at fed1read03>... > the desired result will be in the form > > n=2&userid0=sean&username0=Sean%20Berry&email0=sean_berry%40cox.net&userid1= > pam&username1=Pam%20Ward&email1=pam_ward%40cox.net > > How can achieve adding the numbers to the end of the variable names so that > they can be used by Flash's loadVars function. > I don't know anything about Flash loadVars, but how about this: fields = ['userid', 'username', 'email'] users = [ ['sean', 'Sean Berry', 'sean_berry at cox.net'], ['pam', 'Pam Ward', 'pam_ward at cox.net'] ] pairs = [('n', len(users))] for i, u in enumerate(users): numbered_fields = [f + str(i) for f in fields] pairs += zip(numbered_fields, u) import urllib print urllib.urlencode(pairs) - kv From sdeibel at wingware.com Mon May 3 14:58:44 2004 From: sdeibel at wingware.com (Stephan Deibel) Date: Mon, 3 May 2004 14:58:44 -0400 (EDT) Subject: O'Reilly Python Success Stories, volume II Message-ID: <Pine.LNX.4.50.0405031456000.3387-100000@hedgehog> Hi, O'Reilly Associates has agreed to print a second volume of Python Success Stories and I am looking for contributors of new stories. This booklet will showcase Python in the context of a variety of successful software projects, explaining why Python was a good choice. It is used by O'Reilly as a freebie to market its own books, and it's a great way to get the word out about Python and your company or project. The first Python Success Stories booklet came out in May 2003 and can be viewed here: http://python.oreilly.com/news/python_success_stories.pdf The second printed volume is planned for release before OSCON 2004 (July), and all the stories (even those that don't fit in the book) will be distributed via O'Reilly's and several other websites. There is more information on contributing a story here: http://pythonology.org/successguide Examples of finished stories are here: http://pythonology.org/success Thanks, Stephan Deibel -- Wingware Wing IDE for Python Advancing Software Development www.wingware.com From jcm at FreeBSD-uk.eu.org Thu May 6 16:57:32 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Thu, 6 May 2004 21:57:32 +0100 Subject: Pmw Blt problems on *nix Message-ID: <20040506205732.GA37649@dogma.freebsd-uk.eu.org> I have blt installed, and pmw works fine. But trying a simple demo crashed blt. I saw something similar posted for window, but I am running FreeBSD. Any ideas? snakepit:...python/prototypes/bltgraph> python hello.py Traceback (most recent call last): File "hello.py", line 60, in ? vector_x = Pmw.Blt.Vector() File "/usr/local/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBlt.py", line 99, in __init__ self.tk.call(_vectorCommand, 'create', self._name) _tkinter.TclError: invalid command name "::blt::vector" Exception _tkinter.TclError: 'invalid command name "::blt::vector"' in <bound method Vector.__del__ of []> ignored snakepit:...python/prototypes/bltgraph> jm -- My other computer is your Windows box. From Mike at DeleteThis.Geary.com Thu May 27 12:15:52 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 27 May 2004 09:15:52 -0700 Subject: How to I print without newline ? References: <mailman.364.1085670411.6949.python-list@python.org> Message-ID: <10bc51p5oalj682@corp.supernews.com> > I want to print, but without newline. I want to create a progress for > ftp, but the print is drop a newline for every percent. > I want like this: > > 0% 25% 50% 75% 100% > > But this happening: > 0% > 25% > 50% > 75% > 100% > > How to I prevent the newlines ? Since you want spaces between the values, a comma at the end of the print statement will do the trick: >>> for p in ( 0, 25, 50, 75, 100 ): ... print '%s%%' % p, ... 0% 25% 50% 75% 100% >>> In the more general case, where you want complete control and want to be able to prevent this extra space, use sys.stdout.write(): >>> for i in xrange(20): ... sys.stdout.write( '+' ) ... ++++++++++++++++++++>>> Note that there wasn't a newline at the end. You'll need to do a sys.stdout.write('\n') when you want one. -Mike From ppercot at free.fr Sun May 30 10:37:52 2004 From: ppercot at free.fr (Patrick Percot) Date: Sun, 30 May 2004 16:37:52 +0200 (CEST) Subject: confirm 4f3e88889f326a8c272fdd08ec36583cd6be27e7 In-Reply-To: <mailman.0.1085927852.9290.python-list@python.org> References: <mailman.0.1085927852.9290.python-list@python.org> Message-ID: <20040530.163752.25479867.ppercot@free.fr> On Sun, 30 May 2004 10:37:32 -0400, python-list-request at python.org wrote > Mailing list removal confirmation notice for mailing list Python-list > > We have received a request for the removal of your email address, > "ppercot at free.fr" from the python-list at python.org mailing list. To > confirm that you want to be removed from this mailing list, simply > reply to this message, keeping the Subject: header intact. Or visit > this web page: > > http://mail.python.org/mailman/confirm/python-list/4f3e88889f326a8c272fdd08ec36583cd6be27e7 > > > Or include the following line -- and only the following line -- in a > message to python-list-request at python.org: > > confirm 4f3e88889f326a8c272fdd08ec36583cd6be27e7 > > Note that simply sending a `reply' to this message should work from > most mail readers, since that usually leaves the Subject: line in the > right form (additional "Re:" text in the Subject: is okay). > > If you do not wish to be removed from this list, please simply > disregard this message. If you think you are being maliciously > removed from the list, or have any other questions, send them to > python-list-owner at python.org. > ?+ PP -- Groupe Morbihannais d'Utilisateurs de Logiciels Libres http://www.tuxbihan.org Identifiant Jabber: pp at amessage.de GPG fingerprint = 1A4F E154 3D2C A20E E4CA A543 7951 C5C2 E44A A0B5 Patrick Percot. From me at privacy.net Thu May 13 07:50:23 2004 From: me at privacy.net (Heather Coppersmith) Date: 13 May 2004 07:50:23 -0400 Subject: perl to python References: <mailman.478.1084391040.25742.python-list@python.org> <du74qqkdh1f.fsf@mozart.cc.tut.fi> Message-ID: <m2isf0fsw0.fsf@unique.phony.fqdn> On 13 May 2004 08:37:00 +0300, Ville Vainio <ville at spammers.com> wrote: > Because Python code is more readable and maintainable. That is a > huge win in multi-maintainer situations (which is typical in > production code) ... Agreed. > ... You can also bump up the functionality of the script while > porting, and get better reuse. That part makes me cringe. Port first. Make sure the new code still passes every *old* test you can find. Write new tests against the current functionality and the new code; porting inevitably leads to new corner cases and language idiosyncrasies. Bump the functionality later. If I'm the manager and I hear, "feature X, which wasn't even in the old code, is almost working; but featyre Y, which was in the old code, seems to be broken," then heads will roll. Obviously, e.g., porting an OS from one hardware platform to another (which I've done, more than once) will lead to functionality changes, but there had better not be any bumping until you know that the port is at least as solid as the original. Most of the time, though, it's the other way around: you find bugs in the old code due to the new scrutiny, but then you have the nasty problem of determining whether or not something else depends on the buggy behavior (but that's a better topic for a new thread on another newsgroup). At that point, bumping the functionality during the port could be extremely troublesome. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From uche at ogbuji.net Tue May 18 08:39:06 2004 From: uche at ogbuji.net (Uche Ogbuji) Date: 18 May 2004 05:39:06 -0700 Subject: sending out XML from python. References: <03foc.111778$Jy3.44600@fed1read03> <3o2dnQnr_4xJDDzdRVn_iw@powergate.ca> <c7t82f$23h$1@sea.gmane.org> <mailman.454.1084368087.25742.python-list@python.org> Message-ID: <d116fbae.0405180439.666b3c8e@posting.google.com> Paul Prescod <paul at prescod.net> wrote in message news:<mailman.454.1084368087.25742.python-list at python.org>... > Brad Clements wrote: > > > Also consider elementtree > > > > http://effbot.org/zone/element-index.htm > > > > And pygenx, which is specifically designed for this task: > > http://software.translucentcode.org/pygenx/ > > And it wouldn't hurt to spend 20 minutes poking around Uche's treatises > on the topic: > > http://www.xml.com/pub/a/2003/10/15/py-xml.html Since emitting XML is usually more complex than people think, I also recommend the article in which I go over basic principles: http://www.xml.com/pub/a/2002/11/13/py-xml.html --Uche http://uche.ogbuji.net From mogmios at mlug.missouri.edu Thu May 6 22:11:40 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Thu, 06 May 2004 19:11:40 -0700 Subject: MySQL vrs SQLite In-Reply-To: <4099890c$0$32558$afc38c87@news.optusnet.com.au> References: <mailman.283.1083787205.25742.python-list@python.org> <4099890c$0$32558$afc38c87@news.optusnet.com.au> Message-ID: <409AF05C.4060701@mlug.missouri.edu> >In short, sqlite is a *very* capable little database, as long as it only >ever has one user. More than one user, and it'll block access so only one >user may access it at a time. > > It does block though - it doesn't loss data if more than one program tries to access it at once? In this case I have multiple programs that need to write to, and read from, the db in a reliable way. Most of the actions should be small so I don't think blocking should pose a big question but data loss would be very bad. >SQLite treats all data as strings, but note that it does some internal >"typecasting" such that a column of numbers will be sorted numerically. You >will need to implement your own data conversion though. It's usually as >trivial as a simple mapping containing conversion functions like (from the >Roundup source): > > I always type cast, and otherwise clean, all data coming in and out of my db functions anyway (for security reasons) so that isn't a problem. Since SQLite stores data as strings that means data such as numbers will take up more space than in a db such as MySQL? From nhodgson at bigpond.net.au Sat May 8 02:56:29 2004 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 08 May 2004 06:56:29 GMT Subject: Needed: Python IDE for the visually impaired References: <mailman.322.1083863230.25742.python-list@python.org> Message-ID: <xw%mc.26717$TT.7204@news-server.bigpond.net.au> Michael Chermside: > I received a request from John Guildford, asking whether there is > an IDE available for Python development which will work with > Window-Eyes, Jaws, or other common screen readers. Unfortunately, > IDLE will not work (presumably because the TK widgets are not > standard windows widgets). It is unlikely that any of the Scintilla based IDEs (Komodo, PythonWin, HAP, Boa, Wing, SciTE, ...) will be suitable as Scintilla is a custom control. Scintilla is also incompatible with screen magnifiers as it does not use the standard Windows caret. Neil From ivoras at __geri.cc.fer.hr Thu May 20 14:36:37 2004 From: ivoras at __geri.cc.fer.hr (Ivan Voras) Date: Thu, 20 May 2004 20:36:37 +0200 Subject: Why does the "".join(r) do this? In-Reply-To: <c8ilnb$t1p$00$1@news.t-online.com> References: <545cb8c2.0405200738.296bb094@posting.google.com> <mailman.111.1085068298.6949.python-list@python.org> <c8ilnb$t1p$00$1@news.t-online.com> Message-ID: <c8itrm$epg$1@bagan.srce.hr> Peter Otten wrote: > Skip Montanaro wrote: > > >>Try >> >> u"".join(r) >> >>instead. I think the join operation is trying to convert the Unicode bits >>in your list of strings to strings by encoding using the default codec, >>which appears to be ASCII. > > > This is bound to fail when the first non-ascii str occurs: Is there a way to change the default codec in a part of a program? (Meaning that different parts of program deal with strings they know are in a specific different code pages?) -- C isn't that hard: void (*(*f[])())() defines f as an array of unspecified size, of pointers to functions that return pointers to functions that return void. From mwh at python.net Mon May 17 04:57:52 2004 From: mwh at python.net (Michael Hudson) Date: Mon, 17 May 2004 08:57:52 GMT Subject: RELEASED Python 2.3.4, release candidate 1 References: <67B3A7DA6591BE439001F2736233351202B479BA@xch-nw-28.nw.nos.boeing.com> <mailman.31.1084583605.4157.python-list@python.org> Message-ID: <m3brknh1m7.fsf@pc150.maths.bris.ac.uk> Skip Montanaro <skip at pobox.com> writes: > >> Why do you think the standard and near-universal ./configure > >> && make && make install is tedious? > > Joseph> I would avoid installing applications that way, if only for the > Joseph> fact that you can't uninstall an application. Package > Joseph> management exists for a reason. And once a package is created, > Joseph> installing the application should be a snap. > > Submit the necessary magic and I'm sure it would get incorporated into the > distribution. I think the basic pieces are there. Distutils can build RPMs > I believe. I know Sean Reifschneider builds RPMs with some small lag time > after a release. Perhaps what he does (a spec file?) can be incorporated > into the distribution and an extra target added to the Makefile to simplify > building it. The spec files are in Misc/RPM. I have no idea what you have to do to make an rpm from there though (hey, I've only just learnt how to build binary rpms from .src.rpms after, what, 6 years of being a redhat user...). Cheers, mwh -- Some people say that a monkey would bang out the complete works of Shakespeare on a typewriter give an unlimited amount of time. In the meantime, what they would probably produce is a valid sendmail configuration file. -- Nicholas Petreley From tdelaney at avaya.com Tue May 4 00:20:58 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 4 May 2004 14:20:58 +1000 Subject: Very, very strange problem with properties Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE017296CB@au3010avexu1.global.avaya.com> Kenneth McDonald wrote: > class foo: > def __init__(self): > self._x = 3 > > def __setx(self, val): > print "Calling __setx" > pass > > x = property(fget=lambda self: self._x, fset=__setx) That should be: class foo (object): Tim Delaney From viswap at math.net Sun May 2 04:48:59 2004 From: viswap at math.net (Viswa) Date: 2 May 2004 01:48:59 -0700 Subject: reading data columns into separate lists Message-ID: <354e45f1.0405020048.47db6957@posting.google.com> PythonGurus, I would like to read the ascii data from a file with many columns into a list. I want the type to be float. data=open('dat1.dat','r') lines=data.readlines() print lines Here, the data x1,x2,x3,x4 are separated by tabs and end with new line. 1\t2\t3\t4\n ... ... Is there a way to read the delimiter separated data straightaway to a list of fixed type. Thanks in advance, viswa. From htx1 at gmx.de Mon May 10 17:55:51 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Mon, 10 May 2004 23:55:51 +0200 Subject: Passing objects to a function In-Reply-To: <c7nti4$vkm$1@news-reader2.wanadoo.fr> References: <mailman.385.1084145984.25742.python-list@python.org> <c7n757$3ll$06$1@news.t-online.com> <c7nti4$vkm$1@news-reader2.wanadoo.fr> Message-ID: <c7otn5$que$02$1@news.t-online.com> bruno modulix wrote: > Holger T?rk a ?crit : > (snip) > >> >> This could be supported by an assert statement: >> >> def BlackJackValue(hand): >> """BlackJackValue(Hand_instance) -> int\n\nReturn an integer, which >> is the value of the Hand according to the rules of BlackJack.""" >> >> assert isinstance (hand, Hand) >> >> [...] >> >> The method will throw an AssertionError if hand is not >> an instance of Hand. Assertions can be turned off later for >> performance reasons; with -O I guess. > > > Note that this is also highly unpythonic since you won't be able to pass Unpythonic? That's a matter of taste. So: maybe. > objects that implements the Hand interface but do not subclass Hand. > This may not be a problem in this specific case, but this probably > should not be recommanded in the general case unless there is a very > compelling reason to do so... The assert statement, as it is used in the example above, describes the assumptions the programmer had in mind when writing the function it is written in. In addition, the expression happens to be understood by the interpreter, too. So the assumption can be checked. It's a pity documentation cannot be generated therefrom. Programs are not written into stone. When the need arises, the assert statement can be modified, e.g. to check an interface (hasattr (hand, containsCard), or something else), or even removed. Because documentation regularly turns out to be neglected and assert statements are easily written, it's recommended to use them unless there is a good reason to drop them. In this special case, Thomas clearly wanted to express that the parameter hand should be an instance of Hand. So why shouldn't it be documented and checked this way? Greetings, Holger From jeffbarish at starband.net Wed May 26 12:03:26 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Wed, 26 May 2004 10:03:26 -0600 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: <c92f4m$34k$1@sea.gmane.org> SeeBelow at SeeBelow.Nut wrote: > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be > one instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since > a strength of Python is rapid application development, it slows one > down > to have to put in all those self.'s. The code seems much cleaner to > me > without classes that have only one instance. Oh, also, all the > methods of this class will have to have the instance name prepended to > them. > > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. > > Mitchell Timin > As a novice Python programmer, I also thought about this question recently and came up with one other rationale that no one else has mentioned yet. (If this rationale is wrong, I would value elucidation.) An instance also retains state whereas a function does not (because the instance continues to exist). For example, if you create the function def assigner(): x = 2 the variable x exists only when test runs. A second function printer() def printer(): print x will not print the value assigned to x in assigner. (You get a traceback because global variable x is not defined.) If you want x to continue to exist after assigner runs, you must declare it global. Thus, with def assigner(): global x x = 2 printer() will print the value assigned to x in assigner. When assigner is a method, you can cause x to continue to exist by prepending self. All variables with self prepended have global scope within the instance. Thus, class tester: def assigner(self): x = 1 def printer(self): print x # global variable x not defined t = tester() t.assigner() t.printer() will not work (for the same reason it does not work with the functions above), whereas class tester: def assigner(self): self.x = 1 def printer(self): print self.x # self.x is global within scope of instance t = tester() t.assigner() t.printer() prints 1. It works to have a bunch of global variables in a module rather than a single-instance class, but you may have to be more careful about name clashes as the code expands. Using a single-instance class provides another level of control over scope. Thus, you could have more than one single-instance class in a module each defining its own namespace whereas the code that lives in the other classes would otherwise have to go in separate modules to provide the same degree of namespace isolation. Also, with global declarations, it's hard to tell when you read the code whether a variable has been declared global, whereas the "self." prefix essentially announces that the corresponding variable has been declared to have global scope within the instance. -- Jeffrey Barish From peter at engcorp.com Thu May 20 02:54:02 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 02:54:02 -0400 Subject: socket programming question In-Reply-To: <81dff960.0405192228.1e94f3b@posting.google.com> References: <81dff960.0405192228.1e94f3b@posting.google.com> Message-ID: <CPudnbcVxayXyzHdRVn-tw@powergate.ca> xunil wrote: > assuming am sitted on my PC, and want to be notified when some one > else logs on to his machine. throught some kind of pop-up > > how can i use C socket programming concepts to achieve this ? A couple of questions: 1. Why do you say "C" specifically? This is a newsgroup/mailing list for the Python language. Surely you aren't saying you don't want to use Python for this? 2. Why constrain the solution at all like that? Wouldn't you prefer to use the simplest solution, even if it doesn't involve writing code that directly uses sockets? 3. (Okay, I have three questions...) What platform? OS? GUI? -Peter From jzgoda at gazeta.usun.pl Sun May 23 06:08:15 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 23 May 2004 10:08:15 +0000 (UTC) Subject: problems with module Cookie References: <2pbva0phmailum53q9stnn8ugn00smt26v@4ax.com> <c8obsk$i6k$1@atlantis.news.tpi.pl> <pgs0b0dr6ur10tovkofhi4r2v72egsb8ep@4ax.com> Message-ID: <c8pt6e$r4f$1@atlantis.news.tpi.pl> Manlio Perillo <NOmanlio_perilloSPAM at libero.it> pisze: >>> I'm using the Cookie module (on the client side). > > ^^^ >>> I have found a problem trying to parse the cookie: >>> >>> "Set-Cookie: value=thevalue; path=/; >>> expires=Fri, 21-May-2004 10:40:51 GMT" >> >>You must use date in UTC format. > > This is the date format used by the server cookie! See http://www.w3.org/TR/NOTE-datetime on how should date look in cookies. If date is not in valid format, the module functions may have trouble decoding it. -- Jarek Zgoda http://jpa.berlios.de/ From sholden at holdenweb.com Tue May 25 18:57:18 2004 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 25 May 2004 18:57:18 -0400 Subject: Fwd: Python opening in NY In-Reply-To: <mtNsc.20176$zs2.7774@fe39.usenetserver.com> References: <mtNsc.20176$zs2.7774@fe39.usenetserver.com> Message-ID: <taQsc.182486$f_5.21035@lakeread01> Hans Nowak wrote: > > I got the following email from Darsh Mehta. I am unable to move to New > York myself, but maybe someone else here will be interested. In that > case, please contact this person. He says he can pay up to $35/hr. > [...] Just as a matter of interest, is $35 currently considered an acceptable hourly rate for programming in the Big Apple? I wouldn't have thought so ... regards Steve From gabriel.cooper at mediapulse.com Mon May 24 17:08:19 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 24 May 2004 17:08:19 -0400 Subject: subclassing built-in types Message-ID: <40B26443.6010909@mediapulse.com> I have data in lists of dictionaries with an accompanying array that I would like to be able to treat as a normal array of strings so that it will work with predefined functions that work with such, but I would also like to have the ability to add and manipulate attributes, such as each field's padding for output of the corresponding data: (Running on RHFC2) 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 [...] IDLE 1.0.2 >>> class myString(str): def __init__(self, thestring, padding=0, *args,**kargs): str.__init__(self,thestring, *args,**kargs) self.padding = padding >>> x = myString("hello") >>> x 'hello' >>> x.padding 0 >>> x = myString("hello",40) Traceback (most recent call last): File "<pyshell#205>", line 1, in -toplevel- x = myString("hello",40) TypeError: str() takes at most 1 argument (2 given) >>> x = myString("hello") >>> x.padding = 50 >>> x 'hello' >>> x.padding 50 >>> (in other words, I can do it in two steps, not one. I also tried UserString and string as superclasses.) From mark_mitwrong at wrongbellsouth.net Fri May 28 12:19:24 2004 From: mark_mitwrong at wrongbellsouth.net (Mark Mitchell) Date: Fri, 28 May 2004 16:19:24 GMT Subject: Non-programmer needs help with PyGTK-2.0.0 References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> <40B71BDC.4050700@draigBrady.com> Message-ID: <gEJtc.3986$Yf6.3947@bignews1.bellsouth.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2004-05-28, P at draigBrady.com <P at draigBrady.com> wrote: > Mark Mitchell wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> I have a program written in python that tells me it requires PyGTK, so I >> DLed, ./configure, make, make install and the process seems to go ok. Some >> errors but the process finishes so I assumed they weren't fatal errors. >> >> So now I attempt to run my python program and I get; >> $ gccp.py >> Traceback (most recent call last): >> File "./gccp.py", line 9, in ? >> import pygtk >> ImportError: No module named pygtk >> >> I'm running Slackware 9.1 with a 2.6.6 kernel, and I don't know what other >> information would be helpful. > > Why not try a prepackaged version? > http://www.linuxpackages.net/search_view.php?by=name&name=pygtk2&ver=9.1 > At least it will give you info on the right thing to do > Two reasons, 1, I didn't know there was one. I may go that route in the end. 2, I'd like to learn what I did wrong so that I have a better chance of having it go flawlessly next time I have to install something like this. Thanks for the link, though. It's bookmarked. Mark - -- Remove both wrongs to make the email address right. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAt2h3LVmEOl6/PWERAjjnAJ9wEZbFbXb6oHb8mmIrzsvgajSs7gCfQod+ Z5PwWZj3RIcUoOme5xcV9vU= =fZsW -----END PGP SIGNATURE----- From nicksjacobson at yahoo.com Sat May 1 14:15:50 2004 From: nicksjacobson at yahoo.com (Nick Jacobson) Date: 1 May 2004 11:15:50 -0700 Subject: Help with C API References: <f8097096.0404302152.38dd1eae@posting.google.com> <c6vfmv$grq$1@news1.tilbu1.nb.home.nl> <f8097096.0405010208.3fbc8e2d@posting.google.com> Message-ID: <f8097096.0405011015.6d2207e@posting.google.com> I don't think I'm stating my question clearly. :( Say I create a list in my C function: seq = PyList_New(0); Then append some numbers to it, whatever. Then, when I return from the C function and want to use that list in my Python code, do I have to increment its refcount: return Py_BuildValue("O", seq); Or do I leave it alone and say: return seq; Thanks in advance. From do at linux.darktower.net Sun May 2 10:07:15 2004 From: do at linux.darktower.net (Dominique Orban) Date: Sun, 02 May 2004 14:07:15 GMT Subject: Pass a list to diffrerent variables. References: <c72r5t$2hua$1@otis.netspace.net.au> Message-ID: <slrnc9a586.20g.do@linux.darktower.net> On 2004-05-02, user at domain.invalid <user at domain.invalid> wrote: > When trying to pass the contents from one list to another this happens: > > list = [1,2,3] > list1 = list > print list1 > [1,2,3] > list.append(7) > print list1 > [1,2,3,7] > > Whats the easiest way to pass the data in a list, not the pointer, to > another variable Try list1 = list[:] instead. This creates a copy. D. From miki.tebeka at zoran.com Sun May 23 06:16:20 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 23 May 2004 12:16:20 +0200 Subject: Freeze and Resume execution In-Reply-To: <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> References: <mailman.106.1085054124.6949.python-list@python.org> <0-Cdnaom9PfMMzHdRVn-gw@powergate.ca> Message-ID: <20040523101619.GH1916@zoran.com> Hello All, Thanks for all the input. > >I'd like to use generators but can't see any "nice" way of doing it. > > That would be the approach I would take. What can't you see > with using yield this way? The output function is way down the call stack. The function that handles the "freezing" and need to be saved is about 3-5 stack frames up (depends on the scenario). Propagating the output return value all the way back is tedious and error prone. This is why I'd like to use raise/catch and not "if error ..." Bye. -- ------------------------------------------------------------------------- Miki Tebeka <miki.tebeka at zoran.com> http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From max at alcyone.com Tue May 25 01:00:56 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 22:00:56 -0700 Subject: Solving the Einstein's Riddle in Python References: <juha.haataja-46ED17.14123824052004@newsread.funet.fi> <40B22B86.152586E4@alcyone.com> <7ep4b0p9j86eojoutm6macj9qt9neeujq2@4ax.com> Message-ID: <40B2D308.232E066C@alcyone.com> Christos TZOTZIOY Georgiou wrote: > I saw your name and said, > "this > name is strangely familiar" :) Great site. Thanks :-). -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Something to remember you by. -- Leonard Shelby From della at toglimi.linux.it Thu May 27 11:20:30 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Thu, 27 May 2004 15:20:30 GMT Subject: Update with pickle In-Reply-To: <o8mtc.48931$tb4.1689212@news20.bellglobal.com> References: <AoIsc.27189$tb4.933533@news20.bellglobal.com> <GYJsc.72376$Qc.2938525@twister1.libero.it> <LoKsc.27890$tb4.968272@news20.bellglobal.com> <aSMsc.42$Rp4.28350@monger.newsread.com> <gaPsc.29315$tb4.1059921@news20.bellglobal.com> <OpUsc.2509$Hf.1455264@newshog.newsread.com> <ljWsc.39527$tb4.1256693@news20.bellglobal.com> <y21tc.41582$tb4.1325901@news20.bellglobal.com> <sI7tc.22267$Wc.780951@twister2.libero.it> <pZ8tc.45374$tb4.1453851@news20.bellglobal.com> <71gtc.75003$Qc.3030919@twister1.libero.it> <o8mtc.48931$tb4.1689212@news20.bellglobal.com> Message-ID: <2Hntc.75813$Qc.3045546@twister1.libero.it> Stefan Seefeld wrote: > Think of a 'persistence storage service' that could look like this: > > store = Persistence.Store('foobar') > > object.store(store) # persists the object's state into the store > > ... > > object.restore(store) # restore the object's state from the store > > Of course, here 'object' has to implement some 'Storable' interface, > so it's quite intrusive (and thus not really what Nicolas is looking for). > It's just to illustrate the purpose, anyways. > With python's metaprogramming and introspection capabilities the same > could be achieved without the need for a specific base class. Well, > may be a specific __metaclass__, I don't know. > > It really seems to me that pickle already contains the functionality > that would be required (after all pickle *can* deal with object graphs, > so it has to track object ids internally), it just needs to be exposed > to the user. I believe that's precisely what Nicolas' enhancement request > is all about. Now I understand. If you always use it for restoring a previous state for the same object, it even looks less evil to me :-) Maybe a metaclass with some kind transactions and rollback could be interesting... -- Ciao, Matteo From SeeBelow at SeeBelow.Nut Mon May 17 23:40:39 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 18 May 2004 03:40:39 GMT Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> Message-ID: <40A985CC.8A380731@shaw.ca> Svein Ove Aas wrote: > > Is anyone working on a python-to-native compiler? > I'd be interested in taking a look. > > Come to think of it, is anyone working on a sexpr-enabled version of > Python, or anything similar? I really miss my macros whenever I try to > use it... I really wish there was a python-to-native compiler, a good one that would produce fairly fast execution. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From ally_burnett at yahoo.co.uk Sat May 15 15:23:13 2004 From: ally_burnett at yahoo.co.uk (alastair) Date: 15 May 2004 12:23:13 -0700 Subject: smtplib - missing message References: <23ae7099.0405140440.341a6244@posting.google.com> <reKdnYb-JcNqVDndRVn-gQ@powergate.ca> <m64fn1-or3.ln1@valpo.de> Message-ID: <23ae7099.0405151123.654b9f16@posting.google.com> Peter - thanks for the information, this did the trick ! Matthias - thanks for pointing out the email module - I'm pretty new to Python and hadn't discovered it, this'll come in real handy. Thanks again guys, Cheers, Alastair. From jeffbarish at starband.net Thu May 27 22:02:15 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Thu, 27 May 2004 20:02:15 -0600 Subject: Terminating program run from thread (not just the thread) Message-ID: <c966jg$qmf$1@sea.gmane.org> My Tkinter GUI starts a thread that runs ogg123 using popen3. The thread reads the stderr from ogg123 to determine when ogg123 is done and, until then, to update a progress meter. I need to be able to stop ogg123 before it reaches the end of its task. If I terminate the thread that used popen3 to start ogg123, ogg123 does not terminate. popen3 does not return a pid, so I don't see any way to terminate the program. Suggestions? -- Jeffrey Barish From peres at poczta.onet.pl Tue May 18 12:59:03 2004 From: peres at poczta.onet.pl (lukas) Date: 18 May 2004 09:59:03 -0700 Subject: win32service & win32process - help me please!!! Message-ID: <7e3ec26.0405180859.59aac639@posting.google.com> Hi! Can You help me - how to write a little program to list a win2k services with their process ID. I need to use this on my Win2k server so please help me. I've already read ActivePython documentation & there is nothing about it! Maybe some of You have had a problem like this??? ex. Service name | process name | process id -------------+--------------+------------ apache | apache.exe | 997 svc_maad_1 | maad.exe | 1075 svc_maad_2 | maad.exe | 1088 etc... Thx for every suggestions... Lukas From pugnatio2 at yahoo.com Fri May 7 14:07:28 2004 From: pugnatio2 at yahoo.com (pugnatio2 at yahoo.com) Date: 7 May 2004 11:07:28 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <c7f6fj$aok$1@panix1.panix.com> Message-ID: <997a06e0.0405071007.3b903c7b@posting.google.com> Thanks to all who replied. I think I've got it straight now, and by the way I did use "polymorphism" incorrectly; I should have said "method overloading." I guess I have my choice between separate callables and using type() or isinstance(). What I had hoped to do was something like: xmlDoc = myFormat2XML(obj) where 'obj' could be either a text string or a sequence of lines. It's not just a problem of whether a scalar or sequence object is passed in. Strings, lists, and tuples are all sequences. The deprecation I read, about avoiding type() (p. 129 of _Python in a Nutshell_) said it interfered with (true) polymorphism (via inheritance). Cheers, --tb From jmeile at hotmail.com Fri May 7 03:25:11 2004 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 07 May 2004 09:25:11 +0200 Subject: call scp from python In-Reply-To: <f547ce3b.0405061013.519890a9@posting.google.com> References: <f547ce3b.0405061013.519890a9@posting.google.com> Message-ID: <409b425a$1@pfaff2.ethz.ch> You can either use os.system or some of the popen functions of the os module. Regards, Josef Coder Coder wrote: > Hi > How can scp a file from one computer to another using python? > > > > Thanks. From jbore at tjtech.com Tue May 18 08:16:21 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Tue, 18 May 2004 12:16:21 GMT Subject: how to run an arbitrary function with timeout? References: <mailman.15.1084553467.4157.python-list@python.org> <2004051413541084557280@k2.sage.att.com> <140520041613369125%mday@apple.com> <m31xljkwjc.fsf@union.tjtech.com> <8d3e714e.0405171737.58fd641d@posting.google.com> Message-ID: <m3u0yej5gr.fsf@union.tjtech.com> cappy2112 at yahoo.com (Tony C) writes: >> # set the alarm signal handler, and set the alarm to 1 second >> # >> signal.signal(signal.SIGALRM, alarmHandler) >> signal.alarm(1) > > This is a very interesting solution. > However, signal.alarm() and signal.SIGALRM are not defined in my signal module > I'm using 2.3.3 I'm using 2.2.1, but it's on unix/linux. It looks like the alarm functionality is only available there. I guess there must be something similar on windows, anyone have any ideas? jb From budr at local.host Fri May 14 22:25:37 2004 From: budr at local.host (Bud Rogers) Date: Fri, 14 May 2004 21:25:37 -0500 Subject: RELEASED Python 2.3.4, release candidate 1 References: <67B3A7DA6591BE439001F2736233351202B479BA@xch-nw-28.nw.nos.boeing.com> <mailman.31.1084583605.4157.python-list@python.org> Message-ID: <2mbgn1-6tr.ln1@twocups.netride.net> Joseph wrote: >?I?would?avoid?installing?applications?that?way,?if?only?for Joseph >? the fact?that?you?can't?uninstall?an?application. make -n uninstall > uninstall.script From kevnsgnospam at aol.com Wed May 19 21:37:40 2004 From: kevnsgnospam at aol.com (Kevin G) Date: Thu, 20 May 2004 01:37:40 GMT Subject: Unification of Methods and Functions References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <2h2g50F87lb9U1@uni-berlin.de> Message-ID: <s13oa05mhn1584d2ljvij40ktrorpo432s@4ax.com> On Thu, 20 May 2004 13:32:14 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: <snip> >Also, there's a difference between cacheing and maintaining >redundant data representations. With a cache, if in doubt you >can always throw away the cache and re-calculate. But if your >design relies on incrementally keeping parallel data structures >up to date, if anything gets out of whack, you're hosed, >because you don't have the ability to re-calculate the >redundant data from scratch. Seems to me there's a semantic problem here: if you can't re-calculate it, then by definition it's not redundant. -Kevin From gulliver at atr.co.jp Fri May 14 02:14:14 2004 From: gulliver at atr.co.jp (Roberto Lopez-Gulliver) Date: 13 May 2004 23:14:14 -0700 Subject: Mac OS X and jpeg support.... References: <46850fd1.0405131142.5ff1d525@posting.google.com> <c80s5u$dpd$1@news.nems.noaa.gov> Message-ID: <26b7aa41.0405132214.2ccdd3cf@posting.google.com> > There is another Package Manger Repository put together by Bob Ippolito, > and I think it includes a PIL with jpeg support built in. Check out the > archives of the Python-Mac mailing list. You should be abel to find it > at www.python.org. I got my python running on MacOS X following the instructions in the VisionEgg project (which in turns points you Bob Ippolito's repository) http://www.visionegg.org/install-macosx-details.html http://undefined.org/python/pimp/darwin-7.2.0-Power_Macintosh.plist hope this helps ... and have fun! --r From haim at babysnakes.org Tue May 11 17:48:28 2004 From: haim at babysnakes.org (Haim Ashkenazi) Date: Wed, 12 May 2004 00:48:28 +0300 Subject: Python security settings References: <67B3A7DA6591BE439001F27362333512028772DA@xch-nw-28.nw.nos.boeing.com> Message-ID: <c7rhnc$id6$1@sea.gmane.org> Laughlin, Joseph V wrote: > > import SimpleXMLRPCServer > rpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 3010)) > print "XMLRPC Server started!" > rpc_server.serve_forever() > > When I run this program, I can connect to port 3010 on the localhost, > but I can't connect to the port from any other machine (or from the > local machine using the machine's hostname). Why is this? well, I'm a python newbie but it seems that you opened the socket on 'localhost' which has IP "127.0.0.1". other machines can't connect to this IP (they will connect to themself). there must be a way to open the socket on all local interfaces (and if not, specify the one that you will be using). > > Joe Laughlin > Phantom Works - Integrated Technology Development Labs > The Boeing Company Bye -- Haim From miki.tebeka at zoran.com Mon May 17 11:19:15 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 17 May 2004 17:19:15 +0200 Subject: Binary handling In-Reply-To: <2gro06F5ti55U1@uni-berlin.de> References: <2gro06F5ti55U1@uni-berlin.de> Message-ID: <40A8D7F3.7080400@zoran.com> Hello Derfel, > I have a file of binary data. I want to read this file and parse the data in > it. The format of the file is: > 8 bits number of data pakets > 6 bits offset > 20 bits time > 8 states > > How can I read this fields in binary? I see the struct module and the > binascii, but I can't split the diferent fiels. --- bitter.py --- # Testing ''' >>> b = BitStream(chr(int("10111010", 2))) >>> b.get_bits(3) 5 >>> b.get_bits(2) 3 >>> b.get_bits(3) 2 >>> b.get_bits(0) 0 >>> b.get_bits(1) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/tmp/bitter.py", line 27, in get_bits raise EOFError EOFError ''' from array import array class BitStream: '''Bit stream implementation''' def __init__(self, data): self.arr = array("c", data) self.bit = 0 # Current output bit def get_bits(self, count): '''Get `count' bits from stream''' if count == 0: # Nothing to get return 0 if not self.arr: # EOF raise EOFError value = 0 for c in range(count): if not self.arr: # EOF raise EOFError value <<= 1 shifted = ord(self.arr[0]) >> (8 - self.bit - 1) value |= (shifted & 1) self.bit += 1 if self.bit == 8: # Get new byte self.arr.pop(0) self.bit = 0 return value def _test(): from doctest import testmod import bitter testmod(bitter) if __name__ == "__main__": _test() --- bitter.py --- HTH. Miki From mailinglist at ltsai.com Sun May 30 10:13:49 2004 From: mailinglist at ltsai.com (Tsai Li Ming) Date: Sun, 30 May 2004 22:13:49 +0800 Subject: Redirect stdout & stderr (similar to a daemon) In-Reply-To: <yXeuAls/K3XG089yn@the-wire.com> References: <40b9cd69@news.starhub.net.sg> <yXeuAls/K3XG089yn@the-wire.com> Message-ID: <40B9EC1D.6030401@ltsai.com> Mel Wilson wrote: > In article <40b9cd69 at news.starhub.net.sg>, > Tsai Li Ming <mailinglist at ltsai.com> wrote: > >>I have a problem with a redirecting stdout and stderr. I am a top level >>module and has no control over the imported modules that are making >>system calls such as os.system or popen2.* . I have tried the simplest >>method of capturing stdout, stderr via: >> >>saveout = sys.stdout >>sys.stdout = file_obj >> >>print 1 # works >>os.system('w') # Doesn't work > > > I think the problem here is that os.system runs a > shell with its own new set of process parameters, > including its own stdin, stdout, etc. > > I would try one of the os.exec's or os.spawn's here > instead. > > >>[ ... ] >># Redirect standard file descriptors. >>os.dup2(si.fileno(), sys.stdin.fileno()) >>os.dup2(so.fileno(), sys.stdout.fileno()) >>os.dup2(se.fileno(), sys.stderr.fileno()) > > > These modify the actual file objects represented by > 'sys.stdin', etc. There's no coming back from that. > > Regards. Mel. I would think so too. Sadly, I can't use other system calls because I will be importing other modules that I have no control of. Liming From stephen.mcphail at casaccia.enea.it Thu May 27 09:26:59 2004 From: stephen.mcphail at casaccia.enea.it (Stephen McPhail) Date: Thu, 27 May 2004 15:26:59 +0200 Subject: Fortran-compiled DLLs in Python Message-ID: <5.2.0.9.0.20040527152509.00acbbd8@mail.casaccia.enea.it> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040527/1fb19f95/attachment.html> From ark at acm.org Wed May 26 14:00:29 2004 From: ark at acm.org (Andrew Koenig) Date: Wed, 26 May 2004 18:00:29 GMT Subject: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <pan.2004.05.26.01.02.00.429236@sbcglobal.net> <du7fz9ni0ny.fsf_-_@amadeus.cc.tut.fi> Message-ID: <1X4tc.71833$hH.1301889@bgtnsc04-news.ops.worldnet.att.net> "Ville Vainio" <ville at spammers.com> wrote in message news:du7fz9ni0ny.fsf_-_ at amadeus.cc.tut.fi... > Prefixing names with symbols like $ and @ is a great idea - it makes > the "nouns" (variables) stand out from "verbs", and makes the code > flow like a natural language, making reading it easy and writing it > fun! Interesting idea. Let's try it with English, using @ for nouns and $ for verbs: $Prefixing @names with @symbols like $ and @ $is a great @idea - it $makes the "@nouns" (@variables) $stand out from "@verbs" and $makes the @code $flow like natural @language, $making $reading it easy and $writing it fun! See how much easier the modified text is to read? :-) From segphault at sbcglobal.net Fri May 14 23:56:06 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Sat, 15 May 2004 03:56:06 GMT Subject: book on wxPython? References: <slrncab3p3.ou5.grante@grante.rivatek.com> Message-ID: <pan.2004.05.15.03.52.15.667940@sbcglobal.net> On Sat, 15 May 2004 03:32:00 +0000, Grant Edwards wrote: > Can anybody recommend a good book on wxPython? Are there any > books on wxPython? I have a copy of the python2.1 bible. Its a bit outdated, but it has a really good section on wxpython. Its by no means a comprehensive exploration of wx, but gives a good presentation. The book is nice to have around for other things too, it has good examples, and it really helped extend my understanding of several facets of python. > wxWindows seems to be more low-level than the other GUI > toolkits I've used (Tk, GTK, and Trestle[1]), and there are all > sorts exposed details in wxWindows/wxPython that I find weird. wxWindows is far from low level. it is a cross-platform compatible wrapper that sits on top of other toolkits. (Gtk on linux, for instance) It seems 'low-level' because the python bindings have very unpythonic syntax. People say that WAX fixes this. (I've never used it) > Anyway, I'd really love to find a good book on wxPython. I'm > still working through wxPython tutorials, and I've read through > some of the wxWindows ones (which are of limited value for > somebody steadfastly determined to remain clueless about C++). I applaud your efforts to stay C++ free, and I sincerely hope you have more luck in that endeavor than I did! You might find that perusing wxPython examples helps more than reading those insidious c++ tutorials. The WxPython demo includes a comprehensive collection of examples, showing how to use just about every single widget. You might want to take a look at it. --SegPhault From amk at amk.ca Fri May 7 10:33:14 2004 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 07 May 2004 09:33:14 -0500 Subject: improving the Python docs -- a wiki? copy PHP's model? References: <mailman.265.1083757484.25742.python-list@python.org> <mailman.327.1083875431.25742.python-list@python.org> Message-ID: <U5WdnafZhPe3AwbdRVn-jA@speakeasy.net> On Thu, 6 May 2004 13:30:20 -0700, Mike Rovner <mike at nospam.com> wrote: > Please make your pages belong to CategoryDocumentation. Translating pages into Wiki markup by hand seems insane to me; it'll take weeks to do all the documents, and then it'll quickly drift out of date. Allowing editing of the body of the docs also seems pointless because it'll be too difficult to find changes and apply them to the LaTeX source. Why not just start a new site with a copy of the downloadable HTML docs, and then add comments to each page with a server-side include or some similar mechanism? --amk From jepler at unpythonic.net Mon May 31 09:44:57 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 31 May 2004 08:44:57 -0500 Subject: how to bail if stdin is empty In-Reply-To: <2621b014.0405310535.38e176df@posting.google.com> References: <2621b014.0405310535.38e176df@posting.google.com> Message-ID: <20040531134457.GA19206@unpythonic.net> You can test whether stdin is a "terminal", and act accordingly. $ ./tt.py Standard input is a terminal. Aborting! $ ./tt.py < /dev/null Standard input is a file. Doing something. #!/usr/bin/env python import os if os.isatty(0): print "Standard input is a terminal. Aborting!" else: print "Standard input is a file. Doing something." -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040531/064d6472/attachment.sig> From corey.coughlin at attbi.com Mon May 17 15:35:23 2004 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 17 May 2004 12:35:23 -0700 Subject: Unification of Methods and Functions References: <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> Message-ID: <a8623416.0405171135.5a92ba6c@posting.google.com> You know, it's interesting, I'm an engineer at a semiconductor company, and I've written netlist manipulation objects over and over again with only the most basic oop structure, and they usually work fine. Associating data with each cell is usually not that hard, although the show() function showing data from all cells above it (?) seems kind of strange. This type of problem is a case where object encapsulation is usually a lot more effective than inheritance. In my netlist objects, the most basic object is just a name object, which everything inherits because everything in a netlist has a name. Beyond that, there's some container inheritance, I came up with an ordered dictionary for pin data, some simple inheritance where Pin objects inherit from Net objects, but that's about it. The basic object structure is pretty simple. The highest level object is a netlist. The netlist contains a list (just a simple python list) of cell objects. The cell objects contain a list of nets, a list of pins, and a list of instances. There are classes for instances, nets, and pins (which inherit from nets). The instances do refer to their parent cells, and the pins from the parent are copied in, but that's about as complicated as things get in the class hierarchy. There's also a special container class to describe the connections in a cell, so I can send the connection mesh a net, an instance, or an instance,pin tuple, and find out what it's connected to. That's probably the most complicated class, since it uses a few internal dicts and a type driven interface to resolve the input data. But that's really about the size of it. Transistors would be instances in cells (although a transistor cell parent is also in there) and gates would simply be cells. Now if you had similar cells with different current or power characteristics, I suppose you'd need to associate those with an instance class instead of a cell class. Beyond that, I don't really see why this is such a difficult thing to do. Unless there's some other overriding goal this needs to accomplish that isn't in the spec below. You might want to try just coming up with something like the container hierarchy I have, not worrying about inheritance, and see if that does the trick for you. Greg Ewing <greg at cosc.canterbury.ac.nz> wrote in message news:<2gip0dF3ffrjU1 at uni-berlin.de>... > David MacQuigg wrote: > > 1) We need to represent a hierarchy of cells, typically 5 to 10 levels > > deep. > > 2) Each cell has data associated with it. Some of this data is a > > cummulative total of similar data from all subcells -- total currents, > > total chip area, etc. > > 3) The data for each cell is unique, and it must be displayed in a > > format unique to that cell. > > 4) We need a simple function, show() that can be called for any cell > > or no cell at all (just knowing the cell type). This function should > > show the cell data and the data from all cells above it. In case no > > cells of a particular type have been added to the design, the > > cummulative data should just show a default value, like zero. > > It's still not clear whether the hierarchy you're talking > about is a hierarchy of *kinds* of cells (i.e. a class > hierarchy), or a physical hierarchy of actual cells (i.e. > an instance hierarchy). > > Both of these hierarchies can exist at the same time, and > they are different. > > For example, you might have a kind of cell called NandGate, > and a kind of cell called Transistor. An instance of NandGate > contains instances of Transistor -- this is an instance > hierarchy. But Transistor is not a subclass of NandGate -- > that would imply a Transistor is a kind of NandGate, which > is not true. > > On the other hand, NandGate may well be a subclass of Gate, > and Gate and Transistor may be subclasses of Component. But > that doesn't mean Gates *contain* NandGates. > > If prototype-based programming leads to confusion between > class hierarchies and instance hierarchies, the I would > say it's not helpful. From tismer at stackless.com Thu May 27 19:06:47 2004 From: tismer at stackless.com (Christian Tismer) Date: Fri, 28 May 2004 01:06:47 +0200 Subject: Why a class when there will only be one instance? In-Reply-To: <KPENJIMKHJPNKOLFIHBNKEMKCKAA.vineet@eswap.com> References: <KPENJIMKHJPNKOLFIHBNKEMKCKAA.vineet@eswap.com> Message-ID: <40B67487.1070007@stackless.com> Vineet Jain wrote: >>Just a little observation: >>If you really want the class and the instance to be the same, >>well, you can take a module. >>In a sense, this *is* a class and the only instance. > > > I need to use BASIC language like scripting in a python application. The > users are not programmers and the scripting interface needs to be > as simple as possible. The script would have a init section > a run section a close section and some other parts as well. I > have these sections defined as functions in a class (the class inherits > from a base class) currently but have a feeling that I'm going to have > to simplify things. Am not sure how users will handle class, functions, > self, import, etc. I understand! > I was thinking of using a module, but can I repeatedly call the module. > If so how would I call it? Would I keep reloading it? Where does a module > store it's state information between calls? Ok, in that sense I was wrong: by definition, a module is not callable, and it is run exactly once, usually just to make its definitions which you then call from outside. The module isn't much more than an object wrapped around a dict. All globals are in that dict, including the defined function object, and that's it. It is easy to take a module like you described, and "run" it again, given that you know what's in it. Just keep track of the state you want to preserve and you want to re-initialise, and then call the different parts from outside. Easy. But, you probably want to even go without functions? Then you would have to re-execute all code of the module each time, and well, you can use reload for this, but I would probably write my own evaluator for this, not importing the module directly, but compiling its code once, and then execute the code, give them special globals with custom builtins, to protect you from non-programmers. I was thinking of supporting > different sections by setting different variables which the user would > access it: > > if init: > do init code here > > if run: > do run here > > if close: > do close here > > Any other ideas? I'm trying to keep the scripting interface as simple as > possible but at the same time give the users the power of python. Why nopt, and yes, a module is just fine, better to say, it is not a module, but a piece of python source with a defined structure, and you compile it and run it explicitly. ciao - chris -- Christian Tismer :^) <mailto:tismer at stackless.com> Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From fuf at mageo.cz Thu May 6 08:39:19 2004 From: fuf at mageo.cz (Michal Vitecek) Date: Thu, 6 May 2004 14:39:19 +0200 Subject: Announcing PyInvoke In-Reply-To: <pan.2004.05.06.12.34.26.556781@midtoad.homelinux.org> References: <mailman.165.1083371896.25742.python-list@python.org> <pan.2004.05.06.12.34.26.556781@midtoad.homelinux.org> Message-ID: <20040506123919.GA8557@foof.i3.cz> Stewart Midwinter wrote: >> I have not yet seen real transparent RPC for Python, >> so I decided to implement one: >> http://pybuild.sourceforge.net/pyinvoke.html > >Please tell me what RPC stands for. I don't see that explained anywhere >on your website. "Remote Program Control"? Remote Procedure Call -- fuf (fuf at mageo.cz) From newsgroups at jhrothjr.com Wed May 26 08:12:13 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 26 May 2004 08:12:13 -0400 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> Message-ID: <10b92cm31go2k08@news.supernews.com> <SeeBelow at SeeBelow.Nut> wrote in message news:40B3E861.29B033D5 at shaw.ca... > I see the value of a class when two or more instances will be created, > but Python programmers regularly use a class when there will only be one > instance. > What is the benefit of this? It has a disadvantage of a whole lot of > "self." > being required everywhere, making the code less readable. Also, since a > strength of Python is rapid application development, it slows one down > to have to put in all those self.'s. The code seems much cleaner to me > without classes that have only one instance. Oh, also, all the methods > of this class will have to have the instance name prepended to them. I'm only aware of one domain (interactive fiction) where it is really common to have single instance classes. That's served by a number of special purpose languages (Inform, TADS and Hugo spring to mind). Your example (of single use classes in a UI context) seems to be a bit contrived. I've usually found that I could get quite a bit of code reuse out of UI classes simply by thinking the problems through. Granted, single use classes aren't uncommon, but instances of other classes are much more common in most programs. In Python, there are a number of ways of getting singletons without very much extra effort. > I would appreciate it if someone could explain the advantages of doing > this, or at least the sociological reasons why it occurs. Both have their uses. The class / instance dicotomy comes from the earliest days of object oriented programming, and experiments with classless languages (see the Prothon stuff currently going on, also the IO language) have never been very compelling. A lot of people (which include me) think that it's much to easy to get sloppy with that paradigm. The other thing to understand is that in most OO languages a class is a declaration: it does not appear in the actual object program other than as a framework for the instances that are created. Python is one of the few languages where classes are first class objects. John Roth > Mitchell Timin From smeier at exelixis.com Wed May 26 12:17:46 2004 From: smeier at exelixis.com (Stefan Meier) Date: Wed, 26 May 2004 09:17:46 -0700 Subject: Some Newbie Questions In-Reply-To: <Tq-dnS4zgJvpOyndRVn-jg@comcast.com> References: <40b47710@e-post.inode.at> <Tq-dnS4zgJvpOyndRVn-jg@comcast.com> Message-ID: <200405260917.46850.smeier@exelixis.com> On Wednesday 26 May 2004 07:15 am, Larry Bates wrote: > On question #1: I see this question a lot on > this list, but I'm curious about why you don't > want to instantiate the class? I can't think > of a reason not to and am very curious if I'm > missing something here??? Static classes for example. If you want to maintain object orientation and have stuff to store statically, you might want to put it into a class and maybe even do some data mangling in a method or so, but since the class is static, no need to instantiate it. - Stefan -- Stefan Meier Computational Biology & Informatics Exelixis, Inc. 170 Harbor Way, P.O. Box 511 South San Francisco, CA 94083-511 fon. (650)837 7816 From chrish at cryptocard.com Wed May 5 13:51:16 2004 From: chrish at cryptocard.com (Chris Herborth) Date: Wed, 05 May 2004 13:51:16 -0400 Subject: Web programming ... In-Reply-To: <40990fd8$0$567$e4fe514c@news.xs4all.nl> References: <c7b2er$1q2uv$1@ID-205437.news.uni-berlin.de> <40990fd8$0$567$e4fe514c@news.xs4all.nl> Message-ID: <nQ9mc.40413$ZJ5.1300352@news20.bellglobal.com> Irmen de Jong wrote: > Sarah Tanembaum wrote: > >> Is python good for creating Web application? > > Short answer: yes. > Long answer: http://www.python.org/cgi-bin/moinmoin/WebProgramming I guess it depends on what you mean by "web application"... I've never been able to find decent SOAP support, or something that can grok a WSDL file, for example. -- Chris Herborth chrish at cryptocard.com Documentation Overlord, CRYPTOCard Corp. http://www.cryptocard.com/ Never send a monster to do the work of an evil scientist. From mcherm at mcherm.com Wed May 26 09:17:49 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 26 May 2004 06:17:49 -0700 Subject: modifying mutable list elements in a for loop Message-ID: <1085577469.40b498fd0ce5b@mcherm.com> Peter Ballard writes: > The python tutorial tells me "It is not safe to modify the sequence > being iterated over in the loop". [... tried modifying the list elements and it worked ...] > because how else can one perform an operation on a list of objects? > But that phrase "It is not safe to modify the sequence being iterated > over in the loop" in the tutorial has me slightly worried. Actually, you're far more worried than necessary. The Python tutorial is written for beginners, and the stricture to avoid modifying a sequence being iterated over is good advice for beginners, rather than an actual rule of the Python language. First of all, your analysis is correct: it is always OK to modify the items in a list during a loop. You are even correct that what the list "really" contains (at the C level) is just pointers to the items in the list. But the real truth goes even further. There are some data structures in some languages which you *MUST NOT* modify while traversing them because for some reason (probably having to do with threading) it would result in undefined behavior. But that is NOT a problem with Python. In Python it's perfectly OK to modify a list (or dict, or whatever) while traversing it, it's just not a good idea for beginners (or experienced programmers who want to produce understandable code) because the behavior may not be what you expect. >>> alist = range(10) >>> for x in alist: ... alist.remove(x) ... >>> alist [1, 3, 5, 7, 9] This behavior is perfectly well defined. (Think about it. Now think about it again. Got it?) But you have to admit that it's confusing to beginners, so the Tutorial strongly recomends against it. -- Michael Chermside From xiaohua_sun at yahoo.com Sat May 29 18:11:50 2004 From: xiaohua_sun at yahoo.com (SunX) Date: 29 May 2004 15:11:50 -0700 Subject: 2d lists Message-ID: <337e6cd5.0405291411.4376debc@posting.google.com> What is the best way to assign a 2d lists? Something like; for i in range(10): for j in range(10): aList[i][j] = i*j Thank you in advance. From no.mail at available.net Thu May 13 05:51:41 2004 From: no.mail at available.net (Georgy) Date: Thu, 13 May 2004 09:51:41 GMT Subject: CGI Proplem displaying image References: <d588131f.0405071937.94e4f17@posting.google.com> <c5b3dbee.0405081454.5ef67653@posting.google.com> <d588131f.0405090912.560b51db@posting.google.com> <d588131f.0405102237.15106ea5@posting.google.com> <Jvcoc.38410$jU.2202374@twister.southeast.rr.com> <d588131f.0405122202.5ba4d205@posting.google.com> Message-ID: <NyHoc.43027$jU.2411174@twister.southeast.rr.com> "matthiasjanes" <matthiasjanes at gmx.net> wrote in message news:d588131f.0405122202.5ba4d205 at posting.google.com... | Do I have to use the 'sys.stdout.write( something )' | | or is it also good enough to use 'print (something)' Yes, "print something" will be quite safe here, although 'print' adds a newline mark or a blank (if you end 'print' with a comma) to the output and sometimes it can show on the generated pages. But if you used 'print' for making binary files e.g. images, that could ruin the output, so it's usually easier to use sys.stdout.write and not to think about this problem. Please note also, that on Windows, both of the ways can translate '\n' into '\r\n' so it may be necessary to switch stdout to binary mode, with this code, for example: try: import msvcrt,os msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for stdin except ImportError: pass Georgy From gherron at islandtraining.com Wed May 19 17:57:54 2004 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 19 May 2004 14:57:54 -0700 Subject: comparing strings and integers In-Reply-To: <3064b51d.0405191326.124a3ab3@posting.google.com> References: <3064b51d.0405191326.124a3ab3@posting.google.com> Message-ID: <200405191457.54187.gherron@islandtraining.com> On Wednesday 19 May 2004 02:26 pm, beliavsky at aol.com wrote: > By mistake I coded something like > > print ("1" > 1) > > and got the result "True". Comparing an integer and a string seems > meaningless to me, and I would prefer to have an exception thrown. Can > someone explain why Python allows comparisons between integers and > strings, and how it handles those cases? Why is "1" > 1? > > Pychecker does not warn about the line of code above -- I wish it did. > > In my code what I really intended was to convert the "1" to an int and > THEN do a comparison. >From the manual: 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 fumanchu at amor.org Sun May 9 16:08:52 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 9 May 2004 13:08:52 -0700 Subject: Replacing "illegal characters" in html Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E5620C5@opus.amorhq.net> BenO wrote: > I'm new to python and need to write a function to replace > certain characters > in a string (html). > > The characters I need to replace come from MS Word copy & > paste and are: > > ' (Left quote) > ' (Right quote) > Double Left quotes > Double Right quotes > > Can anyone help me or point me in the right direction on an > efficient way of doing this? The two methods most often used are 1) the .replace method of strings, and 2) regular expressions. 1) The .replace method: >>> replacemap = {""": '"', """: '"', "'": "'", "'": "'"} >>> map(ord, replacemap.keys()) [145, 147, 146, 148] >>> test = ""hl" 'oh'" >>> for k, v in replacemap.iteritems(): ... test = test.replace(k, v) ... >>> test '"hl" \'oh\'' 2) Regular Expressions: >>> import re >>> test = ""hl" 'oh'" >>> test = re.sub("[""]", '"', test) >>> test = re.sub("['']", "'", test) >>> test '"hl" \'oh\'' Hope that helps! Robert Brewer MIS Amor Ministries fumanchu at amor.org From SeeBelow at SeeBelow.Nut Wed May 26 13:39:42 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Wed, 26 May 2004 17:39:42 GMT Subject: EvNim uses neuroevolution to evolve an ANN that plays the gameof Nim References: <gGVsc.99$rb.92248@news.uswest.net> <mailman.321.1085585873.6949.python-list@python.org> Message-ID: <40B4D67B.7BDE9D5B@shaw.ca> Terry Reedy wrote: > > "Michael Livsey" <dotsero at qwest.net> wrote in message > news:gGVsc.99$rb.92248 at news.uswest.net... > > The people at ANNEvolve have been working hard again and have released > > EvNim 1.08. ... Evnim is written in standard C > > Does this have anything to do with Python; if not (and I cannot see any > connection from what you posted), this is off-topic. I think this was a mistake by our reporter. We recently released a Python program, but it was not this one. I agree that it is off-topic. Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From me at privacy.net Fri May 14 08:52:37 2004 From: me at privacy.net (Heather Coppersmith) Date: 14 May 2004 08:52:37 -0400 Subject: appending to dict References: <95f72778.0405140140.662d63fc@posting.google.com> Message-ID: <m27jvff9wq.fsf@unique.phony.fqdn> On 14 May 2004 02:40:00 -0700, bucket79 at daum.net (bucket79) wrote: > is there anyway appending to dictionary? > list has this feature >>>> a = [] >>>> a.append(1) >>>> print a > [1] > but dictionary can't > i wanna do like this thing >>>> a = {1, 2} >>>> a.append(3, 4) -> This is just my idea :@ >>>> print a > {1:2, 3:4} Maybe I'm missing something. Try this: a = { 1:2 } a[ 3 ] = 4 and then check out http://www.python.org/doc/current/tut/node7.html#SECTION007400000000000000000 and http://www.python.org/doc/current/lib/typesmapping.html HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From dmq at gain.com Mon May 10 16:08:22 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 10 May 2004 13:08:22 -0700 Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <16752bcc.0405050817.4ca77017@posting.google.com> <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com> <16752bcc.0405060737.bd43802@posting.google.com> <knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com> <2g0f8iF34iasU1@uni-berlin.de> <rtco90tuesgho2rc15m85gmrtg6cmo2oi0@4ax.com> <2g8a1cF5il06U1@uni-berlin.de> Message-ID: <p4ov909491f7trle45spcpscljcbqq1sgu@4ax.com> On Mon, 10 May 2004 15:08:26 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: >David MacQuigg wrote: >>>In Python, staticmethods are not fundamentally necessary, >>>full stop. We keep trying to tell you that, but it seems >>>you have your fingers in your ears. >> >> I will stop this subthread right here unless you change your tone. > >Sorry, I take that back. > >I stand by the point I was trying to make, though. You >don't need to use static methods at all in a language, >like Python, which doesn't force you to make all functions >a method of something. Apology accepted. You are welcome to participate in the discussion of the best way to structure this introductory Animals.py example. I'm getting some suggetions from James Moughan, and I put t From jacek.generowicz at cern.ch Mon May 24 08:32:38 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 May 2004 14:32:38 +0200 Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <tyfu0yem07c.fsf@pcepsft001.cern.ch> <mailman.49.1084890435.6949.python-list@python.org> <HEyqc.132$Uq1.127@fe2.columbus.rr.com> <7xad0581ax.fsf@ruckus.brouhaha.com> Message-ID: <tyflljim2e1.fsf@pcepsft001.cern.ch> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > Carl Banks <imbosol at aerojockey.invalid> writes: > > I don't follow you. In what way is Python dynamic that Lisp isn't? > > > >>> class foo: > ... def bar(self, x): > ... return x*x > ... > >>> a = foo() > >>> a.bar(3) > 9 > >>> a.bar = lambda x: x*x*x > >>> a.bar(3) > 27 > >>> I'm afraid you'll have to try harder. [1]> (defclass foo () ()) #<STANDARD-CLASS FOO> [2]> (defmethod bar ((foo foo) x) (* x x)) #<STANDARD-METHOD (#<STANDARD-CLASS FOO> #<BUILT-IN-CLASS T>)> [3]> (defparameter a (make-instance 'foo)) A [4]> (bar a 3) 9 [5]> (defmethod bar ((self (eql a)) x) (* x x x)) #<STANDARD-METHOD ((EQL #<FOO #x203185F9>) #<BUILT-IN-CLASS T>)> [6]> (bar a 3) 27 From db3l at fitlinxx.com Fri May 28 19:37:23 2004 From: db3l at fitlinxx.com (David Bolen) Date: 28 May 2004 19:37:23 -0400 Subject: "Private" Member Variables References: <c97r0b$jqq$1@news01.intel.com> <86k6ywig62.fsf@sysfault.org> Message-ID: <uy8nccedo.fsf@fitlinxx.com> Marcus von Appen <mva at sysfault.org> writes: > Yes. Imagine a class, which's attributes should only be able to hold a > specific value range, e.g. a triangle, of which the side length should not > exceed 10. > If you would use the class as - let's say a third party developer and this > class does not contain an accessor nor this 'private' indicator (_ or __), > you possibly would not know about that limited value range. > > You would simply type in triangle.side = 50. > Now another calculation method using that triangle object could receive > a value overflow, because it cannot calculate with such a 'big' value, but > is limited to 10. > > An accessor and private attribute could avoid this: > * You would know, that the author of the class does not want you to modify > the attribute directly. > * The accessor could test the value range at input. > ... > etc.pp. Except that Python doesn't make you use accessors to gain this behavior. If in fact you have such a class, and yet you still want to be able to permit users to use it in the above manner, simply make the "side" attribute into a property (which function as accessors but hidden behind normal attribute access syntax), and you get full control when someone tries to assign something to do, at which point you can validate the input all you want. In terms of knowing that a class enforces such rules, that's something I would expect documented by the class, regardless of implementation. And the great thing is you can initially start out with a normal non-property attribute, and convert it to a property at some point in the future if you need to, without affecting any existing users of the code (well, unless their prior use is later considered invalid, but that would be true if you changed the rules checked by an accessor as well). -- David From alan.gauld at btinternet.com Wed May 5 19:04:46 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 May 2004 00:04:46 +0100 Subject: MySQL vrs SQLite References: <mailman.283.1083787205.25742.python-list@python.org> <slrnc9is2h.8mg.ramen@lackingtalent.com> Message-ID: <uisi90lvd03em0vlta9pl59n2m7qs3t2h4@4ax.com> On Wed, 05 May 2004 22:41:35 -0000, Dave Benjamin <ramen at lackingtalent.com> wrote: > In article <mailman.283.1083787205.25742.python-list at python.org>, Michael wrote: > > I'm considering changing a Python program of mine, that uses MySQL as > > it's db backend, to use SQLite. .... Any draw backs to making this change? No direct experience but doesn't SQLite store its data in memory? If you have a large database that could lead to problems on PCs with a small memory installation or running lots of apps? On the other hand if the data volume is small SQLite could offer significant performance gains over a disk oriented architecture like MySQL etc. Just a thought. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From __peter__ at web.de Mon May 10 02:52:35 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 May 2004 08:52:35 +0200 Subject: list comprehension References: <c7mii9$988$1@lust.ihug.co.nz> <c7mk94$6of$1@panix2.panix.com> <c7ml6k$c88$1@lust.ihug.co.nz> <qj2u90p18cipqu7gq0las26a56j83f95o1@4ax.com> Message-ID: <c7n8rk$60q$06$1@news.t-online.com> Tim Roberts wrote: > Guy Robinson <guy at NOSPAM.r-e-d.co.nz> wrote: > >>This works I was just wondering if something could be written more >>concisely and hopefully faster: >> >>s = "114320,69808 114272,69920 113568,71600 113328,72272" >>e = s.split(' ') >>out ='' >>for d in e: >> d =d.split(',') >> out +='%s,%d ' %(d[0],-int(d[1])) >>print out > > Well, why not the more obvious: s.replace(',',',-') But beware negative numbers: >>> int("--1") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): --1 >>> Therefore at least >>> "123,234 567,-789".replace(",", ",-").replace("--", "") '123,-234 567,789' >>> As to robustness, the OP relying on commas not being followed by a space seems dangerous, too, if the original data is created manually. Peter From vonehr at ipm.fhg.de Tue May 18 09:05:19 2004 From: vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 18 May 2004 15:05:19 +0200 Subject: SWIG callback problem on win32 Message-ID: <c8d1kr$kur$1@news2.rz.uni-karlsruhe.de> Hi, I tried to build the swig: callback example, but when I run the runme.py file I get a message box: abnormal program termination The error appears in already in the first line of the python callback generation: # Add a Python callback (caller owns the callback, so we # disown it first by calling __disown__). caller.setCallback(PyCallback().__disown__()) caller.call() caller.delCallback() When I call only PyCallback().__disown__() alone, the error appears, too. Anybody knows a solution? Thanks a lot, Markus From apardon at forel.vub.ac.be Wed May 12 03:41:32 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 May 2004 07:41:32 GMT Subject: Unification of Methods and Functions References: <mailman.419.1084263049.25742.python-list@python.org> <slrnca1d94.1i9.apardon@trout.vub.ac.be> <mailman.435.1084301183.25742.python-list@python.org> Message-ID: <slrnca3l9e.1i9.apardon@trout.vub.ac.be> Op 2004-05-11, Terry Reedy schreef <tjreedy at udel.edu>: > > "Antoon Pardon" <apardon at forel.vub.ac.be> wrote in message > news:slrnca1d94.1i9.apardon at trout.vub.ac.be... >> I don't see how this contradicts what I want to say. In both case you > have >> something of the form >> >> obj = cls() >> >> And in both obj.method() is equivallent to cls.method(obj) > > I believe Timothy's point was that inst.meth() is more general than any > specific clas.meth(inst) whenever there is more than one possible meaning > of 'clas'. In the following snippet, one can only replace 'animal.speak', > without changing semantics, with 'animal.__class__.speak(animal)' and not > with any specific versioon of clas.speak(animal). If something cannot be > substituted without changing meaning, in a particular context, then, in > that context, it literally does not mean the same thing. Fine it is more general, it is like a curried function. IMO this is just a tangent that has litlle to do with my main point but if you really want to be accurate, I don't mind its just illustrates how much python is doing implicitly. > class mammal: > def speak(self): print 'umf' > > class dog(mammal): > def speak(self): print 'arf' > > class cat(mammal): > def speak(self): print 'meow' > > for animal in [mammal(), dog(), cat()]: animal.speak() >>>> > umf > arf > meow >>>> > > Terry J. Reedy def curry(f): def f1(*h): def fh(*t): return apply(f , h + t) return fh return f1 class obj: pass def mammal(): def speak(self): print 'umf' self = obj() self.speak = curry(speak)(self) return self def dog(): def speak(self): print 'arf' self = obj() self.speak = curry(speak)(self) return self def cat(): def speak(self): print 'meow' self = obj() self.speak = curry(speak)(self) return self for animal in [mammal(), dog(), cat()]: animal.speak() >>> umf arf meow >>> -- Antoon Pardon From dmq at gain.com Tue May 25 07:27:43 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 04:27:43 -0700 Subject: Method binding confusion References: <mailman.212.1083600570.25742.python-list@python.org> <c760s2$ev4$04$1@news.t-online.com> <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> <c8u3pe$b4v$1@news.service.uci.edu> Message-ID: <goa6b0do3hue7t2a6ffck1ttejb10fnssr@4ax.com> On Mon, 24 May 2004 17:21:07 -0700, Josiah Carlson <jcarlson at uci.edu> wrote: >Whether or not there should be an implied self or not, is a value >judgement. Guido (and everyone else who works on the core Python >language) has heard your (and everyone else's) arguments before. I've seen some of the discussions in searching the archives, but what I have seen misses the point about unification and goes overboard on matters of personal preference. I agree that using an explicit 'self' in the body of the method is a personal preference call that only GvR can make, and I've tried to steer around this issue. Unfortunately, because my suggestion requires taking 'self' out of the first argument, there is an automatic reaction -- oh we've heard that before, another "self hater". >I would put good odds on there not likely to be /any/ sort of change >toward what you are advocating (the merging of functions and methods) in >the forseeable future (before Python 3.0) in standard Python. And even >in the far future (Python 3.0), there is no guarantee. This *is* a Python 3 proposal. No way we can make it backward compatible with Python 2. My focus instead has been on making the changes "migratable" -- that is, we *must* have the ability to automatically translate existing Python programs to the new syntax. These are minor improvements in the language, and no such improvement would be worth the loss of ten years development in Python. -- Dave From daniel.dittmar at sap.com Wed May 19 07:21:06 2004 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 19 May 2004 13:21:06 +0200 Subject: drag drop from linux to a wxpython application References: <40ab3ae7$0$21248$636a15ce@news.free.fr> Message-ID: <c8ffv9$f9g$1@news1.wdf.sap-ag.de> marco wrote: > I've got a wxpython application > and when i drag'n' drop files from(linux) rox/nautilus/konqueror to > my app i've got strange chars in filenames (on win32 : it works well) > > example: > - my dir "my photos" will become "/home/marc/my%20photos" > - a dir "f?tes ? strass" will become (something like this) > "/home/marc/f%A8%CFtes%20%8F%AC%20strass" use urllib.unquote: >>> import urllib >>> urllib.unquote ("/home/marc/my%20photos") '/home/marc/my photos' I guess that the result is a utf8 string which has to be translated to ASCII Latin1 or UCS[24] to become a regular Python string. At least that would explain why ? and ? occupy two characters in the encoded form. Daniel From http Tue May 11 15:53:16 2004 From: http (Paul Rubin) Date: 11 May 2004 12:53:16 -0700 Subject: Cannot import Python 2.3.3 RPM GPG key References: <mailman.420.1084267871.25742.python-list@python.org> Message-ID: <7xy8nyn3kj.fsf@ruckus.brouhaha.com> Choo Zhi Min <zhimin at iss.nus.edu.sg> writes: > I was trying to verify Python 2.3.3 RPM packages on Fedora 1. I > downloaded the key from > http://www.python.org/ftp/python/2.3.3/rpms/KRUD-GPG-KEY, but rpm > --import gave error when importing the keys. I used gpg --import and > also got the same problem. > > Is the key ok? Where can I get a good one? Thank you. That key looks malformed. From andrew-pythonlist at puzzling.org Sun May 9 08:34:17 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 9 May 2004 22:34:17 +1000 Subject: how robust is (CGIHTTPServer ) In-Reply-To: <409E1F4B.4060205@cfl.rr.com> References: <mailman.369.1084064582.25742.python-list@python.org> <pan.2004.05.09.02.22.24.953032@sbcglobal.net> <409E1F4B.4060205@cfl.rr.com> Message-ID: <20040509123417.GA9280@frobozz> On Sun, May 09, 2004 at 08:08:43AM -0400, pxlpluker wrote: > can anyone point out a good example of setting up a cgi capable twisted > web? from twisted.web import twcgi, server from twisted.application import internet, service cgidir = twcgi.CGIDirectory('/var/www/cgi-bin') # Or wherever site = server.Site(cgidir) application = service.Application('cgi-demo') sc = service.IServiceCollection(application) i = internet.TCPServer(8080, site) i.setServiceParent(sc) if __name__ == '__main__': from twisted.internet import reactor sc.startService() reactor.run() sc.stopService() This script can be run directly, or you can use Twisted's "twistd" utility on it, which provides logging and daemonisation for you. (And if you use twistd you don't need the if __name__ == '__main__' part.) So, save this script as cgidemo.py and do: python cgidemo.py or: twistd -noy cgidemo.py # See twistd docs for meanings of -n, -o and -y. See http://twistedmatrix.com/documents/current/howto/using-twistedweb for more details, or ask on the twisted-web mailing list (http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web). -Andrew. From johan at svedberg.pp.se Thu May 13 15:05:24 2004 From: johan at svedberg.pp.se (Johan Svedberg) Date: Thu, 13 May 2004 19:05:24 +0000 (UTC) Subject: Help with Distutils References: <slrnca77ma.5il.johan@svedberg.pp.se> <qnkfza4upl5.fsf@arbutus.physics.mcmaster.ca> Message-ID: <slrnca7hnk.5il.johan@svedberg.pp.se> * David M. Cooke <cookedm+news at physics.mcmaster.ca>: [...] > Hope this helps. It does! This was the exact problems I thought of myself! A huuuge thanks for taking the time to break this down for me! Regards, -- Johan Svedberg, johan at svedberg.pp.se, http://johan.svedberg.pp.se/ From __peter__ at web.de Sat May 1 03:16:17 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 May 2004 09:16:17 +0200 Subject: Dictionnary vs Class for configuration References: <40929016$0$8635$626a14ce@news.free.fr> Message-ID: <c6vis2$pts$02$1@news.t-online.com> Famille Delorme wrote: With a little bit of glue you can define the configuration in _your_ style while accessing it in your _professor's_: <config.py> config_sql = { "DATABASE" : "nanana", "USERDB" : "bob", "PASSWORD" : "********" } config_script = { "TIMETOSLEEP" : 100, "PATH" : "/home/script" } </config.py> <configwrapper.py> import config class Config: def __init__(self, section): d = getattr(config, "config_%s" % section.lower()) for k, v in d.iteritems(): setattr(self, k.lower(), v) </configwrapper.py> Use it: <useconfig.py> from configwrapper import Config cfg = Config("SQL") print cfg.database </useconfig.py> Your _users_ might prefer a solution based on ConfigParser, as they most likely have already been exposed to its format: [SQL] DATABASE=nanana USERDB=bob PASSWORD=******** Peter PS: Remember to avoid storing the password in plain text From nid_oizo at yahoo.com_remove_the_ Wed May 26 18:36:09 2004 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 26 May 2004 18:36:09 -0400 Subject: Update with pickle In-Reply-To: <sI7tc.22267$Wc.780951@twister2.libero.it> References: <AoIsc.27189$tb4.933533@news20.bellglobal.com> <GYJsc.72376$Qc.2938525@twister1.libero.it> <LoKsc.27890$tb4.968272@news20.bellglobal.com> <aSMsc.42$Rp4.28350@monger.newsread.com> <gaPsc.29315$tb4.1059921@news20.bellglobal.com> <OpUsc.2509$Hf.1455264@newshog.newsread.com> <ljWsc.39527$tb4.1256693@news20.bellglobal.com> <y21tc.41582$tb4.1325901@news20.bellglobal.com> <sI7tc.22267$Wc.780951@twister2.libero.it> Message-ID: <pZ8tc.45374$tb4.1453851@news20.bellglobal.com> Matteo Dell'Amico wrote: > Well, it's not possible: variables are just names attached to objects, > and while you can assign a name to an object, you *can't* change the > object's type, or replace an object with another one. I think it is acceptable that this pickle.update function would only accept reference of same type and raise an exception otherwise. The point of pickle.update would be to not "replace an object with another one" but to call __init__ on an existing object. > And I think that copying __dict__ is a hack: it wouldn't work, for > instance, with builtin types, when __slots__ are used, or when you are > using properties. I agree it's a hack. It think the best solution would be direct support by pickle module and according to Stefan's post, I'm not the only one with that need (by the way, not only __dict__ can be copied, all other necessary stuff also). > A transparent proxy is a clean way to do it: through delegation, it > would work with any kind of object, changes in code are localized in the > load/save part, and the rest of the application wouldn't even notice. I have experienced problems with proxies. They are never totally transparent, even if all access to members and methods work. For example, a call to isinstance with the proxy would fail because it is not of the same type as the aggregated object. All these glitches can be fixed, but it makes the solution less transparent. Another problem is that the solution is intrusive, meaning that all objects that are dumped must have a corresponding proxy, while the best solution would be to keep this detail at one place and only in the load/dump part of the application. So on the design point of vue, I prefer the hack. Regards, Nicolas From seefeld at sympatico.ca Tue May 18 10:14:24 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 18 May 2004 10:14:24 -0400 Subject: error converting list to tuple Message-ID: <40AA1A40.9090404@sympatico.ca> hi there, I'm trying to convert a tuple to a list, and get a 'TypeError: list objects are unhashable'. Can anybody enlighten me as to the possible causes for this ? Where does hashing come into play during this conversion ? Could it be that my runtime is corrupted ? The code is executed from within a C++ extension module I'm developing... Thanks for any help, Stefan PS: I'm using python 2.3.3 in case that matters From jacek.generowicz at cern.ch Tue May 25 11:25:55 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 May 2004 17:25:55 +0200 Subject: Dynamic languages can be compiled [Was: Prothon gets Major Facelift in Vers 0.1.0 [Prothon]] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> <tyf7jv0n7dt.fsf@pcepsft001.cern.ch> <tyf1xl8n0yl.fsf_-_@pcepsft001.cern.ch> <Xns94F48E9E3C9CCduncanrcpcouk@127.0.0.1> Message-ID: <tyfwu30le9o.fsf@pcepsft001.cern.ch> Duncan Booth <me at privacy.net> writes: > Using Psyco speeds things up somewhat. On my machine this test in Python > without Psyco takes 14.31s, adding a call to psyco.full() reduces this to > 0.51s Good call. How daft of me not to include it. Here's the table with the psyco result on the same machine as the rest. Name Interpreted Compiled With declarations Psyco LispWorks 66 1.0 1.6 Clisp 41 9.5 9.5 CMUCL Got bored waiting 1.5 0.45 SBCL Compiles everything 1.6 0.49 Python Compiles everything 20 0.64 gcc No interactivity 0.29 Could we now just all agree, once and for all, that compiling dynamic languages to native binary really can give significant speedups? (No, of course we can't ... oh well :-) From lbates at swamisoft.com Wed May 26 10:15:15 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 26 May 2004 09:15:15 -0500 Subject: Some Newbie Questions References: <40b47710@e-post.inode.at> Message-ID: <Tq-dnS4zgJvpOyndRVn-jg@comcast.com> On question #1: I see this question a lot on this list, but I'm curious about why you don't want to instantiate the class? I can't think of a reason not to and am very curious if I'm missing something here??? On question #2: I normally write my programs so that they can be called with an option on the processor call line to override the "config-file". Something like: python foo.py -i newconfigfile.ini Then I use ConfigParser to read the options from the .INI file. This provides unlimited flexibility in having .INI files to drive the program. I find that reading config parameters from an external .INI file to be superior to putting values in a .PY file and importing it. I know others on this list may differ. On question #3: I use loggerclass to keep trace/debug information in a logfile as the program executes. Actually I normally have debug "levels" that give increasingly more information as the number increases. I read these from .INI file but allow user to override the .INI file on the processor call line. Example: python foo.py -t -d 2 would turn trace on and debug at level 2 Then put lines in your code like: if trace: log("Entering function a") HTH, Larry Bates Syscon, Inc. "Leopold Schwinger" <leoel at gmx.at> wrote in message news:40b47710 at e-post.inode.at... > Hello! > > I am a really newbie to python, and I have some questions. I couldn't > find anything in the manual, so it would be nice if you could help me. > > (1) Is there any operator in Python in order to call a Member-Function > from a class without creating an instance of the class? (In C++ and PHP > there ist this operator "::" <class>::<memberfunction>) > > (2) Is there any way to dynamically import modules, where the name of > the module is not known during implementation but can be defined durch > scipt execution? Think of lots of different config-Files, which differ > by Path & Name but the variables are all named equal, and i want to > import a special config-File during the execution of the script. > > (3) Is there any way to obtain a kind of "trace"-Info (the actual > filename and codeline) in order to provide some debug-Info in the case > of errors (In C++ and PHP there are these "__line__" and "__file__" > functions, For Python I have only found <Class>.__dict__ and dir(<Class>)) > > Thank you very much, > Leo From tim.one at comcast.net Fri May 14 12:51:07 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 14 May 2004 12:51:07 -0400 Subject: how to run an arbitrary function with timeout? In-Reply-To: <2004051412111084551099@k2.sage.att.com> Message-ID: <LNBBLJKPBEHFEDALKOLCCEODKPAB.tim.one@comcast.net> [Garry Hodgson] > i'm building a test suite on top of unittest, and some > of the tests involve things that might hang, like trying > to connect to a wedged server. so i'd like a simple function > that i can call that will run a given (func,args) pair and > return either the value or raise an exception if it times > out. this seems like it should be straightforward, but i've > not had much luck getting it to work. > > my latest attempt, below, raises the exception ok, > but still doesn't return until snooze() completes: What doesn't return? The snooze() function? You told that to sleep for 10 seconds, and it does, then it prints 'waking up' and returns. Your call to RunWithTimeout also returns, at the point it raises its exception. You can't expect to see "ok" get printed, because when you raise TookTooLong, RunWithTimeout's invocation ends immediately (as raising an uncaught exception does in any function, threads or not) -- RunWithTimeout never executes its "return 'ok'" line. > --> xx > going to sleep > Traceback (most recent call last): > File "./xx", line 26, in ? > print RunWithTimeout( snooze, (10,), 2 ) > File "./xx", line 16, in RunWithTimeout > raise TookTooLong, 'fsdfsdf' > __main__.TookTooLong: fsdfsdf > > ...8 second delay here... > > waking up > > > can someone tell me what i'm doing wrong? Best I can guess, you're expecting something that can't happen, but I'm not sure exactly what. > #!/usr/bin/env python2.3 > > from threading import * > from time import sleep > > class TookTooLong( Exception ): > pass > > def RunWithTimeout( func, args, timeout ): > t = Thread( target=func, args=args ) > t.start() > t.join( timeout ) > > if t.isAlive(): > del t That line didn't accomplish anything useful. If you expected it to "do something", then that's the problem. All it does is unbind the local name "t". If, for example, you expected it to kill the thread, that won't happen. > raise TookTooLong, 'fsdfsdf' > return 'ok' > > > def snooze( duration ): > print 'going to sleep' > sleep( duration ) > print 'waking up' That function executes in its entirety when you call it, and there's nothing you can do to stop that (Python doesn't supply any way to stop a thread T from outside T). > > if __name__ == '__main__': > print RunWithTimeout( snooze, (10,), 2 ) It would have helped a lot if you had spelled out the output you *expected* to see. The output this actually produced is what I expected to see. From PeterAbel at gmx.net Thu May 13 15:44:00 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 13 May 2004 12:44:00 -0700 Subject: Printing formatted strings from a dictionary References: <b4a8ffb6.0405121230.a564636@posting.google.com> <m3r7toh75g.fsf@pc150.maths.bris.ac.uk> Message-ID: <21064255.0405131144.160af9a8@posting.google.com> Michael Hudson <mwh at python.net> wrote in message news:<m3r7toh75g.fsf at pc150.maths.bris.ac.uk>... > tkpmep at hotmail.com (Thomas Philips) writes: > > > I want to print "1 spam 4 you" using a formatted string that gets its > > inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, > > I write > > > > >>> x="%('n1')d %('s1')s %('n2')d you" > > >>> x % d > > > > Traceback (most recent call last): > > File "<pyshell#22>", line 1, in -toplevel- > > x % d > > KeyError: "'n1'" > > >>> > > > > However, I get what I want if I edit x to remove the quotes around n1, > > s1 and n2 and write > > >>> x="%(n1)d %(s1)s %(n2)d you" > > >>> x % d > > '1 spam 4 you' > > > > The syntax that works seems to run counter to the way dictionaries > > work: > > >>> d['n1'] > 1 > > >>> d[n1] > > > > Traceback (most recent call last): > > File "<pyshell#18>", line 1, in -toplevel- > > d[n1] > > NameError: name 'n1' is not defined > > > > What is the error in my logic? > > Um. If the n1 is already inside a string literal, adding more quotes > would be redundant? > > CHeers, > mwh In Python every variable is hold in a dictionary where the key is a string with the variable's name and the value is the object where the variable is bound to. The dictionary which holds the global variables is globals() the dictionary for the local variables is locals() and the dictionary for instances-attributes is instance.__dict__. And always the key of the dictionary is a string. But when you play around with a variable you address it by its name not by a string. So the following is equivalent: >>> x=1 >>> globals()['x']=2 As you see: >>> x 2 >>> x=4 >>> globals()['x'] 4 >>> The same is in the following example: >>> class A: ... def __init__(self): ... self.a=1 ... self.b=2 ... >>> x=A() >>> x.a 1 >>> x.b 2 Addressing x.a and x.b by dictionary: >>> x.__dict__['a'] 1 >>> x.__dict__['b'] 2 >>> And back to your problem. Though the keys in the dictionaries are strings you can address them by their names even if it is a self-made dictionary and the same way you have to do in dictionary-formatting. >>> y=999 >>> s='foo' >>> print '%(s)s = %(y)d' % globals() foo = 999 >>> Or >>> print 'x.a=%(a)d x.b=%(b)d' % x.__dict__ x.a=1 x.b=2 >>> Regards Peter From Chris.Hornberger at blackrock.com Wed May 12 08:43:23 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 08:43:23 -0400 Subject: Idea for Python T-shirt Message-ID: <ABADC7F2A1794A4C94657344DC1050930648BB28@BRDEL-EXCH02.na.blkint.com> EXCELLENT SUGGESTION!! Also: "I'll have the Python." "Excellent choice, Sir." -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Simon Wittber Sent: Tuesday, May 11, 2004 8:57 PM To: python-list at python.org Subject: RE: Idea for Python T-shirt A python T-Shirt? Funnily enough, I was thinking on this last night. Something eloquent, something slightly obscure, which only other Pythonistae would recognize: "import this" Sw. -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Wed May 26 13:01:43 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 May 2004 13:01:43 -0400 Subject: creating .exe file In-Reply-To: <c92htp$atq$1@swifty.westend.com> References: <3f0686ff.0405260841.6deba711@posting.google.com> <c92htp$atq$1@swifty.westend.com> Message-ID: <9rOdnWFMhMvqUCndRVn-tA@powergate.ca> Peter Maas wrote: > Q X wrote: >> I am wondering what kind of tools are available to wrap python scripts >> into just 1 .exe file (with no other files) in windows. I also want >> the .exe file to be able to use command line arguments ie. >> pythonprogram.exe -classpath d:/temp -file c:/hi.text > > http://sourceforge.net/projects/py2exe He explicitly asked for "just one .exe file (with no other files)", but py2exe cannot do that. Unfortunately, unless the commonly available automatic decompressor programs can pass command line options on to the program they invoke, it's probably not possible... -Peter From sridharinfinity at yahoo.com Tue May 11 08:39:36 2004 From: sridharinfinity at yahoo.com (Sridhar R) Date: 11 May 2004 05:39:36 -0700 Subject: Debuggin a ptyhon extension References: <rzxmc.26524$j11.254148@weber.videotron.net> Message-ID: <930ba99a.0405110439.499dae05@posting.google.com> See this recipe. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82826 Steve Menard <devilwolf22 at hotmail.com> wrote in message news:<rzxmc.26524$j11.254148 at weber.videotron.net>... > I am writing a python extension module in VC++ on windows. At some > point, my extension crashes. > > Now I want to debug exactly why. I built the python projects in VC++, > and put the resulting python_d.exe in my ptyon home directory, and the > python23_d.dll in the windows/system32 directory. I also tried to put > the python23_d.dll in python's home directory, to the same result. > > Problem is, running my scripts/extension with python_d.exe, it always > complains it can't find win32api. Yes, I am using win32API to preload a > dll, and can't really get rid of it. > > To try and solve this, I tried replacing the "stock" python.dll with my > python_d, so at least VC++'s debugger would see the debug info. but I > got the same result, of win32api not being found ... > > What is the best way to go about this? My extension will require a fair > amount of native code and interacting with the Python code, so being > able to trace into python would be invaluable. > > Are my problems caused because python 2.3.3 (and possible win32all) were > build using VC.net? > > I am grateful for any help you guys can provide. > > > Steve Menard > devilwol22 at hotmail.com From lbates at swamisoft.com Thu May 20 16:30:11 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 20 May 2004 15:30:11 -0500 Subject: N-Tier Web Applications, Application Servers and Python References: <mailman.116.1085077026.6949.python-list@python.org> Message-ID: <MPednV9viY3OiDDdRVn-hg@comcast.com> You should review Zope. www.zope.org Larry Bates Syscon, Inc. "Orr, Steve" <sorr at rightnow.com> wrote in message news:mailman.116.1085077026.6949.python-list at python.org... I'm looking to architect a 4-tier or N-tier Python web/CGI app with database connection pooling for high performance. Is there a Python equivalent to Sun's now famous Java PetStore application? (Or something like this link: http://www.developer.com/tech/article.php/606971?) Any Python recommended links/white papers? I've glanced at various Python utilities and frameworks (including Twisted) but what I really need is a fairly complete and robust sample/demo app like Java PetStore. If there is no such Python equivalent then there OUGHT to be. ;-) TIA, D. B. From ville at spammers.com Wed May 12 02:29:23 2004 From: ville at spammers.com (Ville Vainio) Date: 12 May 2004 09:29:23 +0300 Subject: Daily Python URL alert (was Re: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <109t59e3v0oob1d@news.supernews.com> <8cGdnYFHpPRsBgLdRVn-iQ@comcast.com> <r7trt5po.fsf@wgmail2.gatwick.eur.slb.com> Message-ID: <du7d65a40qk.fsf_-_@amadeus.cc.tut.fi> >>>>> "Pete" == Pete Forman <pete.forman at westerngeco.com> writes: Pete> For a less obfuscated approach, look at PyOne to run short python Pete> scripts from a one-line command. Pete> http://www.unixuser.org/~euske/pyone/ Looks exactly like something I always wanted to implement, but found that doing the script in a multi-line file is easier. It's great that someone has got around to imlpement something like this. There should be a wiki entry for "quick and dirty python" (sounds somehow... suspicious ;-), having awk/sed/oneliner workalikes. -- Ville Vainio http://tinyurl.com/2prnb From aoteo at riojalta.com Mon May 24 06:30:27 2004 From: aoteo at riojalta.com (Alberto Oteo) Date: Mon, 24 May 2004 12:30:27 +0200 Subject: =?iso-8859-1?q?Envi=F3_el_mensaje_infectado=2E?= Message-ID: <000401c4417a$21757d60$7b00a8c0@RALTA.ES> Kaspersky AV encontr? el mensaje De: python-list at python.org Para: aoteo at riojalta.com Copiar: Copia sin salida: Fecha: lunes, 24 de mayo de 2004 Hora: 12:18 Asunto: Does it matter? contiene virus. Anal?celo con Kaspersky AV Scanner. From lbates at swamisoft.com Tue May 25 10:39:49 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 25 May 2004 09:39:49 -0500 Subject: in operator for strings References: <TSDsc.72714$pN7.62390@newssvr25.news.prodigy.com> Message-ID: <nZSdnVOFbJEpxy7dRVn-uQ@comcast.com> This can be written as: a=('hello','test') b='blah blah hello blah test' reduce(lambda x,y: x and b.count(y), a) or as a fuction: def contains_all(a, b): return reduce(lambda x,y: x and b.count(y), a) Then in main program if contains_all(a,b): ... Larry Bates Syscon, Inc. "Moosebumps" <moosebumps at moosebumps.mb> wrote in message news:TSDsc.72714$pN7.62390 at newssvr25.news.prodigy.com... > Wouldn't it be cool if you could do this? > > ('hello','test') in 'blah blah hello blah test': > > and it would say if all elements of the list are in the string? > > it would be more efficient and more readable than: > > 'hello' in 'blah blah hello blah test' and 'test' in 'blah blah hello blah > test' > > From beliavsky at 127.0.0.1 Wed May 26 17:18:23 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 26 May 2004 16:18:23 -0500 Subject: Changing file names References: <b4a8ffb6.0405261213.33b823ce@posting.google.com> Message-ID: <40b5099f_1@127.0.0.1> tkpmep at hotmail.com (Thomas Philips) wrote: >I want to get a list of all subdirectories of a given directory, and >within each directory, change the name of each file using a >predetermined rule. > >The function glob in module glob will give me a list of all the >subdirectories, and by looping over this list and repeatedly calling >glob, I can create lists of files within each directory, which are >easily edited to create lists of new filenames. > >How then can I change the existing filenames to these new filenames? >What python functions should I be using, and what modules are they >contained in? > >Thomas Philips There is a "rename" function in the "os" module. ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From guardian at supereva.it Fri May 14 06:50:01 2004 From: guardian at supereva.it (david mugnai) Date: Fri, 14 May 2004 12:50:01 +0200 Subject: Speed up properties?! In-Reply-To: <mailman.6.1084523316.4157.python-list@python.org> References: <40A45DAD.2020906@konzept-is.de> <20040514055428.GE24078@frobozz> <mailman.6.1084523316.4157.python-list@python.org> Message-ID: <8v728c.va4.ln@192.168.0.200> Dr. Peer Griebel wrote: > Andrew Bennetts wrote: > >> On Fri, May 14, 2004 at 07:48:29AM +0200, Dr. Peer Griebel wrote: >> >>> Hi, >>> >>> I have a class with some properties. I would like to verify that only >>> valid values are assigned to the properties using assert. Therefore I >>> code setters and getters and use property() to convert these to have a >>> real property. >>> >>> Since the verification is only performed in __debug__ runs the >>> property() is quite a lot of overhead. I tried to circumvent it. This >>> is my result so far: What do you think about this: import types class Meta1(type): def __new__(mcl,classname,bases,classdict): if not __debug__: return type.__new__(mcl,classname,bases,classdict) GetterName="_%s__get_" % classname SetterName="_%s__set_" % classname Properties={} for x in classdict: if isinstance(classdict[x],types.FunctionType): if x.startswith(GetterName): name=x[len(GetterName):] Properties[name]=property(classdict[x], classdict[SetterName+name]) classdict.update(Properties) return type.__new__(mcl,classname,bases,classdict) class A(object): __metaclass__=Meta1 def __init__(self): self.x=5 def __get_x(self): return self._x def __set_x(self,value): if value>5: raise ValueError,value self._x=value S=A() print S.x S.x=12 print S.x --------------------------- HTH dvd -- Being married to a programmer is like having a cat. You talk to it but you're never really sure if it hears you, much less comprehends what you say From dmq at gain.com Fri May 14 11:29:42 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 14 May 2004 08:29:42 -0700 Subject: classes vs dicts References: <be05f1d.0405060212.43929fe1@posting.google.com> <nj57a01tqsvtufcur2gqu3enbjll5l95id@4ax.com> <mailman.522.1084465993.25742.python-list@python.org> Message-ID: <mbp9a0tu8et4v0gg0hm3r6oqu7412r4qdt@4ax.com> Excellent! Someday, I hope to be smart enough I can see such a simple solution right away. -- Dave MacQuigg On Thu, 13 May 2004 10:33:09 -0600, "Dave Brueck" <dave at pythonapocrypha.com> wrote: >David wrote: >> My problem is similar, with the additional requirement that I need a >> convenient way to access data deep within a hierarchy of parameters. >> I chose classes over dictionaries because the syntax to access items >> in a deeply nested dictionary is awkward. >> >> dict[window1][plot2][xaxis][label][font][size] = 12 >> >> vs >> >> statefiles.window1.plot2.xaxis.label.font.size = 12 >> >> The problem is I can't easily save the whole hierarchy to disk. >> Pickle doesn't work with classes. Also, I worry about the overhead of >> classes when I am just needing a simple container. A typical >> statefile will have 1000 parameters in 300 classes nested up to ten >> levels deep. As a structure of nested classes this takes about 74KB >> on disk. Importing the file creates a .pyc file that is 157KB !! It >> does seem to import quickly, however, so speed may not be a problem. >> >> Seems like Python could use a "container" structure which would be >> like a class, but without the overhead and with the ability to >> "pickle" the whole structure. > >Forgive me if I don't understand the problem, but why can't you just do: > >class Bag: > def __init__(self, **kwargs): > self.__dict__.update(kwargs) > >Then if your data is like: > >settings > network > ip = '10.20.30.40' > port = 1234 > logging > level = 3 > >you would construct it by hand like: > >settings = Bag(network=Bag(ip='10.20.30.40', port=1234), logging=Bag(level=3)) > >and you can access members like: > >print settings.network.ip >or >settings.network.useSSL = 1 >etc. > >and you can easily pickle _instances_ so persistence isn't really a problem: > >from cPickle import dumps, loads >q = dumps(settings) >newSettings = loads(q) > >Unless I'm misunderstanding the problem, the only remaining issue is the >overhead. If that really is a problem (most likely not, but maybe if you're >transferring it over a slow network connection or something), then simply use >the built-in gzip or bz2 modules. > >-Dave > From brian at sweetapp.com Wed May 12 14:17:29 2004 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 12 May 2004 20:17:29 +0200 Subject: ANN: Vancouver Python Workshop Message-ID: <40A26A39.1030401@sweetapp.com> Vancouver Python Workshop ========================= The Vancouver Python and Zope User Group is pleased to announce the Vancouver Python Workshop. The conference will begin on July 31st with keynote addresses by Guido van Rossum (the creator of Python) and Paul Everitt (co-founder of Zope Corp). Further talks (and tutorials for beginners) will take place on August 1st and 2nd. The conference will be roughly divided into three tracks: o Python language and applications o Content management with Python (esp. Zope and Plone) o Python for beginners More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/travel.html http://www.tourismvancouver.com Important dates =============== Paper proposals accepted: May 17th to June 15th Attendee registration: June 1st to June 30th Late registration: from July 1st Keynotes, preconference sprints & tutorials: July 31st Conference and tutorial dates: August 1st and 2nd (1) http://news.bbc.co.uk/2/hi/business/2299119.stm http://www.mercerhr.com/pressrelease/details.jhtml?idContent=1128760 Cheers, Brian From mva at sysfault.org Wed May 12 18:07:54 2004 From: mva at sysfault.org (Marcus von Appen) Date: Thu, 13 May 2004 00:07:54 +0200 Subject: __slots__ vs __dict__ References: <120520041314481389%JBrouwers@ProphICy.com> Message-ID: <86hdul2tad.fsf@sysfault.org> Jean Brouwers <JBrouwers at ProphICy.com> writes: > Classes using __slots__ seem to be quite a bit smaller and faster > to instantiate than regular Python classes using __dict__. [snip] Yes, but instances usually will not have a Class.__dict__ attribute anymore. Thus the following code throws an exception on binding new attributes on a per-instance basis: # start class Foo (object): __slots__ = "_test" def __init__ (self): self._test = None if __name__ == "__main__": f = Foo () f.testvar = "test" return # end Rebinding __slots__ in __setattr__ fails with a bus error on my system (it should not be possible anyways, because __slots__ is a tuple): # start class Foo (object): __slots__ = "_test", "_test2" def __init__ (self): self._test = 1 self._test2 = 2 def __setattr__ (self, name, value): # just test a simple rebinding self.__slots__ = self.__slots__ return if __name__ == "__main__": f = Foo () f.testvar = "test" return # end --- gdb backtrace (gdb) r foo.py ... Program received signal SIGBUS, Bus error. 0x08070050 in PyDict_GetItem () (gdb) bt #0 0x08070050 in PyDict_GetItem () #1 0x08080ab7 in _PyType_Lookup () .... Regards Marcus -- We don't understand the software, and sometimes we don't understand the hardware, but we can *see* the blinking lights! From ajsiegel at optonline.com Sat May 22 17:52:51 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 22 May 2004 21:52:51 GMT Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> <1085210465.206473@yasure> <lqcua09sc615finsdk2jknvcobgbia31l5@4ax.com> <1085248385.210031@yasure> Message-ID: <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> > > Consider use of tuples such as (hostname, port) or (firstname, lastname, > middleinitial) or (x_coordinate, y_coordinate). In all cases you *know* > what the first element means, what the second element means etc. It is > usually not useful to find a value since the different values mean > different things. You might rather do this something like - if host_port[1] > == 80:... > >Can you quote _both paragraphs_ of the above and point out the >circularity in his explanation? Given a tuple (1,1,1) representing X,Y,Z corrdinates, I - for one - have trouble explaining the heterogenous nature of the data, outside of the "tuple" sense of the word. Similarly, "conceptual homogeniety" in this context can mean anything - to me, pretty much -, within the limit of describing data elements that it might be sensible to handle together in a list. > >I don't know if homogeneity is the most useful term to get at the >distinction as I understand it, but evidently that's how Guido tried >to explain it, so that's where we start. It can take some explaining. >We could try to think of better ways to approach it - maybe bring in >the notion of a tuple as a "product" of its elements - but the parties >to that discussion would have to 1) understand the distinction, and >2) not be satisfied with the way it's currently explained. No sign >of anyone in that corner yet. The best reason to describe the current explanations as a tautology, is precsiely because it can only really be understood as a meaningful explanation to those who don't really need one. It does little, in my opinion, to serve as help for those who might. Especially, or at least, outside the context of a ten or more post thread of the dialetics. Art From rook_5150 at yahoo.com Fri May 7 00:16:17 2004 From: rook_5150 at yahoo.com (Bryan Castillo) Date: 6 May 2004 21:16:17 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <donn-0FC5DB.15041506052004@nntp6.u.washington.edu> Message-ID: <1bff1830.0405062016.3037b1dc@posting.google.com> Donn Cave <donn at u.washington.edu> wrote in message news:<donn-0FC5DB.15041506052004 at nntp6.u.washington.edu>... > In article <997a06e0.0405061128.6768676d at posting.google.com>, > pugnatio2 at yahoo.com wrote: > > > What's the standard way to implement polymorphic behavior in a python > > method, given that method arguments can't declare their types as > > they're being passed in, and method definitions don't have signatures? > > <snip> > On the other hand, if you want to support a string as an single > value instead of a list or tuple of values, then you're not > really talking about polymorphism here anyway. When a function > decides to support various unrelated types for a particular > parameter, I don't know what you call that, but it isn't > polymorphism in any useful sense. The original poster is talking about function/method overloading as you have in C++ or Java. <snip> From grahamd at dscpl.com.au Sat May 8 04:54:28 2004 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 8 May 2004 01:54:28 -0700 Subject: VIM and tab to space migration References: <c5bg1k$25vq$1@news.wplus.net> <c5c138$i91$1@news.service.uci.edu> <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <mailman.266.1083757569.25742.python-list@python.org> <dc6f5c99.0405061443.5f351f57@posting.google.com> Message-ID: <dc6f5c99.0405080054.343abeb0@posting.google.com> grahamd at dscpl.com.au (Graham Dumpleton) wrote in message news:> I have the following to lines in my .exrc file: > > map ^Ktu 1G!Gunexpand -a^M > map ^Kte 1G!Gexpand^M > > The ^K and ^M are the equivalent control characters. > > I then type ^Ke and it will pipe the whole contents of the file being edited > through "expand" which will turn all tabs into appropriate number of > spaces. Typing ^Ku does the opposite. Whoops, that should read that I type ^Kte and ^Ktu respectively. From Antivirus at heraldnet.com Mon May 24 10:15:02 2004 From: Antivirus at heraldnet.com (Antivirus at heraldnet.com) Date: Mon, 24 May 2004 07:15:02 -0700 Subject: Symantec Mail Security detected an executable file in a message sent from your address. (SYM:34844878131140779714) Message-ID: <444d01c44199$814c27b0$1906b40a@heraldnet.com> Subject of the message: Re: Order [mx][bayes] Recipient of the message: "outbound at heraldnet.com" <outbound at heraldnet.com> If this is a legitimate file, add a 2 to the end of the file extension e.g. .zip2 From kirk at strauser.com Sun May 23 19:40:08 2004 From: kirk at strauser.com (Kirk Strauser) Date: Sun, 23 May 2004 23:40:08 GMT Subject: newbie: why it does not work: command=sys.exit? References: <c8rak8$8g3$1@reader08.wxs.nl> Message-ID: <87isem90ku.fsf@strauser.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-05-23T22:54:53Z, "Paul van Dam" <paul.van.dam at planet.nl> writes: > import sys > widget = Button(None, text='Hello widget world', command = sys.exit) > Traceback (most recent call last): > File "I:\Python\Projecten\#Prog_in_Python\Hfst06\gui02.py", line 5, > in -toplevel- > widget.mainloop() > File "D:\Python23\lib\lib-tk\Tkinter.py", line 965, in mainloop > self.tk.mainloop(n) > File "D:\Python23\lib\lib-tk\Tkinter.py", line 1347, in __call__ > raise SystemExit, msg > SystemExit - From "pydoc sys.exit" Help on built-in function exit in sys: sys.exit = exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). The documentation says that calling sys.exit raises a SystemExit exception. Your program calls sys.exit and gets a SystemExit exception. It seems to be working as expected and documented, unless I'm missing something. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAsTXZ5sRg+Y0CpvERAthNAKCSCOtUsv/6eX4TU+ka0c93tOISrQCfRbRz XvgGK2Kzu137pw4bNlWk7/k= =mWAd -----END PGP SIGNATURE----- From porky_pig_jr at my-deja.com Sat May 1 17:37:44 2004 From: porky_pig_jr at my-deja.com (Porky Pig Jr) Date: 1 May 2004 14:37:44 -0700 Subject: newbie question on Python tutorial example in section 4.7.1 (default arg values) Message-ID: <56cfb0e3.0405011337.2a8710bc@posting.google.com> Hello, hope someone can clarify this section for me (or may be there is a 'newbie FAQs' in which case I would appreciate the link Anyway, the example is def f(a, L=[]): L.append(a) return L and somehow L just keeps growing between the calls, so print f(1) returns [1] and then print f(2) returns [1, 2] etc. I'm not really clear on this example, but assume that L is set aside somewhere (in the function definition), initialized only once (during the def), and then all subsequent calls affect that locally defined L. Given this is how it works (?), I still don't understand how the following workaround works: def f(a, L=None): if L is None: L = [] L.append(a) return L well, it does work, but why? Seems like we initialize L to None (which is as I undersatnd, sort of equivalent of C void), in fact it also works if we initialize L to some arbitrary string. What I don't understand: we check if L is None, and then make it a list and append 'a' to it. So it becomes a list. When then on the subsequent call it is None again rather than list with a single value of 'a' (in the previous call)? TIA From riccardo_cut-me at cut.me.sideralis.net Sat May 22 19:14:49 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Sun, 23 May 2004 01:14:49 +0200 Subject: Problem with PyGTK/Glade2 ComboBox vs ComboEntryBox References: <ec6dce8b.0405211022.7e5ba4b@posting.google.com> <40AF5FDD.7030604@draigBrady.com> <ec6dce8b.0405221332.65ddfed0@posting.google.com> Message-ID: <pan.2004.05.22.23.14.46.951715@cut.me.sideralis.net> On Sat, 22 May 2004 14:32:59 -0700, j_mckitrick wrote: >> Ah this has changed in gtk 2.4 >> http://developer.gnome.org/doc/API/2.2/gtk/gtk-migrating-GtkComboBox.html >> The docs on pygtk.org are out of date, mutter... >> Are you sure (your) pygtk supports the newer model? > > I have no idea. I have what I believe to be the latest pygtk - 2.2.0. > > This has been frustrating me for a while. Is there a workaround? Your version of pygtk does not cover gtk-2.4 changes. You have the latest stable. There is a beta which support new widgets. The last (of yesterday), is pygtk-2.3.92 You can find it at http://ftp.gnome.org/pub/gnome/sources/pygtk/2.3/ Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From heikowu at ceosg.de Sat May 8 01:47:18 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 8 May 2004 07:47:18 +0200 Subject: Unix compress (.Z) files In-Reply-To: <f4fb9bc8.0405071504.51eb9325@posting.google.com> References: <f4fb9bc8.0405071504.51eb9325@posting.google.com> Message-ID: <200405080747.18877.heikowu@ceosg.de> Am Samstag, 8. Mai 2004 01:04 schrieb Peter Smith: > Are there any utilities in Python which can uncompress a file zipped > on a unix system using "compress"? Unix "compress" uses a form of the LZW compression codec (same thing as is used for GIFs), and because of the patent restrictions UniSys has on this codec, it'll be hard to come across a decompressor for this kind of file, if not the original Unix tool itself by now (which is symlinked to gzip on my workstation installation). As far as I know, Python has no binding to an LZW-decompression library (zlib uses something completely different), and so you're on your own. But coding an LZW decompressor is not that hard... ;) Heiko. From skip at pobox.com Wed May 19 09:30:50 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 May 2004 08:30:50 -0500 Subject: unique number generator In-Reply-To: <008d01c43d8d$2c301c10$7f00a8c0@scl01.siliconcreation.com> References: <008d01c43d8d$2c301c10$7f00a8c0@scl01.siliconcreation.com> Message-ID: <16555.24970.423668.102314@montanaro.dyndns.org> I need to implement a unique number generator that 1 or more processes on same or different machines will make use of it. Is there any library / project available already for this? If blazing performance isn't an issue I'd just use the SimpleXMLRPCServer class to write a little server that increments a stored counter. Something like this: from SimpleXMLRPCServer import SimpleXMLRPCServer class Counter: def __init__(self): self.i = 0 def tick(self): self.i += 1 return self.i server = SimpleXMLRPCServer(('localhost', 10000)) server.register_instance(Counter()) server.serve_forever() A client would then do something like import xmlrpclib counter = xmlrpclib.ServerProxy("http://localhost:10000") i = counter.tick() j = counter.tick() print i, j Obviously you can get more elaborate than that (saving/restoring counters across runs or allocating blocks of numbers for more efficiency, for example), but the above appears to satisfy your initial requirements. Skip From greg at cosc.canterbury.ac.nz Mon May 24 23:31:49 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 25 May 2004 15:31:49 +1200 Subject: Unification of Methods and Functions In-Reply-To: <ukp4b01o1lfgh2h4b3e0qc40a9bc2ck30c@4ax.com> References: <16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com><slrnca6d58.1i9.apardon@trout.vub.ac.be><mailman.516.1084460227.25742.python-list@python.org><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <mailman.188.1085259396.6949.python-list@python.org> <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> <ukp4b01o1lfgh2h4b3e0qc40a9bc2ck30c@4ax.com> Message-ID: <2hft17Fc8642U1@uni-berlin.de> David MacQuigg wrote: > My perspective may be different, because I have not yet absorbed the > Python traditions, and I don't have any instictive avoidance of static > methods. Are you coming at this from a Java perspective? In Java (and in C++ until recently) you're forced to use static methods, because the class is the only kind of namespace available. But Python has modules for use as general-purpose namespaces. Classes are thus relieved of the burden of performing this double duty, leaving them free to concentrate on what they do best, which is defining the behaviour of a collection of objects. I really recommend that you *use* Python for long enough to get a good feel for it, before attempting to revise it. Trying to reform something that you don't thoroughly understand is fraught with danger. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From phil at riverbankcomputing.co.uk Wed May 5 16:04:15 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 5 May 2004 21:04:15 +0100 Subject: PyQT developement for Windows In-Reply-To: <Aramc.39435$Qc.1546143@twister1.libero.it> References: <Aramc.39435$Qc.1546143@twister1.libero.it> Message-ID: <200405052104.15867.phil@riverbankcomputing.co.uk> On Wednesday 05 May 2004 7:33 pm, Fabio Corneti wrote: > Hi all, > I read many posts on the subject, but I'm still confused about > licensing issues with PyQT. > > I'm going to start a new project, and I'd like to use PyQT because > it is an excellent product; the particular issue is that > we would like to make the source code available under the GPL, > but we would also like to distribute a compiled version for Win32. > > Having a commercial copy of QT and PyQT, would it be possible to > develop a GPL version which would remain GPLed where PyQT and QT > are GPL and build the Windows version from this code to redistribute > it in some manner (e.g. freeware)? It's up to you how you license your own application so there is no problem with dual licensing it - the GPL and one that is compatible with a Windows version of Qt and PyQt. The problem is how do your users get a copy of Qt and PyQt? Depending on your circumstances, and those of your users, you have the choice of the non-commercial version (free but Qt v2 only), the educational version (free if you are an educational institution), or the commercial version (not free but you can redistribute Qt and PyQt to anybody with your application). Phil From alan.gauld at btinternet.com Sat May 29 07:13:20 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 May 2004 12:13:20 +0100 Subject: "Private" Member Variables References: <c97r0b$jqq$1@news01.intel.com> Message-ID: <h8rgb0ptjmh4dgup1esgqk6mgihe37ebba@4ax.com> On Fri, 28 May 2004 09:56:43 -0700, "Scott Brady Drummonds" <scott.b.drummonds.nospam at intel.com> wrote: > necessary. Given that the very nature of the language precludes any > compile-time type dependencies I'm wondering if there is any benefit to > naming variables with leading underscores and providing accessor functions > like this: > class C: > ... > def value(self): > return self.__value > ... There is very rarely any good reason to provide getXXX/setXXX type accessor functions, even in C++ (JavaBeans are something of an exception because tools need them). The whole point of information *hiding* is that external objects can't access your internal data, they access behaviours. Exposing your data via accessor functions is still exposing it (albeit with control over read/write access). But why does another object need your data? you own it so you should manage it, if something needs doing you should do it - via a behaviour. Indeed, there is a school of thought in OOD that says member data is *only* there to support the published behaviour. Now you may want behaviour that returns a bit of data (like bank account balance) but even in that case, conceptually the balance could be a calculated value. But if you really must display your internal data to the world the best way is as a property IMHO. > why provide an accessor at all? Why not just allow direct reading and > writing of the member variable? Is there something here I'm missing? There should be very little need to access the data at all if the class provides the needed set of ehaviours. If you have an application where objectts are accessing other objects data then that's usually a sign that the OO Design is broken somewhere. > What are your thoughts? How much privacy should I build into my code? If there is tight dependency between two values such that if somebody external changed one (through not appreciating the interdependency) it would make the other semantically inaccurate then its a good idea to hide them to protect yourself. But if we allow a certain amount of trust in our fellow programmers all other variables can be left exposed and we rely on them to use the behaviour published via the methods and not to mess with the innards. That's my personal approach at least... OTOH If you are putting your objects out as a library for general consumption you may take a more conservative view based on the idea that the less things users can break the less work for you. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From stephen.no at spam.theboulets.net.please Sun May 2 07:49:39 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Sun, 02 May 2004 06:49:39 -0500 Subject: Help with ConfigParser Message-ID: <MYWcnSl3C8w-fAnd3cwC-w@speakeasy.net> I'm having a bit of trouble getting my head around the ConfigParser module. I have a very simple configuration file; maybe the easiest thing to do would be to show that: ============ # Add a local directory to be backed up followed # by the directory name on the FTP server. # # Example: /home/joe/digital photos = photos [Backups] /home/stephen/photos/digital camera = photos /home/stephen/documents/tax documents = taxes ============ I just want to retrieve the information in the backups section. Thanks. -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From temp1111 at hotmail.com Wed May 19 10:33:33 2004 From: temp1111 at hotmail.com (temp1111) Date: 19 May 2004 07:33:33 -0700 Subject: embedded python - mpatrol output Message-ID: <dbeccbeb.0405190633.67817664@posting.google.com> Hi Further to my earlier post we're getting the following output when embedding a python application in C++ If there is any obvious cause please let us know. The version of python is 2.2.1 Regards ERROR: [RNGOVF]: memcpy: range [0x017B8540,0x017B8AA7] overflows [0x017B8540,0x017B8A18] 0x017B8540 (1241 bytes) {malloc:222432:0} [9|-|-|-] 0xFE7CF8D0 __builtin_new+224 0xFE7CF9C4 __builtin_vec_new+12 0xF1AB6B3C ??? 0xF1AB8868 ??? 0xFE8FD4D4 PyCFunction_Call+372 0xFE8B236C eval_frame+14048 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8B66E8 fast_function+88 0xFE8B2474 eval_frame+14312 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8B66E8 fast_function+88 0xFE8B2474 eval_frame+14312 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8B66E8 fast_function+88 0xFE8B2474 eval_frame+14312 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8E20F4 function_call+332 0xFE8A7C5C PyObject_Call+52 0xFE8BD460 instancemethod_call+532 0xFE8A7C5C PyObject_Call+52 0xFE8B4914 PyEval_CallObjectWithKeywords+284 0xFE8B8280 PyInstance_New+352 0xFE8A7C5C PyObject_Call+52 0xFE8B678C do_call+156 0xFE8B248C eval_frame+14336 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8B66E8 fast_function+88 0xFE8B2474 eval_frame+14312 0xFE8B3C14 PyEval_EvalCodeEx+2472 0xFE8E20F4 function_call+332 0xFE8A7C5C PyObject_Call+52 0xFE8B4914 PyEval_CallObjectWithKeywords+284 0xFE8A7CE0 PyObject_CallObject+20 0xFEA86A30 run__13PythonContextPcPPcT1T1+5520 0xFEA84B64 run__13PythonContextRCQ42ie3iel6engine7MessageRQ42ie3iel6engine7MessagePcT3+372 0xFEA7F574 run__9IelPythonGQ42ie3iel6engine7MessageRQ42ie3iel6engine7MessagePcT3+708 0xFAF3A2EC ??? 0xFEA9735C sendMsg__Q42ie3iel6engine6RouterRQ42ie3iel6engine7MessageT1RCQ24_STLt12basic_string3ZwZQ24_STLt11char_traits1ZwZQ24_STLt9allocator1ZwN23GQ42ie3iel6engine24TransporterInterface_var+14132 0xFEADA4AC send__21TransporterInterfaceIRCQ42ie3iel6engine15IelUnicodeChars+12060 0xFEAD5DCC send_skel__Q46POA_ie3iel6engine20TransporterInterfaceR17TAO_ServerRequestPvT2R17CORBA_Environment+328 0xFF230834 synchronous_upcall_dispatch__15TAO_ServantBaseR17TAO_ServerRequestPvT2R17CORBA_Environment+336 0xFEAD7158 _dispatch__Q46POA_ie3iel6engine20TransporterInterfaceR17TAO_ServerRequestPvR17CORBA_Environment+48 0xFF23DF10 dispatch__30TAO_Default_Servant_DispatcherRQ218TAO_Object_Adapter14Servant_UpcallR17TAO_ServerRequestR17CORBA_Environment+44 0xFF225C08 dispatch__18TAO_Object_AdapterR13TAO_ObjectKeyR17TAO_ServerRequestG16CORBA_Object_outR17CORBA_Environment+316 0xFEE89384 dispatch__20TAO_Adapter_RegistryR13TAO_ObjectKeyR17TAO_ServerRequestG16CORBA_Object_outR17CORBA_Environment+92 0xFEEBABC4 process_request__21TAO_GIOP_Message_BaseP13TAO_TransportR12TAO_InputCDRR13TAO_OutputCDR+304 0xFEEBA53C process_request_message__21TAO_GIOP_Message_BaseP13TAO_TransportP15TAO_Queued_Data+428 0xFEDA4C38 process_parsed_messages__13TAO_TransportP15TAO_Queued_DataR17TAO_Resume_Handle+228 0xFEDA44FC consolidate_message__13TAO_TransportR17ACE_Message_BlockiR17TAO_Resume_HandleP14ACE_Time_Value+1276 0xFEDA6908 parse_consolidate_messages__13TAO_TransportR17ACE_Message_BlockR17TAO_Resume_HandleP14ACE_Time_Value+120 0xFEDA3C44 handle_input_i__13TAO_TransportR17TAO_Resume_HandleP14ACE_Time_Valuei+708 0xFEDB9D18 handle_input__27TAO_IIOP_Connection_Handleri+336 0xFE1E6E84 dispatch_socket_event__14ACE_TP_ReactorR20ACE_EH_Dispatch_Info+132 0xFE1E6240 handle_socket_events__14ACE_TP_ReactorRiR18ACE_TP_Token_Guard+176 0xFE1E6D10 dispatch_i__14ACE_TP_ReactorP14ACE_Time_ValueR18ACE_TP_Token_Guard+160 0xFE1E5A20 handle_events__14ACE_TP_ReactorP14ACE_Time_Value+572 0xFE265854 handle_events__11ACE_ReactorP14ACE_Time_Value+48 0xFEE50D5C run__12TAO_ORB_CoreP14ACE_Time_ValueiR17CORBA_Environment+504 0xFEDFA4E4 run__9CORBA_ORBP14ACE_Time_ValueR17CORBA_Environment+36 0xFEDFA49C run__9CORBA_ORBR17CORBA_Environment+20 0xFEAE9F60 svc__10ThreadPool+408 0xFE21A220 svc_run__13ACE_Task_BasePv+224 0xFE1D7A74 invoke_i__18ACE_Thread_Adapter+100 0xFE1D79D0 invoke__18ACE_Thread_Adapter+108 0xFE1A5F98 ace_thread_adapter+24 0xFEBE57BC _lwp_start+8 From aahz at pythoncraft.com Sat May 15 14:55:17 2004 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2004 14:55:17 -0400 Subject: Test error with Python 2.3.4c1 References: <m2fza1h6ka.fsf@pchoel.psh> Message-ID: <c85p2l$4df$1@panix3.panix.com> In article <m2fza1h6ka.fsf at pchoel.psh>, Berthold H?llmann <bhoel at web.de> wrote: > >The error desribed in SF error report No. 870120 (segmentation fault >in test_re) still persists for me in 2.3.4c1. Is there a patch for it? Bugfix releases are mostly low-effort collections of patches that already exist -- there's not much attempt made to call for new patches before the release goes out. All that bugfix release candidates are intended to do is make sure that no new bugs have been created. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From Chris.Hornberger at blackrock.com Wed May 12 10:36:45 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 10:36:45 -0400 Subject: getting the index while iterating through a list Message-ID: <ABADC7F2A1794A4C94657344DC1050930648BB2C@BRDEL-EXCH02.na.blkint.com> As long as you need the index and the element, wouldn't it just be better to iterate the list by the index? for i in range( len( list ) ): print "index: %d" % d print "Element: %s " % list[i] ? -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Fernando Rodr?guez Sent: Wednesday, May 12, 2004 10:01 AM To: python-list at python.org Subject: getting the index while iterating through a list Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Thanks -- http://mail.python.org/mailman/listinfo/python-list From miki.tebeka at zoran.com Sun May 23 05:58:09 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 23 May 2004 11:58:09 +0200 Subject: how to terminate a process? In-Reply-To: <01fe01c43f02$ea28bf80$7f00a8c0@scl01.siliconcreation.com> References: <01fe01c43f02$ea28bf80$7f00a8c0@scl01.siliconcreation.com> Message-ID: <20040523095809.GF1916@zoran.com> Hello Wong, > I am developing two app on Windows, one is a GUI using wxPython and > the other is like a daemon process. The GUI app will have a start/stop > button to control the excution of the daemon. While I know how to use > os.popen2() to start my daemon, I can't figure out a way to stop it > 'nicely'... Is there anything that I can do? You can catch signals on your daemon process and either hack some win32 code (using PostMessage I think) to send signal, or you can use pskill from sysinternall or cygwins kill to send signals. HTH. -- ------------------------------------------------------------------------- Miki Tebeka <miki.tebeka at zoran.com> http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From andrew-pythonlist at puzzling.org Thu May 6 02:54:56 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 6 May 2004 16:54:56 +1000 Subject: What does 'is' do? In-Reply-To: <4099de7e$0$4321$5a62ac22@freenews.iinet.net.au> References: <4099de7e$0$4321$5a62ac22@freenews.iinet.net.au> Message-ID: <20040506065456.GH24284@frobozz> On Thu, May 06, 2004 at 02:44:08PM +0800, Derek Fountain wrote: > I recently saw a use of 'is' in a piece of Python code. I was trying to find > out what it does. I can't find it in the online docs. I have the "Python in > a Nutshell" book and that mentions it as a keyword, but I can't find a > description of it in there either. It's not in the index. > > Can someone tell me where to look? How about the Language Reference Manual? http://docs.python.org/ref/ If you look in the index, you'll find "is operator" there, which links to: http://docs.python.org/ref/comparisons.html#l2h-432 -Andrew. From pxlpluker at cfl.rr.com Sat May 15 10:06:31 2004 From: pxlpluker at cfl.rr.com (pxlpluker) Date: Sat, 15 May 2004 10:06:31 -0400 Subject: web security question. Message-ID: <40A623E7.50807@cfl.rr.com> I have a friend that was using formmail.pl until last weekend when it was hacked by spammers with a buffer overflow attack on one of the form fields. I don't know enough about perl to know how/where the overflow happened. I do have a raw copy of the data the spammer was using, he was putting about 40k into a form field to break the script. I am guessing it broke the script on the regex checking for valid emails or before. My question is, is python open to such attacks and how to prevent it. I am working on a web program that will have a email address and will send an email/s. would a buffer overflow attack work against python cgi ? fred From sross at connectmail.carleton.ca Mon May 10 23:09:20 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Mon, 10 May 2004 23:09:20 -0400 Subject: nested for loop References: <4629559b.0405101330.286ddb32@posting.google.com> <VDWnc.21679$FH5.581779@news20.bellglobal.com> Message-ID: <CvXnc.22342$FH5.608956@news20.bellglobal.com> "Sean Ross" <sross at connectmail.carleton.ca> wrote in message news:VDWnc.21679$FH5.581779 at news20.bellglobal.com... [snip] > # slightly modified code from > http://twistedmatrix.com/wiki/python/PostYourCode > def sequences(n, things): > "generates sequences of n items from a set of things" > if n == 0: > yield [] > else: > for x in things: > for y in sequences(n-1, things): > yield [x] + y > > def nXn_matrices(n, elements): > "generates nXn matrices from elements" > for s in sequences(n*n, elements): > yield [s[i*n:(i+1)*n] for i in xrange(n)] [snip] > [I] believe there are several opportunities for optimization both in the > code and in the algorithm (for instance, it may be possible to take > advantage of repetition in the sub-matrices), but I won't be trying that > now. Looks like I'll be trying it now after all: def nXn_matrices2(n, elements): for m in sequences(n, list(sequences(n, elements))): yield m This is slightly faster than the first version, but it has more overhead since it builds a list of the submatrices. That could be problem. It can probably be avoided, but I haven't figured out how to do it just yet. We'll see what happens. Sean From fgeiger at datec.at Sat May 15 11:36:04 2004 From: fgeiger at datec.at (F. GEIGER) Date: Sat, 15 May 2004 17:36:04 +0200 Subject: Guess My Number Game References: <u9ppc.5447$gr.390828@attbi_s52> Message-ID: <c85de4$slc$1@newshispeed.ch> *Many* years ago I owned a TI 58C pocket calculator (anyone remember these?). It had the game you speak about built into its rom. It used bisection: You had to choose a number and than tell the computer if the number it guessed was less than or greater than or equal the one you had chosen. Cheers Franz GEIGER "EAS" <eriksp at attbi.nospam.com> schrieb im Newsbeitrag news:u9ppc.5447$gr.390828 at attbi_s52... > Hey, I'm new to python (and programming in general) so I'll prolly be around > here a lot... > > Anyways, I've found out how to make a "guess my number game" where the > player guesses a number between 1 and 100, but I want to switch things > around. I want to be able to put in my own number and have the computer > guess it. I already know how to make it guess (by using randrange) but I'm > having a hard time making it smarter. (Like guessing higher or lower based > on what it's told it needs to do.) Here's the code I have right now: > > __________________________________________________________ > > > import random > > guess = 0 > tries = 0 > number = input("Pick a number between 1 and 100 for the computer to guess: > ") > > while number > 100 or number < 1: > number = input("Pick a number between 1 and 100 for the computer to guess: > ") > > while guess != number: > guess = random.randrange(101) > print "The computer guessed", guess > tries += 1 > past = guess > while guess < number: > guess = random.randrange(guess, 101) > print "The computer guessed", guess > tries += 1 > while guess > number: > guess = random.randrange(0, guess) > print "The computer guessed", guess > tries += 1 > > print "The computer guessed your number after", tries, "tries." > > raw_input("Press enter to exit.") > > ____________________________________________________________ > > > As you can see, I've already made it a little smarter but I think I could > still mae it better. Any ideas? > > Also, does anyone know a really popular python forum? > > From Scott.Daniels at Acm.Org Sun May 16 22:34:23 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 16 May 2004 19:34:23 -0700 Subject: Python for Large Projects In-Reply-To: <10afh4b6li9e33d@corp.supernews.com> References: <10ae406ck3q1gb1@corp.supernews.com> <DL6dndD3f71g8jrdRVn_iw@powergate.ca> <10afh4b6li9e33d@corp.supernews.com> Message-ID: <40a829c7@nntp0.pdx.net> Ixokai wrote: > "Peter Hansen" <peter at engcorp.com> wrote: >>Ixokai wrote: >>>There is some concern that if we do this same thing with Python, >>>the performance hit of loading an interpreted environment over >>>the shared filesystem will be prohibitive. Some basic testing >>>has made this seem to be the case. >> >>Just focusing on this one point: it doesn't make sense to me that >>this would be the case, and in my experience it is not.... > > These are GUI programs and we've decided to use wxPython, so that > may be adding to it. I will do more testing to see if it was just > a fluke the last time I tried it out. It might have been :) One thing to investigate is file openings. If you combine all of python (and in your case wxPython's) .pyc files into a single zip wish an actual directory structure matching the packages you want to use, you will only have to open the zip file once, rather than pull each module in in several file operations. -- -Scott David Daniels Scott.Daniels at Acm.Org From greg at cosc.canterbury.ac.nz Wed May 12 00:02:10 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 12 May 2004 16:02:10 +1200 Subject: Cash Register In-Reply-To: <d1bd056c.0405111032.3b2c411f@posting.google.com> References: <d1bd056c.0405111032.3b2c411f@posting.google.com> Message-ID: <2gdlu5F1kmmvU1@uni-berlin.de> Ryan Q. wrote: > It works, i'm just posting it hoping someone could do better. > > print '' > print ' *** CASH REGISTER ***' > print ' PRESS 0 AND THEN ENTER TO TOTAL' I notice it's nicely agnostic about what kind of numbers are used. This will come in very handy if complex currency is ever introduced... ITEM $ 3.50 ITEM $ 2.30j ITEM $ 1+2j ITEM $ 0 TOTAL $ (4.5+4.3j) CASH $ 50 CHANGE $ (45.5-4.3j) TOTAL SLAES $ (4.5+4.3j) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From deetsNOSPAM at web.de Thu May 6 06:38:28 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 06 May 2004 12:38:28 +0200 Subject: rectangle layout algorithm? References: <409a0c8d$0$31702$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <2fuiugF2gnpeU1@uni-berlin.de> Richard Taylor wrote: > I need an algorithm to layout a collection of rectangles (images) within a > bounding rectangle (sheet of paper). > > I feel sure that I am not the first person faced with this problem :-) That smells like a 2d-instance of the knapsack-problem, also called cuttingstock-problem - which is np-hard. In other words: There is no such thing like a general solution to this. Some links I found: http://www.inf.uos.de/papers_html/or_94/cutpaper.html Maybe someone implemented a heuristic solvor for this in python - go google for it :) -- Regards, Diez B. Roggisch From htx1 at gmx.de Wed May 26 16:23:43 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Wed, 26 May 2004 22:23:43 +0200 Subject: Changing file names In-Reply-To: <b4a8ffb6.0405261213.33b823ce@posting.google.com> References: <b4a8ffb6.0405261213.33b823ce@posting.google.com> Message-ID: <c92ud9$nhq$05$1@news.t-online.com> Thomas Philips wrote: > How then can I change the existing filenames to these new filenames? > What python functions should I be using, and what modules are they > contained in? http://docs.python.org/lib/os-file-dir.html See "rename", obviously. Holger From rtrocca_NO_SPAM_ at divitech.it Wed May 19 03:27:17 2004 From: rtrocca_NO_SPAM_ at divitech.it (Riccardo) Date: Wed, 19 May 2004 09:27:17 +0200 Subject: pyVideoIO source release In-Reply-To: <FOidnSjClJ2UvDfdRVn-sw@powergate.ca> References: <2gugfoF6p9rhU1@uni-berlin.de> <FOidnSjClJ2UvDfdRVn-sw@powergate.ca> Message-ID: <2h0gi0F7lbn2U1@uni-berlin.de> Peter Hansen wrote: > Riccardo wrote: > >> Hello, after a long time I'm releasing my extension to read AVI files, >> QuickTime and connect to WebCameras under win32. >> I do not have much time to create a decent website by now, therefore I >> released the sources and a binary for python 2.3 just to be prompted >> to do more. >> If somebody will find this useful I'll add any contribution I receive. >> >> the URL is: >> >> www.geocities.com/rtrocca/python >> >> Well, sorry for the lack of more information, >> I'll add docs and other stuff in the future. > > > You should probably add a copy of the LGPL to the source package... > the source files say they are LGPL'ed, and suggest that one should > contact the "Free Foundation, Inc." (sic) if a copy of the license > is not included... > > -Peter Thanks I'll do that ASAP! It is the first time I try to distribute something! Riccardo From eaw at connact.com Tue May 18 16:42:54 2004 From: eaw at connact.com (Eric Woudenberg) Date: 18 May 2004 13:42:54 -0700 Subject: Have added ulaw handling to wave.py -- whom to give it to? Message-ID: <67032014.0405181242.20fc7d8f@posting.google.com> Hi, I've made small changes to the Python 2.2 wave module to allow .wav files with ulaw content to be read and written. I'm wondering how to give it back to the Python community, is this something for this newsgroup, or Python-Dev perhaps? Thanks, Eric Woudenberg From kbass at midsouth.rr.com Sun May 30 16:49:59 2004 From: kbass at midsouth.rr.com (kbass) Date: Sun, 30 May 2004 20:49:59 GMT Subject: OT: Python in a Nutshell Message-ID: <XNruc.1996$gO4.546@fe1.columbus.rr.com> Does anyone have an idea when the next release of the book, ' Python in a Nutshell' will come out? I am looking for reference material that covers Python 2.3 other than the online documentation. I also notice that Amazon and other book outlets have cut the price on this book so I am hoping that this is an indication that another book is coming out soon. Your thoughts. Thanks! kbass From leoel at gmx.at Wed May 26 08:39:16 2004 From: leoel at gmx.at (Leopold Schwinger) Date: Wed, 26 May 2004 14:39:16 +0200 Subject: Some Newbie Questions In-Reply-To: <O_%sc.73765$Qc.2984729@twister1.libero.it> References: <40b47710@e-post.inode.at> <O_%sc.73765$Qc.2984729@twister1.libero.it> Message-ID: <40b48f2f$1@e-post.inode.at> Matteo Dell'Amico wrote: > Leopold Schwinger wrote: > >> (1) Is there any operator in Python in order to call a Member-Function >> from a class without creating an instance of the class? (In C++ and >> PHP there ist this operator "::" <class>::<memberfunction>) > > > Just call it. :-) > > When you are using methods from instances, the first argument (the one > that is usually called "self") is automagically bound to the instance. > When you access it from the class, this won't happen (and the method, in > this case, is called "unbound"). > > For instance: > >>> class A(object): > ... def foo(self): > ... print self > ... > >>> a = A() > >>> a.foo() > <__main__.A object at 0x401f7d6c> > >>> A.foo(a) > <__main__.A object at 0x401f7d6c> > >>> A.foo > <unbound method A.foo> > >>> a.foo > <bound method A.foo of <__main__.A object at 0x401f7d6c>> > > You have an interactive prompt, try playing with it! :-) > >> (2) Is there any way to dynamically import modules, where the name of >> the module is not known during implementation but can be defined durch >> scipt execution? Think of lots of different config-Files, which differ >> by Path & Name but the variables are all named equal, and i want to >> import a special config-File during the execution of the script. > > > You can use the __import__ built-in. For your problem, look at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/283531 . > >> (3) Is there any way to obtain a kind of "trace"-Info (the actual >> filename and codeline) in order to provide some debug-Info in the case >> of errors (In C++ and PHP there are these "__line__" and "__file__" >> functions, For Python I have only found <Class>.__dict__ and >> dir(<Class>)) > > > traceback module. Keep the Library Reference under your pillow! :-) > Thank you for your anwsers, i will play around a bit... From davidf at sjsoft.com Fri May 28 07:57:54 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 28 May 2004 13:57:54 +0200 Subject: preftree 0.3 released Message-ID: <40B72942.8060200@sjsoft.com> Following up on a promise in the Config discussion ... preftree has been released under the Python license. You can get version 0.3 from http://davidf.sjsoft.com/files/preftree-0.3.tar.gz The README is below... any questions or feedback welcome, a more well packaged release can be done later. David prefstree README prefstree is a simple python package for managing application preferences. Overview -------- - prefs are stored in a text format - prefs are in a hierarchical tree - you can parse this tree, and get a object tree out of it - the modified tree can be stored back into the file - we try to make it pythonic... Hello Prefs ----------- Given the prefs file hello.prefs: hello: firstrun = 1 greet = "world" the code: from preftree import prefs helloprefs = prefs.PrefsParser() helloprefs.parse(open('hello.prefs', 'r')) print "Hello %d" % helloprefs.hello.greet helloprefs.hello.firstrun = 0 open('hello.prefs', 'w').write(helloprefs.getsource()) pref file format ---------------- this is an attempt to be python pref names are "." separated you can use them straight: a.b.c = "hello" a.b.d = "goodbye" f.g = "someone" or you can declare a node and indent children a.b: c = "hello" d = "goodbye" f.g = "someone" you can also make a value/node based on another value/node: a.q = a.b: c = "yes" e = f.g this will result in the following values: a.b.c = "hello" a.b.d = "goodbye" a.q.c = "yes" a.q.d = "goodbye" a.q.e = "someone" f.g = "someone" saving back to a file attempts to preserve sensibility and human readability without modifying unmodified prefs From __peter__ at web.de Fri May 7 05:17:50 2004 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 May 2004 11:17:50 +0200 Subject: A simple xml.dom.minidom question References: <c7dbc8$i4l$1@sunnews.cern.ch> <409ab05f$0$24803$9b622d9e@news.freenet.de> <c7fhhn$548$1@sunnews.cern.ch> Message-ID: <c7fk7u$67n$06$1@news.t-online.com> Paulo Pinto wrote: > There are a set of applications that use XML files > as their configuration mechanism. Inside these files > there is some data that isn't standard XML but it in > form expected by the tools. > > For example > > <values> > "value1" "value2" > </values> > > Now, if I use writexml(), I get the following, > > <values> > "value1" "value2" > </values> > > Which I understand, because it is how it should be > in standard XML. > > However I am really required to use the first form. Maybe you can get away with a tiny hack: import xml.dom.minidom as md import cStringIO def wd(writer, data): data = data.replace("&", "&").replace("<", "<") writer.write(data) md._write_data = wd d = md.parseString("""<values>"v1" "v2"</values>""") s = cStringIO.StringIO() d.writexml(s) print s.getvalue() Peter From dns-dbm at EU.org Sat May 1 12:25:58 2004 From: dns-dbm at EU.org (DNS database subsystem) Date: Sat, 1 May 2004 18:25:58 +0200 (CEST) Subject: (no subject) Message-ID: <20040501162558.D350028B81@ns.eu.org> Your e-mail: > From: python-list at python.org > Subject: 0i09u5rug08r89589gjrg > Date: Sat, 1 May 2004 18:24:49 +0200 > Msg-Id: <20040501162546.5273C28B47 at ns.eu.org> has been processed by the automatic update procedure at the FREENIC NCC. Diagnostic output follows: ------------------------------------------------------------------------ Update FAILED: [] content-type: text/plain; *ERROR*: Unknown object type Update FAILED: [] content-transfer-encoding: 7bit *ERROR*: Unknown object type Update FAILED: [] content-type: application/octet-stream; *ERROR*: Unknown object type Update FAILED: [] content-transfer-encoding: base64 content-disposition: attachment; *ERROR*: Unknown object type Objects that just generated a WARNING have been updated as shown. Objects that generated an *ERROR* have NOT been updated as requested. Please re-submit corrected objects. ------------------------------------------------------------------------ Please use <auto-dbm at eu.org> instead of <dbmaster at eu.org> and <auto-assign at eu.org> instead of <assign at eu.org> for fast turnaround times on all but guarded objects. If you have any question about an error or warning message, please contact <dbmaster at eu.org>. Sincerely Yours, Latest and Greatest FREENIC Database Maintenance Department (Automatic Section) From Scott.Daniels at Acm.Org Sun May 2 08:59:53 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 May 2004 05:59:53 -0700 Subject: quotes at the edges of a triple quote string... In-Reply-To: <P8Qkc.312754$Pk3.46254@pd7tw1no> References: <aZPkc.332518$oR5.17959@pd7tw3no> <5eednTy2_ZjVUA7dRVn-uw@powergate.ca> <P8Qkc.312754$Pk3.46254@pd7tw1no> Message-ID: <4094f63f$1@nntp0.pdx.net> Anthony Roberts wrote (looking to fix): >>> prop = re.compile("""(?P<name>[a-z0-9_\-]+)="(?P<value>.*?)""""re.I) > Peter Hansen wrote: >> Can't you still use a triple-quoted string, but escape the >> last quote? >> >>> """test\"""" > Yes... yes I can. I can also use the other quotetation marks. I realized > this just after I posted. > > >>> '''test"''' > 'test"' A couple of things to realize (esp if you are getting into longer regexps). 1) r"""abc""" is a raw string with a triple quote. 2) Also, 'abc' 'def' (string splicing) is _exactly_ the same as 'abcdef' The separate strings are glued together when converting the code to bytecode, so there is no cost of concatenation to worry about. What you might use for a regexp, then might be: prop = re.compile(r"(?P<name>[a-z0-9_\-]+)=" r'"(?P<value>.*?)"') The argument parens are enough for grouping, and the expression broken at appropriate points is arguably more readable. -Scott From P at draigBrady.com Thu May 20 08:03:58 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 20 May 2004 13:03:58 +0100 Subject: Using pygtk and glade2 In-Reply-To: <ec6dce8b.0405191832.71c09ec7@posting.google.com> References: <ec6dce8b.0405191832.71c09ec7@posting.google.com> Message-ID: <40AC9EAE.4020905@draigBrady.com> j_mckitrick wrote: > I am having a problem with combo boxes. If I am using an XML glade2 > file for my gui definition, what is the command I need to use to > access a given combo box and determine the currently selected item? > > jonathon That's easy: text = combo.entry.get_text() More info here: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq14.008.htp Getting the selected item in an option menu is much more difficult: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq16.004.htp Examples are always good: http://www.pixelbeat.org/talks/pygtk/ P?draig. From donn at drizzle.com Thu May 13 23:10:51 2004 From: donn at drizzle.com (Donn Cave) Date: Fri, 14 May 2004 03:10:51 -0000 Subject: Stackless python and microthreads References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <osGdnfGC2oRcsTndRVn-tw@powergate.ca> Message-ID: <1084504249.836501@yasure> Quoth Peter Hansen <peter at engcorp.com>: | Mike C. Fletcher wrote: | | > continuations are the most awesome toys | > you can imagine... we will all mourn their passing in time... | | Will that be _before_, or _after_ we understand what they are? ;-) I gave them a try, and I mourn them with a touch of relief, I guess. I'm the guy who won't bother to learn list comprehensions and generally despises cool gimmicks, but continuations were more than just cool, they were terribly powerful. I hooked them into a graphics toolkit wrapper with an event dispatching model where each window, network connection etc., ran in its own native thread. No blocking, always ready to respond to a new message. When a couple of these threads have to interact, they would queue messages back and forth, and the programming paradigm can get awkward - a lot of state can pile up as everyone's trying to keep track of their progress through some kind of procedure. Well, suppose you send your message and save the whole function state somewhere, and return to the dispatcher. When the response comes back, you pick up the function state and continue it, feeding the response in. Now instead of a tedious kind of state machine, you're writing an plain, ordinary function that sends messages to its peer and looks at the response, as though that were all synchronous, and it's so much simpler. Yet the execution underneath that isn't synchronous at all, because your computation is suspended in between your send and the response. It really does return every time it sends a message, it just starts up next time where it left off. Of course it's hairy, too. That's where the relief comes in. I'll never be able to use continuations ... but then, I'll never have to deal with anyone else's code that uses them. Donn Cave, donn at drizzle.com From heikowu at ceosg.de Sat May 15 09:58:22 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 15 May 2004 15:58:22 +0200 Subject: Guess My Number Game In-Reply-To: <u9ppc.5447$gr.390828@attbi_s52> References: <u9ppc.5447$gr.390828@attbi_s52> Message-ID: <200405151558.22793.heikowu@ceosg.de> Am Samstag, 15. Mai 2004 15:44 schrieb EAS: > Anyways, I've found out how to make a "guess my number game" where the > player guesses a number between 1 and 100, but I want to switch things > around. I want to be able to put in my own number and have the computer > guess it. I already know how to make it guess (by using randrange) but I'm > having a hard time making it smarter. (Like guessing higher or lower based > on what it's told it needs to do.) Here's the code I have right now: On average, the shortest possible runtime (and also a deterministic runtime of O(log2(high-low))) will be achieved if you use interval walking. Thus: number = 64 low = 1 high = 100 while low <> high: med = (low+high)//2 tries += 1 if med == number: print "I guessed your number:", med elif med < number: if med == low: print "I guessed your number:", med+1 low = med+1 else: low = med else: high = med print "I needed", tries, "tries." HTH! Heiko. From donn at drizzle.com Thu May 13 02:08:11 2004 From: donn at drizzle.com (Donn Cave) Date: Thu, 13 May 2004 06:08:11 -0000 Subject: if Request("something") == None: doesn't work References: <AVsoc.47661$FI7.6868@newssvr29.news.prodigy.com> <Ogzoc.47746$AQ2.5767@newssvr29.news.prodigy.com> Message-ID: <1084428488.897136@yasure> Quoth "Sam Sungshik Kong" <ssk at chol.nospam.net>: ... | When there's no argument in the request, | | Request("id") == None returns False | if Request("id"): returns True | str(Request("id")) returns "None" | repr(Request("id")) returns <COMObject<unknown>> | | So my conclusion is that Request("id") is not None. | It's an object, str() of which is accidentally "None". | That confused me. It would confuse anyone. That's pretty bad. Donn Cave, donn at drizzle.com From wilkSPAM at OUTflibuste.net Tue May 11 04:37:06 2004 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Tue, 11 May 2004 10:37:06 +0200 Subject: how robust is (CGIHTTPServer ) References: <mailman.369.1084064582.25742.python-list@python.org> <87n04hlgjd.fsf@blakie.riol> <mailman.376.1084126948.25742.python-list@python.org> Message-ID: <87n04ffjgt.fsf@blakie.riol> pxlpluker <pxlpluker at cfl.rr.com> writes: > Wilk wrote: > >>pxlpluker <pxlpluker at cfl.rr.com> writes: >> >> >> >>> i was looking at twisted but it appears to be WAY beyond my megar >>>skills at this point. >>>so i think CGIHTTPServer will fit my needs if it is pretty stable. >>>I have a small python cgi that i was building and i had this great >>>idea of having the cgi server kinda rolled into it for various >>>portability reasons and maybe some future features that would not have >>>apache to realy on. >>> >>> >> >>If you want to have your own server, you don't need CGI, you can start >>from BaseHTTPServer, it's very robust. I use it in production. >>CGIHTTPServer and SimpleHTTPServer are good examples to show how to >>expand BaseHTTPServer. >> >> > I think i need cgi to run python scripts though. I am allowing file > upload with some user management/accounts. Everything you can do with cgi can be done without... > What kind of traffic does your site get? It's web-applications in intranet with database. There is one, for example, used in a factory, 24h/24 since two years. -- Wilk - http://flibuste.net From Mark.Puchalski at Honigman.com Tue May 25 09:06:43 2004 From: Mark.Puchalski at Honigman.com (Puchalski, Mark) Date: Tue, 25 May 2004 09:06:43 -0400 Subject: Newbie Question Message-ID: <0B9E60AF5E0F1240BA6F635F25ACCE5C03316D56@01EXCVS1.honigman.local> I have a script that I need to do the following: Taking a user id that is in the format 'userid at MACAddress' <mailto:'userid at MACAddress'> , read the userid portion (varying length) and concatenate with @honigman.com. I'm not sure how to make this happen. Suggestions? Thanks. ------------------------------------------------------------------------ ------ Mark A. Puchalski Network Engineer Honigman Miller Schwartz and Cohn LLP Tel 313.465.7167 Fax 313.465.8267 ********************************************************************* Confidential: This electronic message and all contents contain information from the law firm of Honigman Miller Schwartz and Cohn LLP which may be privileged, confidential or otherwise protected from disclosure. The information is intended to be for the addressee only. If you are not the addressee, any disclosure, copy, distribution or use of the contents of this message is prohibited. If you have received this electronic message in error, please notify us immediately (313.465.7000) and destroy the original message and all copies. ********************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040525/73234982/attachment.html> From richardjones at optushome.com.au Wed May 5 20:39:06 2004 From: richardjones at optushome.com.au (richard) Date: Thu, 06 May 2004 10:39:06 +1000 Subject: MySQL vrs SQLite References: <mailman.283.1083787205.25742.python-list@python.org> <slrnc9is2h.8mg.ramen@lackingtalent.com> <uisi90lvd03em0vlta9pl59n2m7qs3t2h4@4ax.com> Message-ID: <4099892a$0$32558$afc38c87@news.optusnet.com.au> Alan Gauld wrote: > On Wed, 05 May 2004 22:41:35 -0000, Dave Benjamin > <ramen at lackingtalent.com> wrote: >> In article <mailman.283.1083787205.25742.python-list at python.org>, Michael >> wrote: >> > I'm considering changing a Python program of mine, that uses MySQL as >> > it's db backend, to use SQLite. .... Any draw backs to making this >> > change? > > No direct experience but doesn't SQLite store its data in memory? No, you're thinking of gadfly :) Richard From NAIGIMSESRIMAIL at gims.com Sat May 15 19:11:43 2004 From: NAIGIMSESRIMAIL at gims.com (GroupShield for Exchange (ESRIMAIL)) Date: Sun, 16 May 2004 01:11:43 +0200 Subject: ALERT - GroupShield ticket number OB20_1084662694_ESRIMAIL_3 was generated Message-ID: <B06B8FEF47ACD7119E720040F42845910322A2EE@ESRIMAIL> Action Taken: The message was blocked because of its subject. To: python-list at python.org <python-list at python.org> From: aahz at pythoncraft.com <aahz at pythoncraft.com> Sent: -140759680,29637329 Subject: Re: Test error with Python 2.3.4c1 Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1817 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20040516/d63f1828/attachment.bin> From opengeometry at yahoo.ca Sun May 2 01:17:05 2004 From: opengeometry at yahoo.ca (William Park) Date: 2 May 2004 05:17:05 GMT Subject: Efficient string concatenation methods References: <b3a34c4c.0405011643.70c163c3@posting.google.com> Message-ID: <c7208g$g44o5$1@ID-99293.news.uni-berlin.de> Oliver Crow <ocrow at skymind.com> wrote: > As a realtive python newb, but an old hack in general, I've been > interested in the impact of having string objects (and other > primitives) be immutable. It seems to me that string concatenation is > a rather common operation, and in Python having immutable strings > results in a performance gotcha for anyone not aware of the impact of > doing lots of concatenation in the obvious way. > > I found several sources with advice for how to do concatenation in a > pythonic way (e.g. ref#1), but I hadn't seen any measurements or > comparisons. So, I put together a little test case and ran it through > for six different methods. Here's the results, and my conclusions: > > http://www.skymind.com/~ocrow/python_string/ > > I'd be happy to hear if anyone else has done similar tests and if > there are any other good candidate methods that I missed. > > ref #1: http://manatee.mojam.com/~skip/python/fastpython.html#stringcat > > Oliver Try printing the integers to a file, then read it back. Should be similar to Method 5. -- William Park, Open Geometry Consulting, <opengeometry at yahoo.ca> Linux solution/training/migration, Thin-client From newsgroups at jhrothjr.com Wed May 5 16:55:41 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 May 2004 16:55:41 -0400 Subject: error handling in Python References: <3064b51d.0405050741.43d11aa0@posting.google.com> Message-ID: <109il8ijukg387f@news.supernews.com> <beliavsky at aol.com> wrote in message news:3064b51d.0405050741.43d11aa0 at posting.google.com... > Suppose I have a function > > def read_data(xfile): > # code here to read dates and prices > return dates,prices > > that if successful returns two Numeric arrays, of dates and prices. It looks like you're still thinking in Fortran. It's probably going to be easier all around to return one list of two element tuples. > I am unsure what to return if read_data is unsucessful. Since a > successful function call returns a list of length two, I could return > a list of length one if there is a problem, so that [-1] is returned > if the file does not exist, [-2] if the dates are invalid, etc. After > calling the function, I could check the len of the result to detect > problems. This seems workable but ad-hoc. > I do NOT want to use the try/except idiom to stop the program if there > is a problem reading data. > > In Fortran I would write a subroutine with calling sequence > > call read_data(xfile,dates,prices,ierr) > > where ierr would be checked upon return for nonzero values. The basic question is: what do you want to do with an error? That conditions how you want to handle it. Do you want to print an error message and quit? Print an error message and continue with the next batch? Fake up a return so the rest of the program continues as if nothing was wrong? John Roth From peter at engcorp.com Tue May 11 15:03:13 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 May 2004 15:03:13 -0400 Subject: OT: Idea for Python T-shirt In-Reply-To: <2472a0tgrcv1oc3mbu0ndljogpc5out9da@4ax.com> References: <ppj1a09ee7766t94o439qd2bgbc18resg1@4ax.com> <JpqdnYIeR4GMRT3dRVn-gg@powergate.ca> <2472a0tgrcv1oc3mbu0ndljogpc5out9da@4ax.com> Message-ID: <MLKdnUWt3tvvvjzdRVn-vw@powergate.ca> Christos TZOTZIOY Georgiou wrote: > On Tue, 11 May 2004 09:41:35 -0400, rumours say that Peter Hansen > <peter at engcorp.com> might have written: > > [snip "nibbles exploding with desire"] > > >>Also, I don't get it... > > > Based on the hungarian phrase-book sketch from the Flying Circus... "my > nipples explode with desire!" Yeah, that part was obvious (to an MP fan). But why the bit-eating snake then? It's gratuitous at that point. Oh, wait, were the ones and zeros supposed to be "exploded nibbles"? That's a reach... From grante at visi.com Tue May 25 00:19:49 2004 From: grante at visi.com (Grant Edwards) Date: 25 May 2004 04:19:49 GMT Subject: GTK or TKinter (or what else?) References: <SxZqc.10613$Wc.388888@twister2.libero.it> <J5isc.8231$be.5948@newsread2.news.pas.earthlink.net> <2hfui1Fch1lmU2@uni-berlin.de> Message-ID: <40b2c965$0$8695$a18e6209@newsreader.visi.com> In article <2hfui1Fch1lmU2 at uni-berlin.de>, Greg Ewing wrote: > Greg Krohn wrote: >> You can do this: >> >>> button = wx.Button(parent, -1, "Search") >> >>> button.Bind(EVT_BUTTON, searchFunction) > > It would be nice if the need to pass all those -1s > could be eliminated as well... Been there, whined about that. :) Right now I'm using wax, (a wxWindows wrapper that hides some of that sort of thing). -- Grant Edwards grante Yow! Is there something at I should be DOING with a visi.com GLAZED DONUT?? From its1louder at yahoo.com Thu May 13 19:02:07 2004 From: its1louder at yahoo.com (Tom) Date: 13 May 2004 16:02:07 -0700 Subject: Real-time graphs References: <mailman.463.1084375754.25742.python-list@python.org> Message-ID: <90f2d9db.0405131502.48f34bd@posting.google.com> I do lab instrument programming - moving stages, polling sensors & controlling instruments. My GUIs have lots of visual feedback - live charts, buttons, indicators, meters, gauges. I use wxPython for the GUI framework, python+numeric for lots of the number crunching/analysis, and swig for wrapping hardware drivers/dlls. For the gauge, plot, and button widgets, I use the national instruments "measurement studio" activex objects through wxPython activex hosting. This works well and was very easy - esp. if you use the CVS BOA constructor IDE. Of course it requires that you buy the NI measurement studio for Visual basic. I already had it because I used to use labview/labwindows for this stuff. It will cost you like $800 for just the widgets (no labview) if I recall correctly. There are many other commercial visual basic/activex widget sets for lab instrumentation/process monitoring. Take your pick. Some will be cheaper/faster/better I'm sure. the disadvantage of this approach is that 1) costs money 2) the vendor will probably only offer VB support, not Python 3) windows only. None of these are a problem for me, since most hardware drivers are windows only anyway. Some day some one will make a great lightweight plotting widget that will drop right into wxpython no problem. I might even do this. But it hasn't happened yet. THere are a hundred plotting packages that shoehorn into wxpython - scipy/chaco, NCARgraphics, and a lot more I've tried and forgotten. They are all too slow, too immature, or too much trouble to use. But wxPython works very well with Activex widgets. They look really good, are fast, and the wrapped widget classes are very pythonic to program. <snrkiwi-lists at yahoo.com> wrote in message news:<mailman.463.1084375754.25742.python-list at python.org>... > I've trolled the lists, FAQs, and Net as a whole, but > can't find anything definitive to answer this. > > We're looking for real-time graph capability (bar, > line, etc), so that we can display telemetry from a > robot system. There are a bunch of packages out > there, but many seem to provide only static graphs > (e.g. for scientific, financial data, etc). Does > anyone currently display real-time telemetry using > Python? Can anyone provide any suggestions? > > TIA > Stephen From timh at zute.net Mon May 17 23:59:32 2004 From: timh at zute.net (Tim Hoffman) Date: Tue, 18 May 2004 11:59:32 +0800 Subject: better csv modules and where have object-craft gone? Message-ID: <40a98a20@news.highway1.com.au> Hi I have been using object crafts csv module for quite a few projects, mainly because I found the csv in python in it's current incarnation is funtionally inferior to object crafts. The object craft module for instance allowed you build up csv gradually (ie field at a time rather the python csv module where the writer does the work a record at a time) which isn't always the way I would like to work, also I have always had encoding problems (specifcally it doesn't support unicode as per the docs) everytime I used the python module where as the object craft one always worked out of the box. Only problem is object craft seemed to have disappeared off the face of the net (ie I can't even resolve their name in DNS). Which is a pity as I don't have a current copy for 2.3 (windows) of their csv module. Does anyone have a copy of the object-craft csv module, or does anyone know where they have relocated ? It is a pity if they have disappeared. Rgds Tim From cookedm+news at physics.mcmaster.ca Wed May 12 22:45:40 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 12 May 2004 22:45:40 -0400 Subject: Google and Python usage Message-ID: <qnkk6zhujsb.fsf@arbutus.physics.mcmaster.ca> Everybody says Google uses Python, but I've never seen it... until I came across this, for the Google AdWords support page: https://adwords.google.com/support/bin/topic.py?topic=102 Is that a .py I spy? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From aahz at pythoncraft.com Sat May 22 14:08:27 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2004 14:08:27 -0400 Subject: terminological obscurity References: <L6erc.519686$Pk3.412259@pd7tw1no> Message-ID: <c8o4ur$dkt$1@panix3.panix.com> In article <L6erc.519686$Pk3.412259 at pd7tw1no>, Elaine Jackson <elainejackson7355 at home.com> wrote: > >A question about terminology ('namespace'): > >>>> prince=tuple() >>>> king=[prince] >>>> del prince > >At this point, does the object formerly known as prince belong to >the namespace implemented by globals()? More generally, is there a >terminological way to distinguish between (1) a function from a set of >names into a set of objects, and (2) the aforementioned set of objects? Objects don't have a namespace, only names and attributes do. Names are bound to objects. All objects are global to the entire interpreter (not just within a module by the usual meaning of "global"). It's not clear to me what your (1) and (2) are supposed to refer to. >Is there a handy noun that refers to sameness of identity in the same >way that 'equality' refers to sameness of value? ('Identicalness' is >pretty clumsy, and 'identity' is confusing, since it already has a >meaning that is closely related but needs to be kept distinct.) "Identity" >A question about terminology ('name'): > >Suppose X is a container that contains n items (incidentally, is >'items' the right term?) and i in an integer with 0<=i<=n. Does " X[i] >" count as a 'name'? "Item" or "element" are both correct. X[i] is a target. See the Language Reference, section 6.3. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From della at toglimi.linux.it Fri May 28 06:34:15 2004 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Fri, 28 May 2004 10:34:15 GMT Subject: accessing elements in multi-dimensional sequences In-Reply-To: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> Message-ID: <HAEtc.24609$Wc.846568@twister2.libero.it> Rodrigo Daunaravicius wrote: > Is there an elegant way to directly refer the 2nd dimension of a > multi-dimensional sequence (like the nth character in a list of strings). > An example would be deleting the newline in all the strings from a list > obtained through readlines without recurring to 'for' loops. > I would expect this to work: > > >>>>d > > ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n', > '0922210996\n'] > >>>>del d[:][-1] >>>>d > > ['0891931243', '0325443777', '0933477028', '0699624617', '0922210996'] > > But it doesn't, d remains unchanged. > > Another attempt produced what seemed to me like a counter-intuitive result > > >>>>b=d[:][:-1] >>>>b > > ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n'] > > > Regards from a python newbie, > Rodrigo Daunarovicius You can express that as [s[:-1] for s in d]. Besides, strings are immutable: if s is a string, you can't do something like s[3] = 'a': though, you can create a new object and tell s to refer to it: s = s[:3] + 'a' + s[4:] If all you want to do is remove trailing whitespace, have also a look at the string strip, lstrip and rstrip methods. -- Ciao, Matteo From tim.one at comcast.net Thu May 13 14:10:30 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu, 13 May 2004 14:10:30 -0400 Subject: Python - open forever ? In-Reply-To: <593D8B10B2409E468D3E916CA156C84D0326C930@mail02.ad.telekom.lv> Message-ID: <LNBBLJKPBEHFEDALKOLCMEGPKPAB.tim.one@comcast.net> [Romans Krjukovs] > Our company is going to start use Python widely. > To make this reality we have to include Python in our strategy > plans for at least 3 nearest years. > This would be a green light to our developers to start new projects on > Python. > > At the presentation of Python and its usage posiibilities in our > home environment to the members of the project managers board, > we got such questions: > > - There is a risk that Python can become closed and unsupported in the > future. "closed" and "unsupported" are different issues. The Python Software Foundation (PSF) holds the Python copyright. The PSF is a membership organization, the members elect the Board of Directors, and the Board sets the license. I'm on the Board, and it's simply inconceivable to me that we would even *think* about closing Python. If we did, then (a) the PSF membership would surely vote us out, and elect a new Board to reverse that stupid decision; and, (b) the PSF would be in legal trouble, because the PSF isn't just a non-profit corporation, it's a "public charity" (that's a technical term) under US tax law, and is constrained to act in accord with its charitable purposes. The idea that the PSF would voluntarily close Python is really too silly to worry about. If your company is indeed going to base part of its business on Python, it would be wise to apply for a PSF Sponsor Member position, and then it would have a vote (indirectly, via its vote for Board members) on Python's license too: http://www.python.org/psf/ Worry about involuntary conversion to closed-source (e.g., in case of bankruptcy) is also unfounded. As is the norm for US public charities, the PSF's Articles of Incorporation: http://www.python.org/psf/records/incorporation.html require that assets of the PSF pass to: one or more organizations which themselves are exempt as organizations described in Sections 501(c)(3) and 170(c)(2) of the Internal Revenue Code of 1986, as amended, or corresponding sections of any prior or future law, or to the federal, state, or local government for exclusive public purpose The spirit of all this legal stuff is that the PSF holds the copyright on Python for the benefit of public-interest purposes. It's not allowed to enrich itself (or other legal entities) at the expense of public good. For example, we couldn't sell the Python copryight to Microsoft even if we wanted to. > - Who can guarantee that Python will be usable and available to us if > it is develeped and maintained by the hackers from all over the world > without any obligations and guarantees ? That one is funny <wink>. It's exactly *because* hackers all over the world have the source code, and under a license that allows them to do just about anything with it, that Python support will never vanish. Your managers are surely wary of single-source supplier arrangements in all other areas of your business! Why they think it might be a good thing to get locked into a single supplier for critical software is beyond me, although I realize this odd concern isn't unique to your company. > - How we can minimize such risk ? (Become a member of some club, > buy licenses, support etc.) Support the PSF, join the Python Business Forum: http://www.python-in-business.org/ and, above all, participate in the Python community. What you get with Python is the total of what contributors have given to it. Become contributors yourselves, and your fears will melt away -- you'll see how Python really works then. From klachemin at home.com Thu May 27 00:00:45 2004 From: klachemin at home.com (Kamilche) Date: 26 May 2004 21:00:45 -0700 Subject: Emulating Python Inheritance Manually Message-ID: <889cbba0.0405262000.2c0bc757@posting.google.com> """ Emulating Python inheritance manually. By loading it from disk at run time, you can create new custom types without programmer intervention, and reload them on demand, without breaking anything. The only time programmer intervention is required, is when new functions are added. It works well for data... I can use 'chicken.color' to access that attribute, but not for functions. I can't say 'chicken.printme()', I have to say 'chicken.do('printme') instead. It can look up the function OK, but the 'chicken.print()' isn't passing the 'self' argument to the function, which results in one argument too few being sent to the function. Does anyone have a way around this problem? """ import sys import types master = {} masterbysortid = {} functions = {} __classctr = 0 # Unbound methods def base_print(self, *args): print "# This is a base print function", self def custom_print(self, *args): print "# Hey! Custom print function, unrelated to a class", self def animal_print(self, *args): print "# This is the animal print function", self def horse_print(self, *args): print "# This is the horse print function", self def chicken_print(self, *args): print "# This is the chicken print function", self def animal_speak(self, *args): print "# Generic animal speak:", text def chicken_speak(self, **args): print "# Squawk!", args['text'] # Classes class CreateObject: def __init__(self, args): ' Constructor' if args == None: raise 'Invalid type!' if type(args) != type({}): raise 'Invalid argument!' if not args.has_key('TYPE'): raise 'Missing type!' typename = args['TYPE'] if not master.has_key(typename): raise 'Unknown type ' + typename + '!' self.__dict__.update(args) def do(self, event, **args): fn = getattr(self, event) if callable(fn): fn(self, **args) else: raise "Can't call '" + str(fn) + "'! Make sure it's registered via RegisterFunctions!" def update(self, args): if args == None: raise 'Invalid type!' if type(args) != type({}): raise 'Invalid argument!' self.__dict__.update(args) def data(self): return self.__dict__ def __str__(self): ' Return a printable version of the data' return str(self.__dict__) def printattrs(self, prefix): for key, value in self.__dict__.items(): print prefix, key, value def __getattr__(self, name): ' Look for the data in the inherited type, if it doesnt exist.' # Look for the data in the object instance m = self if m.__dict__.has_key(name): return m.__dict__[name] else: # Look for the data in the object class typename = m.__dict__['TYPE'] m = master[typename] if m.__dict__.has_key(name): return m.__dict__[name] else: # Look for the object in the inherited class typename = m.__dict__['INHERITS'] if typename == None: raise AttributeError, name else: m = master[typename] if m.__dict__.has_key(name): return m.__dict__[name] else: raise AttributeError, name def RegisterType(args): global master global __classctr # Ensure they passed in arguments if args == None: raise 'Invalid type!' # Ensure they passed in a dictionary if type(args) != type({}): raise 'Invalid argument!' # Ensure the dictionary included a 'TYPE' entry if not args.has_key('TYPE'): raise 'Missing type!' # Extract the type typename = args['TYPE'] # Ensure the type doesn't already exist if master.has_key(typename): raise 'Type ' + typename + ' already exists!' if not args.has_key('INHERITS'): # Inherit from BASE, if no supertype specified if typename == 'BASE': inherits = None else: inherits = 'BASE' args['INHERITS'] = inherits else: # Inherit from another type inherits = args['INHERITS'] if not master.has_key(inherits): raise "Can't inherit from invalid type " + inherits + "!" # Replace function names with function pointers for (key, value) in args.items(): if type(value) == type("") and functions.has_key(value): args[key] = functions[value] # Add it to the master master[typename] = None if not inherits: m = {} else: m = master[inherits].data() __classctr += 1 m.update(args) c = CreateObject(m) c.__sortid = __classctr master[typename] = c masterbysortid[__classctr] = typename def RegisterFunctions(args): if args == None: raise 'Invalid type!' if type(args) != type([0]): raise 'Invalid argument!' for f in args: name = f.__name__ if functions.has_key(name): raise 'Function already exists!' functions[name] = f # Testing def Test(): RegisterFunctions([animal_speak, base_print, animal_print, horse_print, chicken_print, chicken_speak]) RegisterType({'TYPE': 'BASE', \ 'NAME': 'Base Object', \ 'printme': 'base_print'}) RegisterType({'TYPE': 'ANIMAL', \ 'NAME': 'Generic Animal', \ 'printme': 'animal_print', \ 'speak': 'animal_speak'}) RegisterType({'TYPE': 'HORSE', \ 'INHERITS': 'ANIMAL', \ 'NAME': 'Horse', \ 'printme': 'horse_print'}) RegisterType({'TYPE': 'CHICKEN', \ 'INHERITS': 'ANIMAL', \ 'name': 'Chicken', \ 'speak': 'chicken_speak', \ 'color': 'white', \ 'printme': 'chicken_print'}) print '#\tFunctions:' for key, value in functions.items(): print '#\t', key, '\t', value print '#\tMaster:' keys = masterbysortid.keys() keys.sort() for key in keys: k = masterbysortid[key] print '#\t', k value = master[k] value.printattrs('#\t\t') obj1 = CreateObject({'TYPE': 'BASE', 'x': 1, 'y': 2}) obj2 = CreateObject({'TYPE': 'BASE', 'x': 1, 'y': 2, 'z': 3, 'printme': custom_print}) chicken = CreateObject({'TYPE': 'CHICKEN', 'name': 'Chicken Little'}) print "# Chicken:", chicken print "# OK, let's see if this works now:" print "# Chicken color:", chicken.color chicken.do('speak', text = "I'm squawking here!") chicken.do('printme') # What I would like to do, is this: # chicken.printme() chicken.do('speak', text = "I would really like to say 'chicken.printme()' instead. Can I?") # Startup routine if __name__ == "__main__": Test() # Sample output # Functions: # chicken_print <function chicken_print at 0x01F005B8> # animal_speak <function animal_speak at 0x00B687C0> # horse_print <function horse_print at 0x01A15100> # base_print <function base_print at 0x02000180> # animal_print <function animal_print at 0x01FB61C8> # chicken_speak <function chicken_speak at 0x01357558> # Master: # BASE # INHERITS BASE # __sortid 1 # NAME Generic Animal # TYPE ANIMAL # printme <function animal_print at 0x01FB61C8> # speak <function animal_speak at 0x00B687C0> # ANIMAL # INHERITS ANIMAL # NAME Horse # color white # printme <function chicken_print at 0x01F005B8> # name Chicken # __sortid 2 # TYPE CHICKEN # speak <function chicken_speak at 0x01357558> # HORSE # INHERITS ANIMAL # __sortid 3 # NAME Horse # TYPE HORSE # printme <function horse_print at 0x01A15100> # speak <function animal_speak at 0x00B687C0> # CHICKEN # INHERITS ANIMAL # __sortid 4 # NAME Horse # color white # TYPE CHICKEN # speak <function chicken_speak at 0x01357558> # printme <function chicken_print at 0x01F005B8> # name Chicken # Chicken: {'TYPE': 'CHICKEN', 'name': 'Chicken Little'} # OK, let's see if this works now: # Chicken color: white # Squawk! I'm squawking here! # This is the chicken print function {'TYPE': 'CHICKEN', 'name': 'Chicken Little'} # Squawk! I would really like to say 'chicken.printme()' instead. Can I? From peter at engcorp.com Mon May 10 19:51:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 May 2004 19:51:00 -0400 Subject: nested for loop In-Reply-To: <4629559b.0405101330.286ddb32@posting.google.com> References: <4629559b.0405101330.286ddb32@posting.google.com> Message-ID: <m8CdnWqFOPX4iD3dRVn-sw@powergate.ca> Wolfgang Buechel wrote: > I want to iterate over all 2x2 matrices with elements in range 0..25 > (crypto-stuff). > > To produce them, first I wrote a fourfold nested for loop: > > M=26 > for a in range(M): > for b in range (M): > for c in range (M): > for d in range (M): > matr = [[a,b],[c,d]] > (dosomething) > > Then I had a look in comp.lang.python and found: > > > for (a,b,c,d) in [(x,y,z,t) for x in range(M) > for y in range(M) > for z in range(M) > for t in range(M)] : > matr = [[a,b],[c,d]] > > Is there a shorter (and probably, with respect to exec time, faster) > way to write such a 4for loop? Hmm... why would you want something shorter, as it would probably be less readable? Also, how fast do you need it to run, or how many times faster than the above would you like it to run? (The second one is a facetious question... the first is more serious. In effect: what's wrong with what you have?) -Peter From peter at engcorp.com Thu May 20 15:45:19 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 15:45:19 -0400 Subject: Documentation/Info on this sign In-Reply-To: <40ACED36.5030706@hotmail.com> References: <c8iims$24i$1@solaris.cc.vt.edu> <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> <40ACED36.5030706@hotmail.com> Message-ID: <uuudneFAtP5NlzDdRVn-uQ@powergate.ca> Bart Nessux wrote: > confirms the Python counts when it does a backup. I don't know of a way > to see what the OS has to say what it thinks is correct. Any ideas on > how to do this? Yes, just open your C: drive (or whatever file system you have) in an Explorer window, then select all files and folders by doing Ctrl-A (or Select All from the Edit menu), then right-click and select Properties. Along with the total storage space used, etc, the dialog will show "Contains: xx,xxx files". -Peter From guy at NOSPAM.r-e-d.co.nz Mon May 10 05:35:26 2004 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Mon, 10 May 2004 21:35:26 +1200 Subject: list comprehension In-Reply-To: <mailman.386.1084150618.25742.python-list@python.org> References: <c7mii9$988$1@lust.ihug.co.nz> <mailman.386.1084150618.25742.python-list@python.org> Message-ID: <c7nicu$eaf$1@lust.ihug.co.nz> s.replace(',',',-') HA!!:-) Thanks Andrew. As usual making it more complicated than it needs to be... Guy Andrew Bennetts wrote: > On Mon, May 10, 2004 at 12:32:20PM +1200, Guy Robinson wrote: > >>Hello, >> >>Trying to change a string(x,y values) such as : >> >>s = "114320,69808 114272,69920 113568,71600 113328,72272" >> >>into (x,-y): >> >>out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272" >> >>I tried this: >> >>print [(a[0],-a[1] for a in x.split(',')) for x in e] >> >>But it doesn't work. Can anyone suggest why or suggest an alternative >>way? The text strings are significantly bigger than this so performance >>is important. > > > It has several syntax errors; (a[0],-a[1] for a in x.split(',')) is not a > valid expression because list comprehensions are bracketed by square > brackets, not parentheses. Also, the first part of a list comprehension, > the expression to calculate each element, needs to be in parens to if it has > a comma, so that the parser can disambiguate it from an ordinary list. > > I also don't know where you got 'e' from. Is it 's', or 's.split()'? > > If list comprenhensions grow unwieldy, just use a for loop. They're > probably easier to read than a list comprehension that takes you ten minutes > to concoct, and performance is almost identical. For the sake of answering > your question, though, here's a expression that does what you ask: > > >>>>s = "114320,69808 114272,69920 113568,71600 113328,72272" >>>>s.replace(',',',-') > > '114320,-69808 114272,-69920 113568,-71600 113328,-72272' > > You could do this with list comprehensions, e.g.: > > >>>>' '.join(['%s,-%s' % tuple(x) for x in [pairs.split(',') for pairs in s.split(' ')]]) > > '114320,-69808 114272,-69920 113568,-71600 113328,-72272' > > But I don't really see the point, given the way you've described the > problem. > > -Andrew. > > From autarkis at bad-data.net Sun May 23 13:03:26 2004 From: autarkis at bad-data.net (Autarkis) Date: Sun, 23 May 2004 19:03:26 +0200 Subject: xchat plugin - stuck Message-ID: <20040523190326.34af0393@jediknight.unstable.bad-data.net> Hi all I don't have a lot of experience in programming. I use python as a replacement for mIRC scripting in xchat. I made a module that looked like this. #!/usr/bin/python __module_name__ = "helloxchat" __module_version__ = "0.3" __module_description__ = "Python module test" import xchat def passwordtest(word, word_eol, userdata): xchat.emit_print(word[0]) return xchat.EAT_NONE xchat.hook_server("PRIVMSG", passwordtest) That's it. Loaded fine in Python and did an Echo, fine. That's what I wanted. But now it's stuck! I unloaded the programm, the python.so module, restarted xchat, reinstalled xchat and all, but the echo is still here. (The program is no longer). This has to be something really stupid, so if you could help me out here I'd appreciate it a lot. Thanks. From bart_nessux at hotmail.com Mon May 24 09:14:30 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Mon, 24 May 2004 09:14:30 -0400 Subject: Get Amount of Physical Memory Message-ID: <c8ssfm$95h$1@solaris.cc.vt.edu> Is there a function in Python that will get the amount of physical memory from the machine the interpretor is running on? Thanks, Bart From me at privacy.net Sat May 1 09:40:18 2004 From: me at privacy.net (Heather Coppersmith) Date: 01 May 2004 09:40:18 -0400 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> Message-ID: <m2ad0suuyl.fsf@unique.phony.fqdn> On 1 May 2004 05:47:20 -0700, frank at chagford.com (Frank Millman) wrote: [ details of a multi-level object hierarchy, and worries of __init__ methods bypassing it ] > By inheriting from the incorrect class, the special methods to > handle a 'Master' type table have been bypassed. My question is, > how can Table check that objects have inherited from the correct > subclasses? Python usually takes the "we're all adults here" point of view, and leaves that question to unit tests and/or code reviews. No amount of B&D is sufficient to protect from a malicious coder anyway. > Here is my inelegant solution. Assume that table_type contains > the string 'Master'. > class Master(Table): > def __init__(self,table_name,table_type): > self.my_type = 'Master' > Table.__init__(self,table_name,table_type) > class Table: > def __init__(self,table_name,table_type): > if hasattr(self,'my_type'): > ok = (self.my_type == table_type) > else: > ok = False > if not ok: > raise RuntimeError('%s must be of type %s' % > (table_name,table_type)) > Is there a more direct way for a top-level class to determine > which subclasses were used to instantiate it? You could add another (optional) parameter to Table.__init__, but that's really the same solution with new syntactic sugar. You could unwind the stack frame and look at who's calling Table.__init__, but that's rather un-Pythonic, too. IMO, the most Pythonic solution is to provide factory functions that do the Right Thing instead of instantiating your classes directly from your application code. HTH, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From eurleif at ecritters.biz Tue May 18 01:20:56 2004 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 18 May 2004 05:20:56 GMT Subject: "Extracting" a dictionary In-Reply-To: <SqKdnfdPML7sDzTdRVn-gw@comcast.com> References: <mailman.20.1084820319.6949.python-list@python.org> <SqKdnfdPML7sDzTdRVn-gw@comcast.com> Message-ID: <Y2hqc.2185$Hf.1281846@newshog.newsread.com> Jason Mobarak wrote: > Daniel Klein wrote: >> Is there a way to 'extract' a dictionary into the current namespace? > > Is this illegal? > > >>> import __main__ > >>> d = {'foo':'oof','bar':'rab','baz':'zab'} > >>> for k,v in d.items(): > ... setattr(__main__, k, v) > ... > >>> foo,bar,baz > ('oof', 'rab', 'zab') No, but it will need to be changed for the module's name, and won't work at all in a local namespace (like a function). From kenneth.m.mcdonald at sbcglobal.net Mon May 17 17:50:49 2004 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 17 May 2004 21:50:49 GMT Subject: How does use of bsddb interact with Python in a commercial environment? Message-ID: <slrncaid2s.ij.kenneth.m.mcdonald@g4.gateway.2wire.net> This is something I've been curious about for a while, and have never quite figured out... What are the legalities of writing commercial code which makes use of the bsddb module in Python? I would expect that payment of some sort would be necessary, but have no idea how much/under what terms. Sleepycat's most basic fee is $25,000 I believe, if people wish to incorporate code into their product, but what about the case (as in Python) where the code is being accessed only indirectly? No wonder I'm an engineer and not a lawyer :-) Thanks, Ken McDonald From greg at cosc.canterbury.ac.nz Thu May 20 21:45:52 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 21 May 2004 13:45:52 +1200 Subject: Unification of Methods and Functions In-Reply-To: <uavpa017n6dpmlr9ib25rrj6mu423v6j0b@4ax.com> References: <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <16752bcc.0405192127.47843a97@posting.google.com> <uavpa017n6dpmlr9ib25rrj6mu423v6j0b@4ax.com> Message-ID: <2h55ajF9alv2U1@uni-berlin.de> David MacQuigg wrote: > I'm still waiting for that one simple example that you say will do it > all, and do it right. I don't think you should be trying to cram all the features of OOP into a single example. Also, I worry that the zoo topic will seem contrived. Why not base your examples on some real problems from your audience's subject area? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dmq at gain.com Tue May 25 06:04:03 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 03:04:03 -0700 Subject: Unification of Methods and Functions References: <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <slrncb5u26.o6k.apardon@trout.vub.ac.be> Message-ID: <qa56b01nl70u3ffct3pef3paudnqh9flgu@4ax.com> On 25 May 2004 07:39:49 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote: >Op 2004-05-22, David MacQuigg schreef <dmq at gain.com>: >> On Sat, 22 May 2004 12:10:51 -0600, "Dave Brueck" >><dave at pythonapocrypha.com> wrote: <snip> >>>I don't see how this is at all related to static methods. A method is some >>>piece of functionality that is specific to a particular class. If you have some >>>function already lying around, why would you want it as a method, much less a >>>static method? (I can think of a couple of rather contrived examples, but >>>nothing compelling or common in a normal application - help me out here) >> >> Here is an example from our CDP ( Circuit Design Platform ): >> >> class Bag: >> def __init__(self, **kwargs): >> self.__dict__.update(kwargs) >> >> def load(infile): >> strng = infile.read() >> exec( 'bag = Bag(\n' + strng + ')' ) >> return bag >> load = staticmethod(load) >> >> We need to load a "statefile" with a deeply nested hierarchy of >> parameters, which will then be represented by a "Bag" of parameters at >> each level of the hierarchy. The load method needs to be called >> before any Bag exists, so we add the magic "staticmethod" line, and >> don't worry about 'self'. Sure, we could move the load function >> outside of the Bag class, but that would disrupt the natural structure >> of the program. The load function is unique to Bags, and it belongs >> in the Bag class. > >I don't agree it belongs in the Bag class. The fact that it is unique >to Bags is not an argument for that. I would agree that they belong in the >same module. I think we need to trust the programmer who wrote the class as to the right place to put the load function. He is the only one who can organize the best overall structure of modules and classes in the context of his entire system. >IMO you try to cram too much into the class. It seems you want to >put everything in the class that is related to the class. But >sometimes things are related without being a part of it. Writing >a seperate function in the same module makes more sense in that case. In this case there is only one other method in the class ( save ), and it forms a neat, self-contained package. Moving load to the module level just so we can avoid the staticmethod line may put it in a namespace that is already crowded with a bunch of other similar things. We also need tricks like adding "bag" to the function name, or putting the load function right next to the Bag class, so future programmers will notice that the function is for Bags only. >>>I find the current distinction between methods and functions as one that makes >>>quite a bit of sense. It doesn't really cause problems, and I've yet to see a >>>proposal that is cleaner while still making as much sense (IOW, perhaps it IS >>>imperfect, but I can't think of anything better, and apparently nobody else can >>>either). >> >> Have you read the proposal at >> http://www.ece.arizona.edu/~edatools/Python ?? The folks at >> prothon.org also think they have a better solution. There are some >> good ideas amongst all the crud. Unification of methods and functions >> is one. It remains to be seen if they can do this without introducing >> other equally bad complexities. Smooth the carpet in one place, and >> the wrinkles pop up somewhere else. >> >> When you say the distinction between methods and functions makes >> sense, I assume you mean it has some value to the user. I would like >> to hear more about this, because I am assuming just the opposite. In >> my OOP chapter, I rely on the fact that students already understand >> functions. I use the term "method" only when it is necessary to make >> a distinction. Otherwise, everything is just a function, and there is >> only one kind. > >Well one possible view is that methods are just functions. The >difference being that it is not exactly the function as it >is defined in the class but as related function. Now I don't >know if trying to explain methods from this point of view >would be easier for students to understand and it may cause >confusions of its own. But I think this approach deserves >more attention you seem willing to give it. I don't feel I can make much improvement on Learning Python, 2nd ed. I think this is the same approach that you are talking about - functions first, then methods, one variation at a time. -- Dave From tkpmep at hotmail.com Tue May 25 19:54:30 2004 From: tkpmep at hotmail.com (Thomas Philips) Date: 25 May 2004 16:54:30 -0700 Subject: Passing parameters to functions References: <mailman.228.1085416724.6949.python-list@python.org> Message-ID: <b4a8ffb6.0405251554.326eea7f@posting.google.com> Thanks for the explanation. A follow up question: Suppose I want to pass AT LEAST 2 positional arguments and AT LEAST 2 keyword arguments into a function, Then I think I would logically define the function as follows def f(parg1, parg2, karg1="yes", karg2="no", *pargs, **kargs): print parg1, parg2, pargs, karg1, karg2, kargs and I expect that f(1, 2, 3, 4, 5, karg1="maybe", karg2="maybe not", m="yes", n="no") will return 1 2 (3, 4, 5) "maybe" "maybe not" {'m': "yes", 'n': "no"} But instead I get an error: f() got multiple values for keyword argument 'karg1' For the reasons you outlined earlier, the alternate form f(1, 2,karg1="maybe", karg2="maybe not", 3, 4, 5, m="yes", n="no") generates a syntax error. How can I pass all these arguments into the function cleanly? Thomas Philips From lbates at swamisoft.com Thu May 27 13:47:04 2004 From: lbates at swamisoft.com (Larry Bates) Date: Thu, 27 May 2004 12:47:04 -0500 Subject: How to I print without newline ? References: <mailman.364.1085670411.6949.python-list@python.org> Message-ID: <T5GdnS3uCs41tCvdRVn-vw@comcast.com> Here's a progressbar class I wrote some time ago, hope it helps. -Larry class progressbarClass: def __init__(self, finalcount, progresschar=None): import sys self.finalcount=finalcount self.blockcount=0 # # See if caller passed me a character to use on the # progress bar (like "*"). If not use the block # character that makes it look like a real progress # bar. # if not progresschar: self.block=chr(178) else: self.block=progresschar # # Get pointer to sys.stdout so I can use the write/flush # methods to display the progress bar. # self.f=sys.stdout # # If the final count is zero, don't start the progress gauge # if not self.finalcount : return self.f.write('\n------------------ % Progress -------------------1\n') self.f.write(' 1 2 3 4 5 6 7 8 9 0\n') self.f.write('----0----0----0----0----0----0----0----0----0----0\n') return def progress(self, count): # # Make sure I don't try to go off the end (e.g. >100%) # count=min(count, self.finalcount) # # If finalcount is zero, I'm done # if self.finalcount: percentcomplete=int(round(100*count/self.finalcount)) if percentcomplete < 1: percentcomplete=1 else: percentcomplete=100 #print "percentcomplete=",percentcomplete blockcount=int(percentcomplete/2) #print "blockcount=",blockcount if blockcount > self.blockcount: for i in range(self.blockcount,blockcount): self.f.write(self.block) self.f.flush() if percentcomplete == 100: self.f.write("\n") self.blockcount=blockcount return if __name__ == "__main__": from time import sleep pb=progressbarClass(8,"*") count=0 while count<9: count+=1 pb.progress(count) sleep(0.2) pb=progressbarClass(100) pb.progress(20) sleep(0.2) pb.progress(47) sleep(0.2) pb.progress(90) sleep(0.2) pb.progress(100) print "testing 1:" pb=progressbarClass(1) pb.progress(1) <fowlertrainer at anonym.hu> wrote in message news:mailman.364.1085670411.6949.python-list at python.org... > Hi ! > > I want to print, but without newline. I want to create a progress for > ftp, but the print is drop a newline for every percent. > I want like this: > > 0% 25% 50% 75% 100% > > But this happening: > 0% > 25% > 50% > 75% > 100% > > How to I prevent the newlines ? > > Thanx for help: > FT > > From jhefferon at smcvt.edu Thu May 20 20:45:21 2004 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 20 May 2004 17:45:21 -0700 Subject: Why does the "".join(r) do this? References: <545cb8c2.0405200738.296bb094@posting.google.com> <c8ikud$kgb$05$1@news.t-online.com> Message-ID: <545cb8c2.0405201645.16ac3364@posting.google.com> Peter Otten <__peter__ at web.de> wrote > So why doesn't it just concatenate? Because there is no way of knowing how > to properly decode chr(174) or any other non-ascii character to unicode: > > >>> chr(174).decode("latin1") > u'\xae' > >>> chr(174).decode("latin2") > u'\u017d' > >>> Forgive me, Peter, but you've only rephrased my question: I'm going to decode them later, so why does the concatenator insist on decoding them now? As I understand it (perhaps this is my error), encoding/decoding is stuff that you do external to manipulating the arrays of characters. > Use either unicode or str, but don't mix them. That should keep you out of > trouble. Well, I got this string as the filename of some kind of Macintosh file (I'm on Linux but I'm working with an archive that contains some pre-X Mac stuff) while calling some os and os.path functions. So I'm taking strings from a Python library function (and using % to stuff them into strings that will end up on the web, which should preserve unicode-type-ness, right?) and then .join-ing them. I didn't go into the whole story when posting, because I tried to boil the question down. Perhaps I should have. Thanks; I am often struck by how helpful this group is, Jim From greg at cosc.canterbury.ac.nz Sun May 23 22:10:44 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 14:10:44 +1200 Subject: Unification of Methods and Functions In-Reply-To: <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> References: <16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> Message-ID: <2hd3t4Fbk8gkU2@uni-berlin.de> David MacQuigg wrote: > The need for static methods > will arise when the student first writes a method that needs to work > without a current instance. But why would he need such a method, as opposed to a plain function? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From greg_miller at nexpress.com Wed May 26 13:12:59 2004 From: greg_miller at nexpress.com (Greg) Date: 26 May 2004 10:12:59 -0700 Subject: launching Adobe Reader from wxHTMLwindow Message-ID: <ec6e757a.0405260912.7b408df3@posting.google.com> I have some html code that is displayed on a wxHTMLwindow in a Python application. One of the ahref links is to a pdf document. When I click the link, I get what appears to be some sort of header material for a pdf document, but Adobe Reader doesn't start. Is there a special call I will have to use in the HTML code instead of ahref to get Reader to launch? From tjreedy at udel.edu Thu May 13 10:56:58 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 May 2004 10:56:58 -0400 Subject: Unification of Methods and Functions References: <pisi90h6rismofe5du8s4a1omhm5ipv7bg@4ax.com><16752bcc.0405060737.bd43802@posting.google.com><knfl90tes9m608n99jn9lfcnpij5gqemaf@4ax.com><16752bcc.0405070531.10dcc1fc@posting.google.com><4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com><16752bcc.0405080607.4bb18276@posting.google.com><889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> Message-ID: <c802bs$ern$1@sea.gmane.org> "Antoon Pardon" <apardon at forel.vub.ac.be> wrote in message news:slrnca6d58.1i9.apardon at trout.vub.ac.be... > One could argue that all forms of methods and functions are unified. > It is just that python does some magic so that the method you > access from an object is not the actual function but the curried > function with the object. My view is similar: in Python, a method is a dressed up (wrapped) function. 'Unification of methods and functions' reads to me like 'unification of dressed-up bodies and naked bodies'. What would that mean? One thing I like about Python is that there is only function-body syntax and not a separate, slightly different method-body syntax. To me, having only one type of code body *is* unification. So it is hard for me to see what is being proposed. Introducing a syntax like '.var' that would only be meaningful in a method and not a function would be dis-unification. Terry J. Reedy From roy at panix.com Wed May 26 10:17:37 2004 From: roy at panix.com (Roy Smith) Date: Wed, 26 May 2004 10:17:37 -0400 Subject: modifying mutable list elements in a for loop References: <mailman.316.1085577473.6949.python-list@python.org> Message-ID: <roy-5F478D.10173726052004@reader2.panix.com> Michael Chermside <mcherm at mcherm.com> wrote: > >>> alist = range(10) > >>> for x in alist: > ... alist.remove(x) > ... > >>> alist > [1, 3, 5, 7, 9] > > This behavior is perfectly well defined. (Think about it. Now think > about it again. Got it?) But you have to admit that it's confusing > to beginners, so the Tutorial strongly recomends against it. It's confusing to non-beginners too. I've been using Python for 7 years now. While I don't spend a lot of time delving into the esoterica of the language, I think I've got a pretty good handle on how it works. I think I understand what's going on in the loop, but there's a difference between being able to understand why it's doing something vs. being able to look at a piece of code and predict what it's going to do. I don't think I would have been able to do that with this code. So, my recommendation is to stay away from tricky things like this. The same thing could have been done with: >>> temp = range (10) >>> alist = temp [1::2] >>> alist [1, 3, 5, 7, 9] or for that matter: >>> range (1, 10, 2) [1, 3, 5, 7, 9] but I suspect the point of the example was not how to create such a list from scratch, but how to get every other element of an existing list. Never try to be fancy. Someday, somebody's going to have to read your code and they'll curse you for it. That somebody might even be you. From stephen.no at spam.theboulets.net.please Sat May 1 08:53:45 2004 From: stephen.no at spam.theboulets.net.please (Stephen Boulet) Date: Sat, 01 May 2004 07:53:45 -0500 Subject: Pyrex 0.9.1.1 compile problem References: <Qd6dneK8yKywBQ7dRVn-gw@comcast.com> Message-ID: <Vp6cndn3tZ6jAg7d3cwC-g@speakeasy.net> Same error on my linux intallation. Peter wrote: > Kernel 2.6.5 > Slackware 9.1 > Python -V: 2.3.1 > > running python setup.py install yields the following error: > > peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ python setup.py install > Traceback (most recent call last): > File "setup.py", line 8, in ? > if sys.platform in ("unix", "darwin"): > NameError: name 'sys' is not defined > peter at peter:/mnt/src/rox/Pyrex-0.9.1.1$ > > What am I missing? > > Thx -- Stephen From here to there and there to here, funny things are everywhere. -- Dr Seuss From eric at zomething.com Tue May 18 21:40:40 2004 From: eric at zomething.com (Eric @ Zomething) Date: Tue, 18 May 2004 17:40:40 -0800 Subject: installing modules compiled with visual studio Message-ID: <20040518174040.668833117.eric@zomething.com> Matthias <matthiasverniers at mail15.com> wrote: > Subject: installing modules compiled with visual studio > > Hello > > I am a programming newbie, trying to install the "Twisted" package from > source, on a Windows computer with Python 2.3 installed. But when I try to > build the sources it gives an error: "Python was built with version 6 > Visual Studio, and extensions need to be built with the same version of > the compiler, but it isn't installed". It seems there are some C or C++ > libs included in the package, but Python can't install them because I > don't have Visual Studio installed. Is there a way I can build the > extensions without using Visual Studio ? I have another C++ compiler > installed on my pc. Help would really be appreciated as I need the > package, now I run an older version that came with an installer, but I > really need the newer package. I've asked the same question, and I think I was told to compile Twisted (etc.) with my (non-Visual Studio) C++ compiler. Or was it "re-compile Python with my C++ compiler" (huh?) I didn't go through the effort, partly because I have misgivings about whether that approach would work - are there C++ Visual Studio libraries required by the source which my compiler won't have? - quite possibly I just don't get it. That error message certainly doesn't do much for adoption of the package; Twisted might be "the answer" for the things I want to do, but that error seems to make that tough to discover. I've come across this on a few other packages as well, but just a minority. Maybe someone can give me a "Tutor" level schooling... I know I should "get this"... signed, Clueless clueless at zomething.con "Program in Python and learn C++!" From jarausch at igpm.rwth-aachen.de Mon May 24 03:59:49 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Mon, 24 May 2004 09:59:49 +0200 Subject: iterator expression - please explain Message-ID: <2hdobkFbkjkoU1@uni-berlin.de> Hi, with Python 2.4a0 (CVS 2004/05/24) I get def myfun(myarg): for z in myarg: print z myfun(x^2 for x in xrange(10)) 2 3 0 1 6 7 4 5 10 11 I expected the sequence 0,1,4,9,.... What am I missing and what's going on here? Many thanks for a hint, Helmut. --- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From jfabiani at yolo.com Mon May 17 13:09:55 2004 From: jfabiani at yolo.com (john fabiani) Date: Mon, 17 May 2004 17:09:55 GMT Subject: module for working with the result set In-Reply-To: <c8ao3c$mh5$03$1@news.t-online.com> References: <EO4qc.276$gK2.225@newssvr27.news.prodigy.com> <c8ao3c$mh5$03$1@news.t-online.com> Message-ID: <Dl6qc.300$y13.206@newssvr27.news.prodigy.com> Diez B. Roggisch wrote: > john fabiani wrote: > > >>Hi, >>newbie question: >>PyPgSQL (postgres driver) returns a list (not a tuple O'Rielly states >>DBAPI returns a tuple) and most of the books describe how to work with >>tuples and dictionaries when working with a result set. Does anyone know >>of a paper or tutorial that explains a few ways to deal with result >>sets. Or if anyone knows of a module that will help (that I can study) - >>that would be just as helpful? > > > What exactly is your problem? Lists behave equally with respect to read > accees to tuples. So whatever you want to do with a tuple, do it. That's what I thought but everytime I attempt to use any of the examples in the O'Reilly books I get errors. I'm so new to this stuff I can't tell if it's me or the fact I not using tuples. Things like the following: mydata=cursor.fetchmany(10) for field in mydata[0]: print mydata[0][field] Traceback (most recent call last): File "C:\Python23\Lib\site-packages\sm\scriptutils.py", line 49, in run exec codeObject in mainDict File "<source>", line 10, in ? File "C:\Python23\Lib\site-packages\pyPgSQL\PgSQL.py", line 2063, in __getitem__ key = self._xlatkey[key.lower()] KeyError: '5992 ' Exception raised while running script <source> But ;( print mydata[0][0], mydata[0][1] the above works perfectly - prints what I want. So I'm confused. Also, using things like the dtuple module does not work at all. thanks John From ville at spammers.com Tue May 25 15:04:24 2004 From: ville at spammers.com (Ville Vainio) Date: 25 May 2004 22:04:24 +0300 Subject: Problem with uudecode References: <pan.2004.05.25.16.42.14.955307@but.no.spam> Message-ID: <du7aczw9vlz.fsf@lehtori.cc.tut.fi> >>>>> "Juho" == Juho Saarikko <sorry at but.no.spam> writes: Juho> I made a Python script which takes Usenet message bodies Juho> from a database, decodes uuencoded contents and inserts them Juho> as Large Object into a PostGreSQL database. However, it Juho> appears that the to last few bytes I skimmed through your program, and noticed that you use binascii module uuencode/decode. Have you given the "uu" module a try, to see if it works better? Also, get rid of "regex" module, it even gives a DeprecationWarning suggesting switching to "re". -- Ville Vainio http://tinyurl.com/2prnb From hadi at nojunk.com.au Fri May 14 10:10:15 2004 From: hadi at nojunk.com.au (Hadi) Date: Sat, 15 May 2004 00:10:15 +1000 Subject: beginner's question References: <c82d51$78s$1@lust.ihug.co.nz> <drmdnbUpXMTjITndRVn-hg@powergate.ca> <pI3pc.34421$dr1.946771@news20.bellglobal.com> Message-ID: <c82jgg$aji$1@lust.ihug.co.nz> what's wrong with helping to new beginners? Don't be snob! regards, hadi "Sean Ross" <sross at connectmail.carleton.ca> wrote in message news:pI3pc.34421$dr1.946771 at news20.bellglobal.com... > > "Peter Hansen" <peter at engcorp.com> wrote in message > news:drmdnbUpXMTjITndRVn-hg at powergate.ca... > [snip] > > Otherwise we're likely to be spoonfeeding you answers to your homework > > assignment. > [snip] > > Hm. I've already done the 'spoonfeeding'. Didn't really think about it. > Sorry about that. From now on, I'll have atleast one cup of coffee in the > morning before I start replying to posts. > > From sorry at but.no.spam Tue May 25 15:58:15 2004 From: sorry at but.no.spam (Juho Saarikko) Date: Tue, 25 May 2004 22:58:15 +0300 Subject: Problem with uudecode References: <pan.2004.05.25.16.42.14.955307@but.no.spam> <du7aczw9vlz.fsf@lehtori.cc.tut.fi> Message-ID: <pan.2004.05.25.19.58.14.290393@but.no.spam> On Tue, 25 May 2004 22:04:24 +0300, Ville Vainio wrote: >>>>>> "Juho" == Juho Saarikko <sorry at but.no.spam> writes: > > Juho> I made a Python script which takes Usenet message bodies > Juho> from a database, decodes uuencoded contents and inserts them > Juho> as Large Object into a PostGreSQL database. However, it > Juho> appears that the to last few bytes > > I skimmed through your program, and noticed that you use binascii > module uuencode/decode. Have you given the "uu" module a try, to see > if it works better? I did examine the uu module, but it would seem that I'd had to parse the message first anyway to get the file name and the non-binary parts of the message as keywords. Besides, as I understand it, the uu module uses the binascii module, so if there's something wrong with the binascii module, the uu module can't possibly work well. Oh well, I would had to write the parsing engine anyway (or learn to use the e-mail classes), to properly handle mime and yenc messages. And I suppose I'd better start using imagemagic to verify the mimetype of decoded files, instead of just believing the filename. And join together files that have been spread over multiple messages. Work, work, work... > Also, get rid of "regex" module, it even gives a DeprecationWarning > suggesting switching to "re". I would, if I knew how to make regular expressions; I found the uu-parsing snippet from the net and built my script around it, but the regular expression doesn't seem to work with the re module. From max at alcyone.com Wed May 19 22:14:31 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 May 2004 19:14:31 -0700 Subject: ANN: uid.py 1.0.2 -- Configurable unique ID generation Message-ID: <40AC1487.EA453C74@alcyone.com> Summary Configurable unique ID generation. Overview Provided is an implementation of a "unique" ID (UID) generator in Python. The implementation does not follow UUID or GUID standards, but rather uses available system, host, user, shell environment, process, and other ephemeral information fed into a hasher (by default MD5) to generate the UID. The system is designed to be used both as a standalone application and as a module. The data used to be fed into the hash, as well as the hashing mechanism itself, can be overridden both through the command line and programmatically by importing the module. Getting the software The current version of uid is 1.0.2. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/uid/uid-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/uid/. Requirements uid.py is intended to be used under UNIX and UNIX-like systems in Python 2.x. License This code is released under the GPL. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Nature likes to hide herself. -- Heraclitus From lbates at swamisoft.com Wed May 26 10:04:16 2004 From: lbates at swamisoft.com (Larry Bates) Date: Wed, 26 May 2004 09:04:16 -0500 Subject: modifying mutable list elements in a for loop References: <9d5509fa.0405260439.175797e@posting.google.com> Message-ID: <gLSdnZRdoZVDPind4p2dnA@comcast.com> If you write this as a list comprehension it "seems" more safe (and clear to me at least): a = [[1,2], [3,4], [5,6], [7,8]] a = [x+[10] for x in a] Larry Bates Syscon, Inc. "Peter Ballard" <pballard at ozemail.com.au> wrote in message news:9d5509fa.0405260439.175797e at posting.google.com... > Whew. I hope that title is descriptive! > > Hi all, > > The python tutorial tells me "It is not safe to modify the sequence > being iterated over in the loop". But what if my list elements are > mutable, such as lists or objects, e.g. > > a = [[1,2], [3,4], [5,6], [7,8]] > for coord in a: > coord.append(10) > print str(a) > > When I tried it, it gave the "expected" answer, i.e. > > [[1, 2, 10], [3, 4, 10], [5, 6, 10], [7, 8, 10]] > > It worked, but is it safe? I can't see why it wouldn't be, but > technically I have broken the rules because I have modified the > sequence which is being looped over. > > [It seems to me that the list elements are pointers (in C-speak), so I > can safely modify the data they are pointing to, because I am not > modifying the list elements themselves. Or is that an implementation > detail (i.e. not safe)?] > > Actually the more I think about it the more I think it must be OK, > because how else can one perform an operation on a list of objects? > But that phrase "It is not safe to modify the sequence being iterated > over in the loop" in the tutorial has me slightly worried. > > -- > Regards, > > Peter Ballard > Adelaide, AUSTRALIA > pballard at ozemail.com.au > http://members.ozemail.com.au/~pballard/ From rjt-usenet at thegrindstone.me.uk Thu May 6 12:28:00 2004 From: rjt-usenet at thegrindstone.me.uk (Richard Taylor) Date: Thu, 06 May 2004 17:28:00 +0100 Subject: Private identifiers - naming References: <930ba99a.0405060600.17e076bc@posting.google.com> <c7diku$f1j$2@arcturus.ciril.fr> Message-ID: <409a6791$0$31686$fa0fcedb@lovejoy.zen.co.uk> Yermat wrote: > Sridhar R wrote: >> In python, to hide (from direct access) identifiers from outsiders >> (not current module), we usually prefoften variables with '__'. >> >> But this is usually _difficult_ to read. Imagine a module (which is a >> common one) containing more private variables than public variables. >> >> How cryptic it would be to see text with lot of __ in front of them !! >> >> Any thoughts? > > Do we really need private variable ? > One of the things I like about Python is that it places trust in the programmer. No nasty compiler policeman telling me off when I break the rules. So the point of a 'private' variable is to indicate to the user of a class that the author of the class did not intend it to be accessed directly. Personally I tend to do this by appending a single '_' to method or identifier names. If a caller wishes to ignore my hint that they should not access such variables/methods then that is up to them. This 'trust' in the programmer often means that more use can be made of third-party packages because the way that they are used can be 'bent' slightly by 'tweeking'. Experience has taught me that the over zealous use of private/protected identifiers in C++ can made libraries much less flexible. We are all adults here, no need for nasty police men. Richard From dontaskme at doityourself.com Fri May 14 10:24:55 2004 From: dontaskme at doityourself.com (Meno) Date: 14 May 2004 07:24:55 -0700 Subject: make faster Richards benchmark References: <mailman.540.1084499664.25742.python-list@python.org> <osGdnfaC2oTOtjndRVn-tw@powergate.ca> Message-ID: <9c2d8268.0405140624.f7a167e@posting.google.com> Peter Hansen <peter at engcorp.com> wrote in message news:<osGdnfaC2oTOtjndRVn-tw at powergate.ca>... > Simon Wittber wrote: > > >>>And Simon: "I just tried the benchmark with Psyco, and cut the run > >>>time for input=10000 from 8.1 seconds to 3.4" > >>> > >> > >>What platform is this on? > > > > WinXP, P4 2.6GHZ, 512MB RAM > > Hmm... did anyone else confirm your numbers, so that I'm > the odd man out? > > I'm using Python 2.3.3 and the latest download of Psyco > for it. > > If you're using that too, the only apparent difference is > the CPU. Is it possible that could make such a significant > difference? (Unlikely at best, I'd say.) > > -Peter On AMD XP 2500 and 512 MB RAM: gone from 855430 ticks to 503353 ticks with psyco. That is I think 41% less time. Peter, note that getting it to run twice as fast "only" means 50% less time. Maybe that is what you should compare with your 38%... Nemo. From csad7 at yahoo.com Sun May 16 05:25:58 2004 From: csad7 at yahoo.com (chris) Date: Sun, 16 May 2004 11:25:58 +0200 Subject: general Wiki format question and Python Wiki markup parsing libraries Message-ID: <c87c38$otu$07$1@news.t-online.com> hi, i am looking for a way to structure the text in XML comments to produce a XHTML doc format for the XMLs (in this case XSLT). so is was thinking about using a wiki like text format. e.g. something like <!-- !Headline some __bold__ text in a paragraph * a list * another item etc... (the markup used is only an example!) --> but it should be a widely used format that people do not need to learn yet another syntax. it will be used by people using XSLT so it should not be language (py, perl, java, ...) specific. is there something like a "standard" wiki format at all, or at least one that is widely used? in my company we use a jspwiki which e.g. uses !, !! and !!! for headlines, __bold__ and * list markup (like the example above). is this more or less a standard as this is the only wiki i've used yet? i was googling for python libraries which would parse a wiki text format to xhtml but could not find something really useful. is there a python library to parse these text formats? i was looking a bit into reStructuredText but was wondering if this is generally used or maybe is too Python specific. any hint would be great thanks chris From FrankBechstein at t-online.de Tue May 11 13:00:53 2004 From: FrankBechstein at t-online.de (Frank Bechstein) Date: Tue, 11 May 2004 19:00:53 +0200 Subject: error handling In-Reply-To: <9a7d1123ef0a311cfdff5522c570b4ec@news.teranews.com> References: <c7p559$6nq$05$1@news.t-online.com> <9a7d1123ef0a311cfdff5522c570b4ec@news.teranews.com> Message-ID: <c7r0rq$3vu$01$1@news.t-online.com> Thank you! I figured it out From svein+usenet01 at brage.info Tue May 18 16:45:46 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Tue, 18 May 2004 22:45:46 +0200 Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <Q3lqc.2178$eH3.47040@news4.e.nsc.no> <slrncak7aq.21u.grante@grante.rivatek.com> <uk6z94uym.fsf@broadpark.no> <1mklty031ke5a.dlg@thorstenkampe.de> <duuqc.3297$37.397543@news.siol.net> Message-ID: <oAuqc.2306$eH3.49684@news4.e.nsc.no> Mitja wrote: > Thorsten Kampe <thorsten at thorstenkampe.de> > (news:1mklty031ke5a.dlg at thorstenkampe.de) wrote: >> * Tor Iver Wilhelmsen (2004-05-18 17:26 +0100) >>> Grant Edwards <grante at visi.com> writes: >>> >>>> Dude, didn't you take high-school math? 1/3 _is_ 0.33333... >>> >>> No, because at some point you will stop writing 3's, either out of >>> boredom, exhaustion or because you need to pee. At that instant, you >>> introduce a rounding error, making 3 * 1/3 = 0.99999999999... instead >>> of 1.0 >> >> Must have been a long time since you went to school... 1/3 is >> /exactly/ 0.3...: http://mathworld.wolfram.com/RepeatingDecimal.html >> > > Even worse.... > 0.999999999999999999999... is exactly 1 :) Only for infinite counts of '9', and computers don't do infinity. From tim.one at comcast.net Fri May 21 14:17:15 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 21 May 2004 14:17:15 -0400 Subject: Python 2.3.4c1 -- nasty threading bug (Linux) In-Reply-To: <x7pt8xoo5f.fsf@handshake.de> Message-ID: <mailman.131.1572214656.32708.python-list@python.org> [Dieter Maurer] > Python apparently contains a long lasting threading bug on Linux > with LinuxThreads. Yes, although note that LinuxThreads is an incorrect implementation of the phtreads standard in a relevant respect, so you should also say that LinuxThreads has a longstanding bug here. > SIGSEGV causes hung threads (Linux) > http://www.python.org/sf/756924 ... > This problem causes multi-threaded applications such > as Zope to enter a funny state when one of the threads crashes. > Some of the threads die but others remain and can only be killed > with "kill -9". Normal restart logic fails for Zope because of these > remaining threads. > > <mailto:alangmead at boston.com> submitted a patch > > <http://sourceforge.net/tracker/index.php?func=detail&aid=949332&group_id= > 5470&atid=305470> > > Nevertheless, the problem still exists in Python 2.3.4c1. > Either the patch was not applied or it does not fix the problem. The patch wasn't applied, and the 2.3.4 release manager doesn't want to risk it for 2.3.4. Do read the bug report! There are 36 comments attached (so far) because it's a complex problem to solve it correctly. Andrew Langmead (whose patch you referenced) is continuing to participate in finding a correct solution. See his comment there dated 2004-05-04 10:00 for the relevant respect in which LinuxThreads is buggy but NPTL is not. From steve at ferg.org Wed May 5 21:54:55 2004 From: steve at ferg.org (Stephen Ferg) Date: 5 May 2004 18:54:55 -0700 Subject: Best IDE? References: <c5bg1k$25vq$1@news.wplus.net> Message-ID: <b16e4ef7.0405051754.3093ee5e@posting.google.com> Komodo, hands down. Personal edition is only $29. From JSmuts at clover.co.za Sun May 30 11:41:31 2004 From: JSmuts at clover.co.za (Jaco Smuts) Date: Sun, 30 May 2004 17:41:31 +0200 Subject: py2exe service dependency Message-ID: <OFBE597406.C64C7F52-ON42256EA4.0055E25F-42256EA4.005632EC@clover.co.za> Hello there I've written a service using win32service. When I do service.py install it registers dependencies succesfully, however the version compiled with py2exe seems to miss the dependencies ? in subclass serviceFramework set the service dependency in _svc_deps_ I'm using Python 2.3.3 with py2exe 0.5 any help will be appreciated. thanks jaco -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040530/28332280/attachment.html> From Joseph.V.Laughlin at boeing.com Mon May 3 15:54:02 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Mon, 3 May 2004 12:54:02 -0700 Subject: Setting CPU Affinity Message-ID: <67B3A7DA6591BE439001F2736233351202876EDA@xch-nw-28.nw.nos.boeing.com> When I spawn a new process via spawnv(), how can I set the CPU affinity for the newly-spawned process with python? Thanks, Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From http Thu May 13 15:35:34 2004 From: http (Paul Rubin) Date: 13 May 2004 12:35:34 -0700 Subject: Generators: section 9.10 of the python tutorial References: <mailman.527.1084471592.25742.python-list@python.org> Message-ID: <7xk6zgce7t.fsf@ruckus.brouhaha.com> "David Stockwell" <winexpert at hotmail.com> writes: > Section 9.10 of the tutorial discusses the yield keyword. When I > tried using it I get the following SyntaxError. > > What does this error mean? Does it mean we can't use yield in our > code? It means you're using an older version of Python in which yield isn't a standard built-in keyword. Try putting from __future__ import generators at the very top of your source file to enable the yield statement. The special import is there so that old code that uses "yield" as (say) a variable name won't suddenly break. From ajsiegel at optonline.com Fri May 28 08:56:40 2004 From: ajsiegel at optonline.com (Arthur) Date: Fri, 28 May 2004 12:56:40 GMT Subject: terminological obscurity References: <1085378050.309299@yasure> <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <donn-F5877E.11513724052004@nntp1.u.washington.edu> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <donn-10607D.09032925052004@nntp1.u.washington.edu> <dam7b0dip3fi1dnicj4gmnb30d5vf2up88@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> Message-ID: <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> On Fri, 28 May 2004 09:01:46 +0200, "Martin v. L?wis" <martin at v.loewis.de> wrote: > >So: No, "homogenous data" is *NOT* a tautology. It refers to >inherent properties of the elements of the list, not to the >fact that they are members of the list. Is the random set of, say, 10 human beings homogeonous or hetereogenous? Or is that a meaningless question, as the answer depends purely on context? Are objects that have hundreds of attributes each, and that conform as to a single attribute, which attibute accounts for there presence together in a list, meaningfully homogenous - outside of the fact of their presence together in the list? Art From tzot at sil-tec.gr Mon May 31 18:28:53 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 01 Jun 2004 01:28:53 +0300 Subject: Regexp: unexspected splitting of string in several groups References: <39cbe663.0405310341.430d2035@posting.google.com> Message-ID: <vcbnb0he70056kn2tppgr3fagnm24sjs2d@4ax.com> On 31 May 2004 04:41:11 -0700, rumours say that pit.grinja at gmx.de (Piet) might have written: >vartype is a simple string(varchar, tinyint ...) which might be >followed by a string in curved brackets. This bracketed string is >either composed of a single number, two numbers separated by a comma, >or a list of strings separated by a comma. After the bracketed string, >there might be a list of further strings (separated by blanks) >describing some more properties of the column. >Typical examples are: >char(30) binary >int(10) zerofill >float(3,2)... >I would like to extract the vartype, the bracketed string and the >further properties separately and thus defined the following regular >expression: Does this RE work for you? tre= re.compile(r"(\w+)" r"(?:\(([\d\w]+(?:,[\d\w]+)*)\))?" r"(\s+\w+)*") For your examples: >>> tre.match("char(30) binary").groups() ('char', '30', ' binary') >>> tre.match("int(10) zerofill").groups() ('int', '10', ' zerofill') >>> tre.match("float(3,2)").groups() ('float', '3,2', None) PS1 if you make the re slightly more complex, you can avoid the initial space in the third "properties" group. I also assumed no space between the "vartype" and the left parenthesis (if it is there). PS2 redemo.py somewhere in your python's installation is a good friend of yours. PS3 I am a fan of regular expressions for years, and I often overuse them. Perhaps somebody else might give you a better advice than me. -- TZOTZIOY, I speak England very best, "I have a cunning plan, m'lord" --Sean Bean as Odysseus/Ulysses From bstoyanov at dspace.de Tue May 25 09:30:07 2004 From: bstoyanov at dspace.de (questioner) Date: Tue, 25 May 2004 09:30:07 -0400 Subject: Search and extract text in MS Word Message-ID: <6324c8b6b4429042467b0331f254b7be@localhost.talkaboutprogramming.com> Hello everyone, I want to find text and extract a rest of line after the found line till line end. Does anyone know how to do this? Regards, P.S. My code looks like this so far: word = win32com.client.Dispatch("Word.Application") doc = word.Documents.Add(filenamePath.doc) search = doc.Content.Find ?... and then ... ? From roccomoretti at hotpop.com Tue May 18 13:50:09 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 18 May 2004 12:50:09 -0500 Subject: So what's a "pythong"? (was Re: Python/C++ Developers required for consulting position in Brooklyn, NY) In-Reply-To: <FOidnSvClJ3UvDfdRVn-sw@powergate.ca> References: <cf879d68.0405180550.33f29483@posting.google.com> <FOidnSvClJ3UvDfdRVn-sw@powergate.ca> Message-ID: <c8dich$hkm$1@news.doit.wisc.edu> Peter Hansen wrote: >> We are looking for several contractors with very strong C++ and >> Pythong development skills. > > > "Pythong"... now there's a scary image. :-) Ouch! > > -Peter Is it anything like the "Guido Speedo"? http://www.python.org/doc/Humor.html#speedo From tom at livelogix.com Tue May 4 04:56:51 2004 From: tom at livelogix.com (Tom Locke) Date: 4 May 2004 01:56:51 -0700 Subject: compiler module supports 'statements as expressions' Message-ID: <789f72ac.0405040056.534f89f2@posting.google.com> Hi, I am writing a compiler (in python) that targets python byte-code, using compiler.ast and compiler.pycodegen. The language is lisp-like in that there is no statement / expression separation. e.g. I can do (in a python-like syntax) print (if x: "yes" else: "no") or while line = raw_input("> "); line != "": print line Having hacked away for a short while on a translator to make these things into separate statements that would be legal in Python, I was VERY surprised when I accidentally discovered that this seems to be LEGAL at the byte-code level. (CPython 2.3.3, Win XP) compiler.pycodegen.ModuleCodeGenerator generates working code for AST fragments like these: Printnl([If([(Name('x'), Stmt([Const('yes')]))], Stmt([Const('no')]))], None) and While(Stmt([Assign([AssName('line', 'OP_ASSIGN')], CallFunc(Name('raw_input'), [Const('> ')], None, None)), Compare(Name('line'), [('!=', Const(''))])]), Stmt([Printnl([Name('line')], None)]), None)])) AST 'statement' nodes, when used in an expression context, evaluate as follows. If: value of the executed clause Stmt: value of the last statement in the list While and Assign: Undefined ? python crashes if you try to do something with these values. This is really very helpful for me ? it's just the semantics I wanted! I think I'm right in saying that there's no legal Python that parses into ASTs like these, right? Can I rely on this?? Is it there for a reason? (e.g. to support certain optimizations?) Is this just serendipity ? the 'natural' behavior of the stack based byte-code interpreter? Thanks, Tom. From jcm at FreeBSD-uk.eu.org Fri May 7 16:07:36 2004 From: jcm at FreeBSD-uk.eu.org (Jonathon McKitrick) Date: Fri, 7 May 2004 21:07:36 +0100 Subject: Disabling Pmw comboboxes Message-ID: <20040507200735.GA81646@dogma.freebsd-uk.eu.org> I found lots of hack solutions that were years old, including subclassing the ComboBox and disabling/unbinding, then enabling/binding the subcomponents when needed. Has a better way been added to the Pmw toolkit itself? jm -- My other computer is your Windows box. From ruses at users.ch Sun May 9 16:56:52 2004 From: ruses at users.ch (=?ISO-8859-1?Q?Morris_Carr=E9?=) Date: Sun, 09 May 2004 22:56:52 +0200 Subject: I knew there was an mystery to it ! Message-ID: <409E9B14.3040206@users.ch> Back then - in particular, soon after 9/11 - I evidenced the natural irony of the standard python implementation, by showing it had the clear and spontaneous humor of replying : 'BUSH' when asked the convoluted question : filter(lambda W : W not in "ILLITERATE", "BULLSHIT") Now at first sight, it was clear I could attribute it to unexpectedly cosmic dimensions taken by the BDFL's "time machine" effect over Python, when applied to the time-shattering event that was 9/11. OTOH, this was an inelegantly public-resource-seizing viz the lawful Python community and its BDFL. Not to speak of 9/11 grieving ones. So that idea fell off my hands. My live mind kept expecting a deeper mystery, though, to the above Python formula. I found it out, by discovering that their was a clearly brilliant competitor explanation, to examine for contrast and completion : Original Python responded 'BUSH' when asked the convoluted question : filter(lambda W : W not in "ILLITERATE", "BULLSHIT") in particular, soon after 9/11 because in particular Python was a language designed with the idea that suffice two scopes, one local, and one global ! Now, Python is past that. (MMmmhh...) So it appears, is Bush. Conservation ! Diagonal Invariant ! Discovery ! Eur?ka ! to-me-it-looks-like-EPR-ly yours, Mori Squared From thorsten at thorstenkampe.de Wed May 26 17:50:05 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 26 May 2004 23:50:05 +0200 Subject: creating .exe file References: <3f0686ff.0405260841.6deba711@posting.google.com> <c92htp$atq$1@swifty.westend.com> <9rOdnWFMhMvqUCndRVn-tA@powergate.ca> <mailman.328.1085592956.6949.python-list@python.org> Message-ID: <sk1yah5a534y$.dlg@thorstenkampe.de> * Thomas Heller (2004-05-26 19:35 +0100) > Peter Hansen <peter at engcorp.com> writes: >> Peter Maas wrote: >>> Q X wrote: >>>> I am wondering what kind of tools are available to wrap python scripts >>>> into just 1 .exe file (with no other files) in windows. I also want >>>> the .exe file to be able to use command line arguments ie. >>>> pythonprogram.exe -classpath d:/temp -file c:/hi.text >>> http://sourceforge.net/projects/py2exe >> >> He explicitly asked for "just one .exe file (with no other files)", >> but py2exe cannot do that. > > Gordon McMillan's installer can do this. If you manage to find a copy > to download. http://paulbaranowski.org/modules.php?name=Downloads&d_op=viewdownloadsimpledetails&lid=8&title=Gordon%20McMillan's%20Installer > Or Tools/freeze. ? Thorsten From asdf at asdf.com Sun May 2 14:30:24 2004 From: asdf at asdf.com (asdf sdf) Date: Sun, 02 May 2004 18:30:24 GMT Subject: Newbe-books In-Reply-To: <O3Zkc.488$vz5.260@nwrdny01.gnilink.net> References: <Uldkc.29554$Qc.1128956@twister1.libero.it> <ekr2905p04fe3a667aejluqq4gb0fit5af@4ax.com> <O3Zkc.488$vz5.260@nwrdny01.gnilink.net> Message-ID: <47blc.4370$2b3.235@newssvr27.news.prodigy.com> > Ditto. I learned from the tutorial and DejaNews. I bought _Programming > Python_, because I liked _Programming Perl_ so much, but I haven't had > much use for it. I'm evaluating _Learning Python_ as a training aid. > It's not bad, so far. I'll probably give it to our next hire. I have both Learning Python and Programming Python. I use PP very little. I have maybe 15 bookmarks in LP but only two in PP, a much larger book. LP skips over threads as an advanced topic. So I got that discussion from PP. But a couple of pages is all that it takes. PP has more detail on the os and sys modules which was useful. But the online doc would certainly have covered it in a pinch. LP is a good book with good value for its size. PP just hasn't been a 'goto' reference. Lutz's strategy is to make LP the basic teaching book, with PP the book for detailed exercises with more real-world applications. I haven't seen 2ed for LP, but I'm interested to see if it merits buying if you already have 1ed. From SeeBelow at SeeBelow.Nut Mon May 3 21:44:02 2004 From: SeeBelow at SeeBelow.Nut (SeeBelow at SeeBelow.Nut) Date: Tue, 04 May 2004 01:44:02 GMT Subject: Must function defs appear earlier than calls? References: <4096E9F8.38ABF26D@shaw.ca> <109drk3erp8cm8c@news.supernews.com> Message-ID: <4096F56A.F9815BA7@shaw.ca> John Roth wrote: > > <SeeBelow at SeeBelow.Nut> wrote in message news:4096E9F8.38ABF26D at shaw.ca... > > Must function defs appear earlier in a file than use of their name? > > No. Function definitions must be executed before they > are called, but they don't have to be before their > calls. > > The reason for this is that it's the execution of the function > definition at run time that binds the function to the name in > the dictionary, and that's where it has to be to be executed. > > > If so, is there some way around this? It's creating a puzzle for me. > > Possibly you could say a bit more about what you're > trying to do that's causing some perplexity? > > John Roth > > > > Mitchell Timin I'm using Tkinter, creating buttons and scales. One of the buttons should have a command option to execute a function that initializes some class objects. These objects take a scale object as one of their initialization parameters, So I have to create the class objects after I create the scales. It seems that I must create the button that calls the initialization function after that, or else the function assigned to the command option is undefined. But I want to create the button first, so that it appears near the top of my frame. I hope that's clear. Now you see why I didn't describe that in my original post! And thanks for your help! Mitchell Timin -- "Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal." - Friedrich Nietzsche http://annevolve.sourceforge.net is what I'm into nowadays. Humans may write to me at this address: zenguy at shaw dot ca From Scott.Daniels at Acm.Org Fri May 14 12:40:18 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 14 May 2004 09:40:18 -0700 Subject: looping over the files in a directory In-Reply-To: <pan.2004.05.14.16.17.33.273871@freelance-developer.com> References: <kE5pc.476427$oR5.129809@pd7tw3no> <pan.2004.05.14.16.17.33.273871@freelance-developer.com> Message-ID: <40a4fba5$1@nntp0.pdx.net> Mark J. Nenadov wrote: > On Fri, 14 May 2004 15:32:32 +0000, Elaine Jackson wrote: > >>Can anyone please tell me the actual syntax for saying something like this: >> for <file> in <directory>: >> <do something with the file> > A simple example: > import os > path = '/home/bob/' > for f in os.listdir(path): > print f A further clue for Elaine is: listdir returns file "names". Files are things the OS has; names are how we talk about the files to the OS. If you want to do anything with the file, you'll have to decide what you want to do, and communicate the _full_name_ of the file to the OS when you try to do it. You can do that either by joining the path and file names, or by changing the "working directory" so that the simple file name works. Which you do depends on your overall goal. This is purposely left a bit elliptical to leave you some work in case this is a homework assignment. -- -Scott David Daniels Scott.Daniels at Acm.Org From peter.maas at mplusr.de Thu May 27 10:59:22 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 27 May 2004 16:59:22 +0200 Subject: Idea: Python Shorthand (was Re: Why a class when there will only be one instance? In-Reply-To: <du7fz9ni0ny.fsf_-_@amadeus.cc.tut.fi> References: <40B3E861.29B033D5@shaw.ca> <pan.2004.05.26.01.02.00.429236@sbcglobal.net> <du7fz9ni0ny.fsf_-_@amadeus.cc.tut.fi> Message-ID: <c94von$6ag$1@swifty.westend.com> Ville Vainio wrote: > You might want to create a preprocessor that adds "self" to all > in-class definitions that have @, and convert @hei to self.hei. Voila, > Ruby non-silliness. This is an editor job. Good programming editors allow to expand abbreviations, so there is no need to clutter the language definition or write a preprocessor. Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From sross at connectmail.carleton.ca Wed May 26 09:37:52 2004 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 26 May 2004 09:37:52 -0400 Subject: supermethod shortcut References: <c91uk9$krq$1@ctb-nnrp2.saix.net> Message-ID: <x31tc.41583$tb4.1326265@news20.bellglobal.com> "David Fraser" <davidf at sjsoft.com> wrote in message news:c91uk9$krq$1 at ctb-nnrp2.saix.net... > Hi > > I was recently thinking about the awkwardness I find in using the super > method to call a superclass's function. > [snip] > > The whole super(Y, self).some_method seems an awkward way to say "call > the superclass's version of this function". [snip] You may find the following recipe interesting: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284528 From rschroev_nospam_ml at fastmail.fm Fri May 21 14:18:07 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 21 May 2004 18:18:07 GMT Subject: Documentation/Info on this sign In-Reply-To: <40ACED36.5030706@hotmail.com> References: <c8iims$24i$1@solaris.cc.vt.edu> <1O-dnXHH1_PKTjHd4p2dnA@powergate.ca> <40ACED36.5030706@hotmail.com> Message-ID: <zJrrc.121415$fX4.6662257@phobos.telenet-ops.be> Bart Nessux wrote: > Both functions produce the same results (33,000 files)... the problem: > the filesystem has twice as many files (66,000) than the actual sums of > these two counts when doing a virus scan or an adaware scan. To make > matters more confusing... the IBM Tivoli backup software that I use > confirms the Python counts when it does a backup. Just an idea... maybe virus scanners and adaware open and scan archives (zip, rar, tar, ...) and include the files in the archives in their counts? -- "Codito ergo sum" Roel Schroeven From bart_nessux at hotmail.com Thu May 20 11:26:20 2004 From: bart_nessux at hotmail.com (Bart Nessux) Date: Thu, 20 May 2004 11:26:20 -0400 Subject: Documentation/Info on this sign Message-ID: <c8iims$24i$1@solaris.cc.vt.edu> Could someone point me to documentation on this (and similar) signs used in Python: += Usage would be: x = += len(y) Literally, that's "variable x equals 'funky-symbol-that-I-want-to-learn-about' the length of variable y" Thank you, Bart From grante at visi.com Fri May 21 17:36:13 2004 From: grante at visi.com (Grant Edwards) Date: 21 May 2004 21:36:13 GMT Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <donn-90E5D2.13452221052004@nntp1.u.washington.edu> Message-ID: <slrncastid.5mc.grante@grante.rivatek.com> On 2004-05-21, Donn Cave <donn at u.washington.edu> wrote: >> For example, why shouldn't index() find an object in a >> non-homogeneous sequence? Either the object is in the sequence or >> it's not. If it is, there is an index that corresponds to it. > > For example, > tm = time.localtime(time.time()) > i = tm.index(5) > > What would that mean? > > It's absurd to search for the location of a value in a tuple, > because the values don't have any meaning independent of their > location. OK, I see what you mean. That brings up the question of why use integer indexes to access members of of a group of objects when the order of the objects is meaningless? -- Grant Edwards grante Yow! Do you guys know we at just passed thru a BLACK visi.com HOLE in space? From goodger at python.org Sun May 2 12:39:45 2004 From: goodger at python.org (David Goodger) Date: Sun, 02 May 2004 12:39:45 -0400 Subject: [OT] does the charset lie? In-Reply-To: <16533.8123.5800.539196@montanaro.dyndns.org> References: <16533.8123.5800.539196@montanaro.dyndns.org> Message-ID: <40952451.3020106@python.org> Skip Montanaro wrote: > Given an HTML file with this meta tag: > > <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> > > and all individual characters being legitimately in the iso-8859-1 character > set, but with this numeric entity: > > ’ > > is the charset correct or should it have been utf-8? The charset is correct. "&" "#" "8" etc. are all in iso-8859-1. "’" is just a way of indicating a character outside of the text's charset. Internally, the browser may use Unicode or some other encoding, but that's not your problem. -- David Goodger From chuck.amadi at ntlworld.com Mon May 31 11:24:35 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Mon, 31 May 2004 16:24:35 +0100 Subject: a python script which will parse an email message Message-ID: <40BB4E33.9030402@ntlworld.com> (Please include python-list/comp.lang.python on your mails. You'll get more useful feedback.) chuck> Hi Skip used your snippet - the above returns a chuck> Returned mail: see transcript for details chuck> Returned mail: see transcript for details Assuming those are the subjects of the messages in /var/spool/mail/chucka, that looks fine. chuck> The second snippet - returns chuck> <open file '/tmp/subjects', mode 'w' at 0x3fcf0ea0> Returned mail: see chuck> transcript for details chuck> <open file '/tmp/subjects', mode 'w' at 0x3fcf0ea0> Returned mail: see chuck> transcript for details chuck> When i less /tmp/subjects theres no data. What version of Python are you using? Maybe it's so old it doesn't support the print >> openfile, ... construct, though if not, I'd expect a SyntaxError. Did you forget the ">>"? Skip From qrczak at knm.org.pl Sat May 29 16:51:25 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sat, 29 May 2004 22:51:25 +0200 Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> <m2k6z1ejcc.fsf@unique.phony.fqdn> <KXrsc.15274$bF3.12656@fed1read01> <n7i*p+mlq@news.chiark.greenend.org.uk> <%WRsc.18276$bF3.9891@fed1read01> Message-ID: <pan.2004.05.29.20.51.24.846937@knm.org.pl> On Tue, 25 May 2004 17:59:20 -0700, Mark Hahn wrote: > I've agreed to adding longs. I'm thinking of only having longs. It's more efficient if ints which fit in a machine word (or a machine word minus one or two bits used for tagging them as ints) are represented as such, rather than using a generic big int representation. It doesn't mean they should be treated differently in the language. It can be a hidden implementation detail, visible only for those who write extensions in C. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From apardon at forel.vub.ac.be Thu May 13 09:47:02 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 13:47:02 GMT Subject: Scope rule pecularities References: <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <2g8ag2F4re0lU1@uni-berlin.de> <slrnca428q.1i9.apardon@trout.vub.ac.be> <Xns94E78398B6CAAduncanrcpcouk@127.0.0.1> <slrnca4693.1i9.apardon@trout.vub.ac.be> <donn-A934F5.11082112052004@nntp2.u.washington.edu> <slrnca69ju.1i9.apardon@trout.vub.ac.be> <mailman.504.1084436448.25742.python-list@python.org> <slrnca6k7a.1i9.apardon@trout.vub.ac.be> <mailman.507.1084448440.25742.python-list@python.org> Message-ID: <slrnca6v2o.1i9.apardon@trout.vub.ac.be> Op 2004-05-13, Andrew Bennetts schreef <andrew-pythonlist at puzzling.org>: > On Thu, May 13, 2004 at 10:41:45AM +0000, Antoon Pardon wrote: >> Op 2004-05-13, Andrew Bennetts schreef <andrew-pythonlist at puzzling.org>: >> > On Thu, May 13, 2004 at 07:40:45AM +0000, Antoon Pardon wrote: >> >> >> >> But I don't ask for rebinding, I ask for easy in place copying. >> >> >> >> Lets name a new operator "@=" Now given variables A and C >> >> of the same class I would like to see the following: >> >> >> >> >>> B = A >> >> >>> A @= C >> >> >>> A is B >> >> True >> >> >>> A is C >> >> False >> >> >>> A == C >> >> True >> > >> > It's already easy: >> > >> > from copy import copy >> > >> > b = a >> > a = copy(c) >> >> Sorry, you are wrong. After this you get >> >> >>> a is b >> False > > Oh, sorry, I misread -- as you can see, I assumed you meant that C was a > copy of A, when actually you wanted A to be a copy of C. > > Now I understand what you mean about an "in-place copy". > >> >> And maybe if D is of an other class >> >> >> >> >>> D @= C >> >> TypError >> > >> > Assignments in Python don't care about what the name is currently bound to, >> > if anything. >> >> This is not assignment (as is understood in python). > > Indeed! But it *looks* like assignment -- it has an equals sign. In fact, > it's only one character different to Python's assignment. My point is that > the proposed syntax is confusing. Well it is a kind of assignment. It is how assignment works in some other languages. Now I find both kind of assignments usefull. I don't like it when a language restricts me to one specific kind. If you don't like the proposed syntax, I'm open to suggestions, >> class M: >> >> def cp_from(self, a): >> for key in dir(self): >> value = getattr(a,key) >> setattr(self,key,value) >> >> d.cp_from(c) > > You can do that already, without defining any new methods: > > d.__dict__.update(c.__dict__) > > [This won't work for the minority of types that don't have __dict__s on > their instances, but it does work for virtually all user-defined classes.] You can't expect people to type in that. > Assuming that d and c have the same set of instance variable names (which I > would expect most code following good style would do), I don't see why > modifying an existing instance of d to be a copy of c is any better than > simply making a copy from scratch with the clearer: > > d = copy(c) > > What's the big advantage to mutating an existing instance? The difference (whether you want to call it an advantage or not is up to you) is that with d = copy(c), d is rebound to a new object. The object itself, which could still be bound to other names, stay the same. What I sometimes want is a change of the object itself so that the change is visible to all names with which the object is currently bound. -- Antoon Pardon From http Mon May 3 15:25:22 2004 From: http (Paul Rubin) Date: 03 May 2004 12:25:22 -0700 Subject: Best way to serve Python Web Pages? References: <9d393e9d.0405030857.787b2440@posting.google.com> Message-ID: <7xpt9lmhy5.fsf@ruckus.brouhaha.com> I will give an unpopular answer and say that Python's main advantage over PHP in web applications is Python's superiority as a programming language for implementing complex projects. Python has considerable disadvantages in the areas you're asking about (ease of programming, lots of examples, lots of people who know how to use it, ease of administration, etc.) but if you're doing something big and complicated, you have to overcome all those other kinds of issues anyway, so you win by using Python. However, it sounds like you're doing something relatively lightweight, in which case those disadvantages start to weigh on you. You may be better off using PHP. From dlissett0 at yahoo.com Fri May 14 18:02:52 2004 From: dlissett0 at yahoo.com (Duncan Lissett) Date: 14 May 2004 15:02:52 -0700 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> <Xns94E8683D9EEF2duncanrcpcouk@127.0.0.1> Message-ID: <6748553f.0405141402.200fe0eb@posting.google.com> Duncan Booth <me at privacy.net> wrote in message news:<Xns94E8683D9EEF2duncanrcpcouk at 127.0.0.1>... -snip- > Next most obvious thing is to junk the linked lists and replace them with > ordinary Python builtin lists. After the Packet links were replace with a Python list the code was ~1% slower... > Replace the traceOn variable with __debug__ so you get the same benefits as > compiled languages by optimising out the test for the trace statements. Using __debug__ made the code ~1% faster > Remove the pointless set/get methods and just access the members directly. As a special dispensation to Python, directly accessed Packet and Tcb fields, ~10% faster > Avoiding multiple accesses to the same instance variable, or assigning to > instance variables until you are about to return from a method: use a local > during the execution of the method. Seems we're pushing into code optimization rather than not coding badly. Being careful about the tests in conditionals, and reordering some conditionals sped things up some more. (I should roll the same changes into the other langauge implementations.) The OO style implementation took 104.4s and now takes 87.1s I took the OO style implementation, made the methods of the scheduler class into functions, made the fields into globals, and made the Task class run methods into top-level functions. The C style implementation took 114.9s and the OO conversion takes 80.3s http://www.lissett.com/ben/bench3.htm Further suggestions are welcome (yes, I will try pysco later) From donn at u.washington.edu Fri May 7 15:52:34 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 May 2004 12:52:34 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <c7f6fj$aok$1@panix1.panix.com> <997a06e0.0405071007.3b903c7b@posting.google.com> <mailman.348.1083956045.25742.python-list@python.org> Message-ID: <donn-4D0925.12523407052004@nntp2.u.washington.edu> In article <mailman.348.1083956045.25742.python-list at python.org>, Gary Herron <gherron at islandtraining.com> wrote: > On Friday 07 May 2004 11:07 am, pugnatio2 at yahoo.com wrote: ... > > The deprecation I read, about avoiding type() (p. 129 of _Python in a > > Nutshell_) said it interfered with (true) polymorphism (via > > inheritance). > > That deprecation is correct. Instead of using type(), use > isinstance(param, type). > > The call to isinstance returns True if param is an instance of the > given type or any subtype thereof. This works correctly for > inheritance, giving you the polymorphism you want. Subtype polymorphism! Is that how it works in Python, though? >>> f = open('x', 'r') >>> import StringIO >>> s = StringIO.StringIO('contents ...') >>> t = type(f) >>> t <type 'file'> >>> isinstance(s, t) 0 Who cares if it's a subtype? Donn Cave, donn at u.washington.edu From me at privacy.net Wed May 12 16:51:48 2004 From: me at privacy.net (Duncan Booth) Date: 12 May 2004 20:51:48 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> <du7hdum415y.fsf@amadeus.cc.tut.fi> <slrnca3t0e.2asc.kirk@eyegor.jobsluder.net> <Xns94E78860DF4B5duncanrcpcouk@127.0.0.1> <8gisf1ihvc.fsf@galapagos.bx.psu.edu> Message-ID: <Xns94E7DE615EDFDduncanrcpcouk@127.0.0.1> Scott Schwartz <"schwartz+ at usenet "@bio.cse.psu.edu> wrote in news:8gisf1ihvc.fsf at galapagos.bx.psu.edu: > Duncan Booth <me at privacy.net> writes: >> import sys >> for line in sys.stdin: >> line = line[:-1].split('\t') >> print "%s %s %s %s" % (line[3], line[2], line[1], line[0]) > >> While I agree with you that using the appropriate tool is preferred >> over using Python for everything, I don't really see much to choose >> between the Python and awk versions here. > > 1) Python throws an error if you have less than three fields, > requiring more typing to get the same effect. I would rather have the error when the input isn't formatted as expected. The alternative would be incorrect output. If you really want to suppress the error then: line = (line[:-1]+'\t'*3).split('\t') > > 2) Python generators on stdin behave strangely. For one thing, > they're not properly line buffered, so you don't get any lines until > eof. But then, eof is handled wrongly, and the loop doesn't exit. True, if you are trying to reformat interactive input. I had assumed that the use case here was redirecting input from a file, and in that case the EOF problem isn't an issue. Buffering may or may not be a problem. > > 3) There is no efficient RS equivalent, in case you need to read > paragraphs. In that case I would write a generator to group the lines. Longer than RS, but also more flexible. From johnathan_doe at _NOSPAM_fastmail.com.au_I_SAID_NO_SPAM! Sun May 23 07:23:19 2004 From: johnathan_doe at _NOSPAM_fastmail.com.au_I_SAID_NO_SPAM! (Johnathan Doe) Date: Sun, 23 May 2004 21:23:19 +1000 Subject: Issues in compiling Python to machine code Message-ID: <40b089a5$0$16599$5a62ac22@freenews.iinet.net.au> I've been thinking about what the issues would be in compiling Python into native machine code, and since type information is important in Python, it seems possible that Python code can be compiled into native machine code (albeit with a lot of extra effort). For instance, type information is discovered when something is assigned to a variable or an anonymous piece of data is used in a program. Compiling Python bytecode into native machine code could involve a pass over the bytecode to look at all the uses of a variable or anonymous variable, call some Python function to discover its variable, then record it in the symbol table. Another issue is what to do with objects. Finding the offset to a pointer which is the object's constructor, for instance, if that's the way it's done internally in Python. And then freeing the memory used by an object when it's no longer needed. Perhaps freeing memory for an object can be done by inserting machine code to return memory back to the heap after the first pass over the bytecode and recording the place a variable is last used (hopefully then it won't be used in some other way later of course... perhaps it can record all cases where that variable is referred to by another name and track them, too.) Seems like compiled Python would need a lot of support code, in any case, that gets run at certain times: before the program starts, whenever a variable is accessed, before an object is used (to allocate memory), whenever something happens to data within an object (allocate/reallocate/destroy), and so on... Are there any reasons why Python would be *impossible* to compile? Thanks :) From miki.tebeka at zoran.com Mon May 24 02:47:05 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 24 May 2004 08:47:05 +0200 Subject: Freeze and Resume execution In-Reply-To: <20040523141548.DF35.SLAWEK@cs.lth.se> References: <20040523115548.DF2E.SLAWEK@cs.lth.se> <20040523131353.GS1916@zoran.com> <20040523141548.DF35.SLAWEK@cs.lth.se> Message-ID: <20040524064705.GY1916@zoran.com> Hello Slawomir, > def output_gen(bits): > size = 0 > for bit in bits: > send_one_bit(bit) # HW call > size += 1 > if size == OUT_BUFFER_SIZE: > yield "BufferFull" # use yield instead of raise here > size = 0 > > generator = None > def output(): > res = generator.next() > if res == "BufferFull": raise BufferFull > > def sendall(bits): > global generator > generator = output_gen(bits) > while True: > try: > output() > except BufferFull: > print "Emptying buffer" > except StopIteration: > print "Done sending" > break > > def test(): > sendall("1234567890123456789012") > > ********************************************************************** > > Catching BufferFull and calling output() doesn't need to be in > sendall() function, it can basically be anywhere you want it to be. > > Does this do what you want it to do? It's not a complete solution but improves things *very much*. Thanks! -- ------------------------------------------------------------------------- Miki Tebeka <miki.tebeka at zoran.com> http://www.cs.bgu.ac.il/~tebeka The only difference between children and adults is the price of the toys. From peter at engcorp.com Tue May 25 00:49:00 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 25 May 2004 00:49:00 -0400 Subject: smtplib data error In-Reply-To: <37zsc.16577$SQ2.1218@edtnps89> References: <exrsc.16505$SQ2.3515@edtnps89> <mailman.240.1085433868.6949.python-list@python.org> <37zsc.16577$SQ2.1218@edtnps89> Message-ID: <yrmdnS8MuLSgTS_dRVn-jg@powergate.ca> yazzoo wrote: >>> Traceback (most recent call last): File "test-py.cgi", line 790, in ? >>> sendemail(EmailFrom, EmailTo, emsg) File "test-py.cgi", line 20, in >>> sendemail failed = server.sendmail(EmailFrom, EmailTo, emsg) File >>> "/usr/lib/python2.2/smtplib.py", line 685, in sendmail raise >>> SMTPDataError(code, resp) smtplib.SMTPDataError: (550, 'Administrative >>> prohibition') >> > The traceback above though seems to suggest that smtplib uses sendmail No it doesn't. Rather it suggests there is a method on the server object called sendmail() and that it is raising the exception shown. You can check the source: smtplib.py is right there on your hard drive. -Peter From tdelaney at avaya.com Tue May 25 01:50:32 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 25 May 2004 15:50:32 +1000 Subject: Useful? __slots__ for functions Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0187FF2E@au3010avexu1.global.avaya.com> Nick Jacobson wrote: > The __slots__ attribute of new-style classes can reduce memory usage > when there are millions of instantiations of a class. > > So would a __slots__ attribute for functions/methods have a similar > benefit? i.e. could a function using __slots__ use significantly less > memory, and therefore run faster, if called millions of times? If you're talking about local names being in an indexed array (or __slots__) then the time machine has got you. Local names in functions (or rather, code objects) are resolved using a simple index rather than a dictionary lookup. Tim Delaney From Harald.Schreiber at t-online.de Sun May 23 14:43:29 2004 From: Harald.Schreiber at t-online.de (Harald Schreiber) Date: Sun, 23 May 2004 20:43:29 +0200 Subject: Problem concerning pyparallel Message-ID: <c8qqp4$u1$01$1@news.t-online.com> Hi, When trying to install the pyparallel-software under Windows98SE I got an errormessage about a missing cl.exe. Can someone there out give me some explanations? Harald Schreiber From max at alcyone.com Mon May 24 15:22:54 2004 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 May 2004 12:22:54 -0700 Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> <m2k6z1ejcc.fsf@unique.phony.fqdn> Message-ID: <40B24B8E.39F77A11@alcyone.com> Heather Coppersmith wrote: > Also, modern day cryptography applications can demand integer/ > logical operations on 256-, 512-, or more- bit (upwards of 1e150) > integers. Also, number theorists certainly would care. -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ A war at sea. A war with no battles, no monuments ... only casualties. -- Capt. Marko Ramius From NOmanlio_perilloSPAM at libero.it Sat May 15 02:51:19 2004 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 15 May 2004 06:51:19 GMT Subject: PEP: import version References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> <mailman.503.1084435759.25742.python-list@python.org> Message-ID: <bafba0tarf4vrsr6oob5nnaht9gp2mrcm2@4ax.com> On Thu, 13 May 2004 18:07:27 +1000, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote: >On Thu, May 13, 2004 at 07:46:51AM +0000, Manlio Perillo wrote: >[...] >> A possible syntax is this: >> import wxPython version '2.4' > >I'd like to see versioned imports too, but it looks like a tricky problem to >me. Some questions that immediately spring to mind reading your proposal: > >How would this work with from X import Y? How would this work with packages >(e.g. import X.Y.Z)? > >e.g. how would you add version requirements to these statements: > > from gtk import main > I see a simple solution: from gtk version '2.0' import main It should be up to gtk root module (ex __init__.py) to decide what version of sub modules to load. >But what about the second one -- can only top-level modules/packages have >versions? e.g. what if the "twisted.web" package has a version that's >independent of the top-level "twisted" container package? Would "from >twisted.web version '1.3.0'" mean Twisted version 1.3.0, or Twisted Web >version 1.3.0? > The sub-level packages have version too. In example: twisted version 1.3.0 -> web version 1.1 twisted version 1.3.5 -> web version 1.1 twisted version 1.4.0 -> vew version 1.2 The right sub module version to load is decided by the top level module. In detail (using a single file for all versions): __init__.py if __version__ == '1.4.0': __all__ = [ ('web', '1.2'), ... ] elif __version__ == '1.3.5': _all = [ ('web', '1.1'), ... ] That is, the items of __all__ should be tuples. >What happens if the same program tries to import different (and possibly >conflicting) versions of the same module, e.g.: > > import gtk version '2.0' > import gtk version '1.2' > >Should an ImportError be raised? Should it succeed (assuming both versions >are available)? Is it even possible to have two different versions of the >same library/module installed in parallel, and if so, how? It should unload gtk version 2.0 and load the version 1.0 Regards Manlio Perillo From Chris.Hornberger at blackrock.com Wed May 12 15:06:53 2004 From: Chris.Hornberger at blackrock.com (Hornberger, Chris) Date: Wed, 12 May 2004 15:06:53 -0400 Subject: if Request("something") == None: doesn't work Message-ID: <ABADC7F2A1794A4C94657344DC1050930648BB36@BRDEL-EXCH02.na.blkint.com> how about if not Request("something"): ... ? -------------------------- Chris Hornberger Blackrock - 302.797.2318 chris.hornberger at blackrock.com Card carrying MSDN member since 2004. No, really. I've got the card to prove it. -----Original Message----- From: python-list-bounces+chris.hornberger=blackrock.com at python.org [mailto:python-list-bounces+chris.hornberger=blackrock.com at python.org]On Behalf Of Kirk Strauser Sent: Wednesday, May 12, 2004 2:55 PM To: python-list at python.org Subject: Re: if Request("something") == None: doesn't work -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 At 2004-05-12T17:12:00Z, "Sam Sungshik Kong" <ssk at chol.nospam.net> writes: > if Request("something") == None: Have you tried: if Request("something") is None: > if str(Request("something")) == "None": Well, right. repr(None) == 'None'. > if len(Request("something")) == 0: > works! That seems kinda strange, granted. - -- Kirk Strauser The Strauser Group Open. Solutions. Simple. http://www.strausergroup.com/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) iD8DBQFAonJC5sRg+Y0CpvERAvRPAJ0Uojjx9qMtOHKApnDMnt3TxsL5ngCgnKWG ejWI7Ycj5asnK9WsoWL11Eo= =bL+r -----END PGP SIGNATURE----- -- http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Thu May 20 11:12:45 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 May 2004 11:12:45 -0400 Subject: alternatives to making blocks like { } or other ?? References: <c8do0u$9fb$1@news.atman.pl><jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com><c8e5sh$109b$1@news.atman.pl><slrncalqqf.8f2.grante@grante.rivatek.com><sjDqc.108220$NR5.92596@fe1.texas.rr.com> <9ace45f.0405200616.7e5110ba@posting.google.com> Message-ID: <c8ihte$fro$1@sea.gmane.org> "Andrei Smirnov" <asmirnov1234567890 at yahoo.com> wrote in message news:9ace45f.0405200616.7e5110ba at posting.google.com... > Please, Python writers, do provide braces as compatibility mode. The Python developers are all volunteers working on the parts of the language they find interesting or at least tolerable. There plates are completely full with a backlog of requested bugfixes and feature or module additions. If *you* want something different (Braython?), you can get together with the other brace advocates and either do it yourselves or hire someone. The source code is available and the license permissive. Terry J. Reedy From Joseph.V.Laughlin at boeing.com Mon May 17 19:30:14 2004 From: Joseph.V.Laughlin at boeing.com (Laughlin, Joseph V) Date: Mon, 17 May 2004 16:30:14 -0700 Subject: Timer events Message-ID: <67B3A7DA6591BE439001F2736233351202B47A65@xch-nw-28.nw.nos.boeing.com> If I want a function to be called every second, how would I do this? Would I use timer events? Joe Laughlin Phantom Works - Integrated Technology Development Labs The Boeing Company From vineet at eswap.com Wed May 19 19:51:56 2004 From: vineet at eswap.com (Vineet Jain) Date: Wed, 19 May 2004 19:51:56 -0400 Subject: Help with large data set and fatal python error (pysqlite) In-Reply-To: <c8goj2$s92$1@sea.gmane.org> Message-ID: <KPENJIMKHJPNKOLFIHBNEEAGCKAA.vineet@eswap.com> I've tried to close all the db connections after I use them and still et the problem. I still get the problem if I add: cur = None conn.close() after I retrieve each reult set. -----Original Message----- From: python-list-bounces+vineet=eswap.com at python.org [mailto:python-list-bounces+vineet=eswap.com at python.org]On Behalf Of Terry Reedy Sent: Wednesday, May 19, 2004 5:54 PM To: python-list at python.org Cc: pysqlite-users at lists.sourceforge.net Subject: Re: Help with large data set and fatal python error (pysqlite) "Vineet Jain" <vineet at eswap.com> wrote in message news:KPENJIMKHJPNKOLFIHBNKEPNCJAA.vineet at eswap.com... > I've been able to recreate the problem with the following code segment. It > seems that the problem comes when you have multple db files open at the same > time. In my application I have many database files open at the same time. > I'm not using threads so all access to the db files are done sequenetially. > > At the end of the program I get the following error: > > Fatal Python error: deallocating None > > This application has requested the Runtime to terminate it in an unusual > way. > Please contact the application's support team for more information. Have you done so? In this case, the 'application' is, it would seem, sqlite. > If I change the numInnerLoop to 5, 10, 20, or 30 it works however anything > over 35 gives the above error. In my actual application, when run for a > larger set, the error can come in the middle of the program and is causing > me a lot of grief. Do the docs for sqlite specify max open connections? If not, maybe send them your example. If so, ask if limit can be raised. In the meanwhile, stay under it. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list From kdahlhaus at yahoo.com Thu May 13 14:39:59 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 13 May 2004 11:39:59 -0700 Subject: Real-time graphs References: <mailman.463.1084375754.25742.python-list@python.org> <40a35edb$0$16606$5a62ac22@freenews.iinet.net.au> Message-ID: <283adf56.0405131039.10801c77@posting.google.com> It looks sharp, but the free version has watermarks and is distributable only in free software. From deetsNOSPAM at web.de Mon May 17 08:24:40 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 17 May 2004 14:24:40 +0200 Subject: Binary handling References: <2gro06F5ti55U1@uni-berlin.de> Message-ID: <c8aauf$78h$03$1@news.t-online.com> Derfel wrote: > Hello all, > I have a file of binary data. I want to read this file and parse the data > in it. The format of the file is: > 8 bits number of data pakets > 6 bits offset > 20 bits time > 8 states > > How can I read this fields in binary? I see the struct module and the > binascii, but I can't split the diferent fiels. You can use struct to create a long from your data and then work on that with the usual bitwise operators for shift and boolean and so that you extract the actual data. If the above is the entire spec, I see some problems to get the alignment proper, but with a bit of shifting you should be able to work around that. -- Regards, Diez B. Roggisch From dai4happy at yahoo.com Sat May 8 05:51:09 2004 From: dai4happy at yahoo.com (angel) Date: Sat, 8 May 2004 17:51:09 +0800 Subject: Help me. How to open a new IE window? Message-ID: <c7iaqu$2400$1@news.f.de.plusline.net> Hi I want python(win32com) to open a new IE window. Source is: /******/ import win32com.client msie = win32com.client.Dispatch("InternetExplorer.Application") msie.Visible = 1 msie.Naviagte(http://www.python.org) /******/ The problem is the program always grabs a existed IExplorer window or Explorer window. It never opens a new window. Please help me. Thanx Victor From mike at edey.mine.nu Mon May 31 10:14:59 2004 From: mike at edey.mine.nu (Mike Edey) Date: Mon, 31 May 2004 14:14:59 GMT Subject: [].index Message-ID: <pan.2004.05.31.14.14.56.340200@edey.mine.nu> Good day. Recently I'd run into wishing a list's index method would match substrings. Being fairly new to this game I can't help but think that my solution is a little, well, clumsy. In the following trivial example I'm only interested in finding the first matching list item: >>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo = >>> ['b','e','e'] >>> [data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for >>> ix in range(len(foo))] ['bbb', 'eee', 'eee'] So I guess this question is - have I missed a cleaner method then this nested list comprehension? From andrew-pythonlist at puzzling.org Fri May 7 04:15:46 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Fri, 7 May 2004 18:15:46 +1000 Subject: Scope rule pecularities In-Reply-To: <20040507073753.GE24597@frobozz> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <20040507073753.GE24597@frobozz> Message-ID: <20040507081546.GF24597@frobozz> I wrote: [...] > > You can't do the operation in-place with immutable values such as numbers > and tuples, though. So to make "x += 1" work (where is is some integer), ^^ Obviously I meant to say "x" here. -Andrew. From seefeld at sympatico.ca Thu May 27 09:22:50 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 27 May 2004 09:22:50 -0400 Subject: how does CPython work? In-Reply-To: <3064b51d.0405260703.43634439@posting.google.com> References: <3064b51d.0405260703.43634439@posting.google.com> Message-ID: <J0mtc.48923$tb4.1687542@news20.bellglobal.com> beliavsky at aol.com wrote: > The book "Learning Python" says that a "Python Virtual Machine" > interprets "byte code" to run a Python program. Is there a book or > site that describes in more detail what Python is doing behind the > scenes? One reason for my question is that I want to better understand > what kinds of Python programs run relatively fast or slow, rather than > relying solely on trial and error. beside what has already been said concerning code execution you should get familiar with python's object model to understand what a method call implies, for example. Symbols are looked up in dictionaries (all method objects are usually accessed through an instance's '__dict__' dictionary for example), so being careful with the related issues will help you profile and optimize your code, too. Regards, Stefan From eriksp at attbi.nospam.com Fri May 21 18:42:16 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 21 May 2004 22:42:16 GMT Subject: Command Prompt References: <Cnurc.5$hi6.3519@attbi_s53> <mWurc.17$Fa1.14@news01.roc.ny> Message-ID: <cBvrc.5514$JC5.574553@attbi_s54> Depend on the operating system or the computer? The two OS I use are Windows XP Pro and Windows NT 2000 Pro. From rxv at hotmail.com Sun May 30 18:12:40 2004 From: rxv at hotmail.com (Ike) Date: Sun, 30 May 2004 22:12:40 GMT Subject: Jython Forum References: <10bk67t3t6sqp4b@corp.supernews.com> Message-ID: <s%suc.17264$be.14572@newsread2.news.pas.earthlink.net> Its a great idea - badly needed too! "Maboroshi" <n/a> wrote in message news:10bk67t3t6sqp4b at corp.supernews.com... > Just thought I would let everyone know of my Jython Forum I couldn't really > find one specific to Jython so I set this up > > if anyone wants to contribute anything visit http://www.pacificflame.com > > and if you think its a stupid idea let me know > > if you have any ideas for the forum please post to this message > > From insert at spam.here Wed May 19 00:40:53 2004 From: insert at spam.here (Doug Holton) Date: Tue, 18 May 2004 23:40:53 -0500 Subject: MFC application and Python In-Reply-To: <2410357897.20040519033752@smtp.myrealbox.com> References: <2410357897.20040519033752@smtp.myrealbox.com> Message-ID: <OYednfL0WrDKeDfdRVn-sQ@comcast.com> Adal Chiriliuc wrote: > I'm working on a C++ Win32 MFC application and I want to move as much > code as possible to Python. > > At first I wanted to use a Python GUI package and keep the critical > components (performance wise) in C++ extensions. The application must > have a native look so this leaves us with only two choices. > > wxPython is way too bloated (9 MB on disk, 20MB! in memory for basic > stuff) and people say buggy. PythonWin is nice and small, but lacks > some features, like GDI support. If you're already coding in C++, and think wxPython is too bloated, and you were prepared to use pythonwin (win32gui) if only it had more features, then I'd say stick with C++, it's not much more difficult than using win32gui and will allow you to make your application as fast and lightweight as you like. But if you seriously want to switch to Python, then I'd reconsider wxpython. It is the best python GUI toolkit for your specific purposes I think. It isn't buggy. From dmq at gain.com Tue May 25 06:41:02 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 03:41:02 -0700 Subject: Unification of Methods and Functions References: <slrnca6d58.1i9.apardon@trout.vub.ac.be><mailman.516.1084460227.25742.python-list@python.org><3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com><mailman.186.1085249459.6949.python-list@python.org> <66ava0hb9pngr25b3m5t7f972u665lcjbc@4ax.com> <mailman.188.1085259396.6949.python-list@python.org> <pku0b0hh06hqng3b5kdjk690tt2cars7m7@4ax.com> <2hd5ihFaefmmU1@uni-berlin.de> <ukp4b01o1lfgh2h4b3e0qc40a9bc2ck30c@4ax.com> <2hft17Fc8642U1@uni-berlin.de> Message-ID: <ts76b0hqsqd3v0udef6blf9d2j1hmibbu8@4ax.com> On Tue, 25 May 2004 15:31:49 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: >David MacQuigg wrote: >> My perspective may be different, because I have not yet absorbed the >> Python traditions, and I don't have any instictive avoidance of static >> methods. > >Are you coming at this from a Java perspective? In Java >(and in C++ until recently) you're forced to use static >methods, because the class is the only kind of namespace >available. I studied Java a little bit two years ago, but not enough to absorb any bias toward static methods. >But Python has modules for use as general-purpose >namespaces. Classes are thus relieved of the burden >of performing this double duty, leaving them free to >concentrate on what they do best, which is defining >the behaviour of a collection of objects. I hesitiate to waste a whole level of packaging on just tying static methods to their classes. A distribution of our circuit-design platform might have a bunch of classes in a module for netlisting. That module might be part of a complete package for a particular simulator. I suppose I could subdivide the module into smaller packages, but it seems awkward. Maybe if we could have more than one module per file. Files would then be one more level in the packaging hierarchy. I still prefer to just add the staticmethod line and leave the method where I first put it - in the class to which it applies. >I really recommend that you *use* Python for long >enough to get a good feel for it, before attempting >to revise it. Trying to reform something that you >don't thoroughly understand is fraught with danger. OK with me. Looks like there is no rush on Python 3. In about three months I should have double the experience with Python I have now. -- Dave From andymac at bullseye.apana.org.au Mon May 17 09:11:05 2004 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Mon, 17 May 2004 23:11:05 +1000 (EST) Subject: Test error with Python 2.3.4c1 In-Reply-To: <m2ad082xpb.fsf@pchoel.psh> References: <m2fza1h6ka.fsf@pchoel.psh> <m27jvdh5k6.fsf@pchoel.psh> <c85sdb$802$1@panix3.panix.com> <m2vfixfnc3.fsf@pchoel.psh> <c866s7$fp0$1@panix2.panix.com> <m2ad082xpb.fsf@pchoel.psh> Message-ID: <20040517225306.V64722@bullseye.apana.org.au> On Sun, 16 May 2004, Berthold H?llmann wrote: > > caused some changes to the way sre operates, so it was a non-starter for > > the 2.3.x series. > > > > Anyway, please close your bug with a note about it being fixed in 2.4 > > CVS. As for the other issue, I don't have enough time/energy to even > > understand what the issue is. Given that it's about SAX, I suggest you > > start a new thread and hopefully someone else will pick it up. > > OK, I closed the bug, but still would like to see USE_RECURSION_LIMIT > default reduced to something like 6500 (3000 seems to be OK for > FreeBSD on sparc64, so I guess this can't be a behavioral change). Prior to 2.4, sre is recursive. Recent versions of gcc (in particular) at higher optimisation levels are generating much larger stack frames than used to be the case. This is even moreso the case with 64-bit platforms. In the particular case of FreeBSD 4.x, in the presence of threads (the default build choice, using libc_r) there is a hard coded stack size of 1MB, which leaves this environment especially sensitive to stack frame size. The alternative threads libraries (libkse/libthr) available on 5.x are less affected, but I don't know to what extent (& Python's configure script doesn't know about them that I've heard). I've seen reference to the problem on Linux, but I don't know why that platform is (apparently) short on stack. This is a highly platform/compiler dependant issue, which is why the maze of #ifdef'ery for USE_RECURSION_LIMIT - something that has only happened since about Python 2.3.1 as I recall. The most effective solution with recent gcc versions is to recompile sre.c with -Os (instead of -O3). It is unfortunately awkward to implement with autoconf. The non-recursive sre in 2.4 is a complete fix, but is too extensive/invasive a change for back-porting for a bug-fix release. -- 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 noamr at correctme.users.sourcephorge.net Wed May 26 16:45:43 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Wed, 26 May 2004 23:45:43 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: <mailman.231.1085421255.6949.python-list@python.org> References: <c8l3s3$27o$1@news.iucc.ac.il> <r6-dnZ3iwqgNETPdRVn-uQ@comcast.com> <c8of2o$o5k$1@news.iucc.ac.il> <mailman.231.1085421255.6949.python-list@python.org> Message-ID: <c92vln$61l$1@news.iucc.ac.il> Fredrik Lundh wrote: > Noam Raphael wrote: > > >>I have to write: >>picture[s2i(picture[10:14]):s2i(picture[10:14])+4] >>I think this is nicer (and quicker): >>picture[s2i(picture[10:>4]):>4] > > > that's spelled > > picture = Image.open(file) > picture.getpixel((0, 0)) > > </F> > > > > Hello, Thanks for your suggestion, but I meant to give an example for the need of those slices when handling files of a format which is not already handled by a module someone wrote. And what if I want to write a new module for handling images? Noam Raphael From python at quixs.com Sat May 8 09:35:34 2004 From: python at quixs.com (Lars Heuer) Date: Sat, 8 May 2004 15:35:34 +0200 Subject: Calling constructor of unknown classes In-Reply-To: <109pnotf49o0m7b@news.supernews.com> References: <mailman.357.1084020587.25742.python-list@python.org> <109pnotf49o0m7b@news.supernews.com> Message-ID: <477266762.20040508153534@quixs.com> Hi John, > Since you know the module (you just imported it), do something > like this: > klas = getattr(mod, "className") > instance = klas() Thanks. I tried something similar, but instead of my way, your way works. ;) Best regards, Lars From blugerz at yahoo.com Fri May 21 18:34:55 2004 From: blugerz at yahoo.com (Brian) Date: 21 May 2004 15:34:55 -0700 Subject: Python Newbie Message-ID: <3c0a04e4.0405211434.6667f727@posting.google.com> Hi I am new to this newsgroup and new to programming. I have had this interest in learning to program because.......well just because. It's just a curiosity that I have. The reason I am starting with Python, well some of the websites I went to recommended Python, so here I am. Ok on to the question. I am currently using the book "Python programming for absolute beginners" by Michael Dawson. The program I am working on is a password program....dont laugh I know it's really simple to some, but I am kinda stuck. The book shows how to code a password program like this: password = raw_input("Enter your password:") if password == "secret": print "Access Granted" else: print "Access Denied" raw_input("Press the enter key to exit") Ok that is easy enough I understand what is going on here. As the book goes on it also talks about elif, and while loops. At the end of the chapter it gives various challenges that the reader is asked to complete. One of the challenges is to take the password program from above and change it so that the user gets only three attempts to enter the correct password. Well I ain't got it to work yet, I thought I came close, but no cigar. This is what I have so far: #Limiting password atempts to three password = raw_input("Enter your Password: ") count = 0 while password != "secret": print password = raw-input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count > 3: print "Please come back when you remember your Password." else: raw_input("Press enter to exit.") Ok, I know I may be way off course here but any help would be greatly appreciated. I dont want to get frustrated and say the heck with it, especially if it is something minor. Thanks in advance. From jeffbarish at starband.net Thu May 20 11:44:04 2004 From: jeffbarish at starband.net (Jeffrey Barish) Date: Thu, 20 May 2004 09:44:04 -0600 Subject: Tkinter: update_idletasks Message-ID: <c8ijo9$l2n$1@sea.gmane.org> I'm confused about how to use the update_idletasks method. In my program, I have a handler for a button in which execution will linger. During that time, I would like for the GUI to continue to show signs of life. I have a Pmw MessageBar in which I display a status message. I figured out that if I run update_idletasks on that MessageBar, then the MessageBar will update the display as I update the message. However, if I cover the GUI with some other window and then expose it again, the GUI does not refresh until the handler finishes (except for the MessageBar). Do I have to run the update_idletasks method for every widget in the GUI? for all the frames? for just the root frame? Or is it impossible to get the GUI to refresh in this situation? -- Jeffrey Barish From antonio.p2 at llibero.it Wed May 19 15:12:16 2004 From: antonio.p2 at llibero.it (Antonio.P) Date: Wed, 19 May 2004 19:12:16 GMT Subject: Zope file upload size limit Message-ID: <kkOqc.295123$rM4.12386560@news4.tin.it> Hi to all. I am using an html form to upload files to zope. I'd like to limit the max upload size to 3Mb but I haven't found anything on the manual about it. Is it possible to put this limit? Thank you. From skip at pobox.com Sat May 15 12:17:17 2004 From: skip at pobox.com (Skip Montanaro) Date: Sat, 15 May 2004 11:17:17 -0500 Subject: where is Python Tools/scripts directory? In-Reply-To: <95aa1afa.0405142203.7dd64fad@posting.google.com> References: <95aa1afa.0405142203.7dd64fad@posting.google.com> Message-ID: <16550.17037.701031.85232@montanaro.dyndns.org> Michele> Is there a simple way to get the path to the Python Michele> Tools/scripts directory? Currently I have defined by hand an Michele> environment variable such as Michele> PYTHONSCRIPTS=/home/myhome/packages/Python-2.3.3/Tools/scripts Michele> so I can alias the more useful scripts in my .bashrc (for Michele> instance alias dutree=$PYTHONSCRIPTS/dutree.py), but this Michele> approach is PITA, I have to change the variable each time I Michele> change machine and at each new Python version. Is there a Michele> better way? I'm not aware of a better way short of identifying those scripts of interest and modifying setup.py to install them in $PREFIX/bin. In setup.py search for "Tools/scripts" and modify the list. Feel free to submit a patch to SF if you think those scripts would be of broader interest and ought to be installed by default. Skip From anthony at interlink.com.au Mon May 31 11:39:02 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 01 Jun 2004 01:39:02 +1000 Subject: pre-announce: Python 2.4a1 is about a month away Message-ID: <40BB5196.7070207@interlink.com.au> This is a pre-announcement that the first alpha of Python 2.4 is about a month away. The purpose of this notice is to give people a heads up - if you have a bug that you want to see fixed for 2.4, start looking at it now. Fixes are welcome through the release cycle, although after the first beta fixes that result in a change to behaviour will be much less likely to be accepted. So, if you have a bug you want to see fixed, what should you do? - If it's not logged on SF, log it. - If it's logged, consider adding a patch that fixes the problem, or at least a simple test case that demonstrates the bug. - If someone else has supplied a fix, see if this fix works for you, and post your results to the bug. - If there's a working fix, feel free to add a note asking for the fix to go into CVS. The SF bug tracker for Python has a _lot_ of bugs in it, and it's easy for bugs to be overlooked. If you're just interested in what's coming up in 2.4, see the current development version of the "What's New in 2.4" document at http://www.python.org/dev/doc/devel/whatsnew/whatsnew24.html On behalf of the python-dev team, thanks! Anthony [This form of pre-announcement will hopefully become a part of the release process for all future releases of Python, both major and bugfix releases, to give people a chance to get their bugfix-of-choice submitted in time. Any feedback on this process, please feel free to email me] -- Anthony Baxter <anthony at interlink.com.au> It's never too late to have a happy childhood. From guettli at thomas-guettler.de Tue May 25 11:01:38 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 May 2004 17:01:38 +0200 Subject: Search and extract text in MS Word References: <6324c8b6b4429042467b0331f254b7be@localhost.talkaboutprogramming.com> Message-ID: <pan.2004.05.25.15.01.38.33695@thomas-guettler.de> Am Tue, 25 May 2004 09:30:07 -0400 schrieb questioner: > Hello everyone, > > I want to find text and extract a rest of line after the found line till > line end. > Does anyone know how to do this? Hi, I use wvware to extract the plain text of ms-word. Then you can use the string methods of the standard library. This way you don't need win32 and it can run on unix, too. http://wvware.sourceforge.net/ HTH, thomas From tismer at stackless.com Sun May 16 11:51:13 2004 From: tismer at stackless.com (Christian Tismer) Date: Sun, 16 May 2004 17:51:13 +0200 Subject: Stackless python and microthreads In-Reply-To: <1084504249.836501@yasure> References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <osGdnfGC2oRcsTndRVn-tw@powergate.ca> <1084504249.836501@yasure> Message-ID: <40A78DF1.7020401@stackless.com> Donn Cave wrote: > Quoth Peter Hansen <peter at engcorp.com>: > | Mike C. Fletcher wrote: > | > | > continuations are the most awesome toys > | > you can imagine... we will all mourn their passing in time... > | > | Will that be _before_, or _after_ we understand what they are? ;-) > > I gave them a try, and I mourn them with a touch of relief, I guess. > I'm the guy who won't bother to learn list comprehensions and generally > despises cool gimmicks, but continuations were more than just cool, > they were terribly powerful. Yes. And terribly hard to maintain as well :-) > I hooked them into a graphics toolkit wrapper with an event dispatching > model where each window, network connection etc., ran in its own native > thread. No blocking, always ready to respond to a new message. When a > couple of these threads have to interact, they would queue messages back > and forth, and the programming paradigm can get awkward - a lot of state > can pile up as everyone's trying to keep track of their progress through > some kind of procedure. > > Well, suppose you send your message and save the whole function state > somewhere, and return to the dispatcher. When the response comes back, > you pick up the function state and continue it, feeding the response in. Ok, that's a nice pattern which I use as well, *with* current Stackless and *without* continuations. Turning control flow inside out does not depend upon continuations. You just need the ability to switch contexts, which is in fact much less, but buys you a lot more. A continuation is immutable. That means it can be activated multiple times and it will not change state. How to explain this? Well, consider a Python function, and you have several continuations captured from that running function. Then you can jump at any continuation at any time, as often as you like. This capability is incredible, but I never saw an example of code that *really* had to have this feature. Returning to some point in the running program and continuing there is what most people need. This is less than a general continuation, because the continuation is gone after resuming. You can call it a one-shot continuation. On every context switch, the current continuation is preserved, but it is never fired twice. This is very much like threads. Full continuations enforce that you have complete control over the current program, especially you need to be able to track all object references which must stay alive in a continuation. This is not possible if your program state contains hidden objects on the C stack, because we have no introspection feature in the Python C implementation. In other words: You cannot use continuations in the context of C extensions. Restricting ourselves to one-shot continuations, we don't need to track any objects explicitly. This makes it possible to deal with hidden objects just by saving and restoring parts of the C stack. And this makes tasklets more powerful that the old continuations: it is possible to switch context all the time. The program environment does not need to collaborate. Collaboration is more efficient (i.e. trying to leave no state on the C stack), and Stackless tries to do it almost everywhere. But that's not a limitation. You can write ordinary C code and ask Stackless to switch tasklets, and it will switch. I consider this more valuable than continuations which pretend to be universal and immportal, but only in a restricted context. > Now instead of a tedious kind of state machine, you're writing an plain, > ordinary function that sends messages to its peer and looks at the response, > as though that were all synchronous, and it's so much simpler. Yet the > execution underneath that isn't synchronous at all, because your computation > is suspended in between your send and the response. It really does return > every time it sends a message, it just starts up next time where it left > off. Exactly what I'm doing with Stackless. I have my own implementation of sockets and files, which pretend to have synchronized calls only, but under the hood they are asynchronous, dispatching over a poll/select loop and optimizing throughput. The code is much shorter than asyncore, and reasonably more effective if your server is computation-bound. Unfortunately I can't publish this module, yet, it was contract work. cheers - chris -- Christian Tismer :^) <mailto:tismer at stackless.com> Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From mark.pearse at skynet.be Tue May 11 13:14:41 2004 From: mark.pearse at skynet.be (Mark Pearse) Date: Tue, 11 May 2004 19:14:41 +0200 Subject: OT: Idea for Python T-shirt References: <ppj1a09ee7766t94o439qd2bgbc18resg1@4ax.com> <JpqdnYIeR4GMRT3dRVn-gg@powergate.ca> Message-ID: <40A10A01.3030502@skynet.be> Peter Hansen wrote: > Christos TZOTZIOY Georgiou wrote: >> "With Python your nibbles explode with desire" >> > > Also, I don't get it... > I think its a reference to the misleading Hungarian phrase book sketch! See, eg http://bau2.uibk.ac.at/sg/python/Scripts/TheHungarianPhrasebookSketch Mark, whose hovercraft is rapidly filling with eels From greg at cosc.canterbury.ac.nz Mon May 24 01:30:03 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 24 May 2004 17:30:03 +1200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <uQ8sc.12043$bF3.2078@fed1read01> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> <30260531.0405231227.24089c9f@posting.google.com> <uQ8sc.12043$bF3.2078@fed1read01> Message-ID: <2hdfj1Fbj2rtU1@uni-berlin.de> Mark Hahn wrote: > BTW: The 0.008 MB you are talking about either does nothing useful or is > just calling windows high-level routines. I assume maybe you are > exaggerating? I think it depends on what you mean by "useful". I imagine you could fit a lot of quite useful functionality into that much code, as long as you didn't require it to have a fancy GUI interface, etc. Heck, 8-bit micros used to fit an entire operating system and BASIC interpreter into 8-16KB or so... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From klachemin at home.com Thu May 27 00:01:21 2004 From: klachemin at home.com (Kamilche) Date: 26 May 2004 21:01:21 -0700 Subject: Inclusion Guards Necessary? References: <889cbba0.0405261147.3835adef@posting.google.com> <mailman.336.1085601714.6949.python-list@python.org> Message-ID: <889cbba0.0405262001.6badf537@posting.google.com> "Mike C. Fletcher" <mcfletch at rogers.com> wrote in message news:<mailman.336.1085601714.6949.python-list at python.org>... > No, multiple imports of a python module just do a lookup and return the > same module object as was returned by the previous import. Thanks! From colarte at telesat.com.co Tue May 25 11:23:45 2004 From: colarte at telesat.com.co (Camilo Olarte) Date: Tue, 25 May 2004 10:23:45 -0500 Subject: par files? (Russell Lear) Message-ID: <1085498625.40b3650126dac@ilpostino4.telesat.com.co> Why not use .zip files ??? What's new in python 2.3 : you can import from a zip file : http://www.python.org/doc/2.3.3/whatsnew/node5.html Camilo Olarte Telesat, m?s f?cil...m?s Internet. http://www.telesat.com.co/ From anton at vredegoor.doge.nl Fri May 28 07:58:23 2004 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 28 May 2004 13:58:23 +0200 Subject: accessing elements in multi-dimensional sequences References: <192ga7lzy3p56$.9s0j70tak09n$.dlg@40tude.net> Message-ID: <40b72a41$0$128$3a628fcd@reader3.nntp.hccnet.nl> Rodrigo Daunaravicius <rodelrod at hotmail.com> wrote: >Is there an elegant way to directly refer the 2nd dimension of a >multi-dimensional sequence (like the nth character in a list of strings). >An example would be deleting the newline in all the strings from a list >obtained through readlines without recurring to 'for' loops. d = ['0891931243\n', '0325443777\n', '0933477028\n', '0699624617\n', '0922210996\n'] #swap rows and columns, with the side effect of turning #strings into lists, strings must be of equal length or #else some information will be lost: d1 = zip(*d) #remove a row (corresponds to a *column* in the old view) #this is an elementary operation now: del d1[-1] #swapping again restores the old row and column view: d1 = zip(*d1) #join the elements of the sublists in order to produce strings: d1 = map(''.join,d1) print d1 #output is: #['0891931243', '0325443777', '0933477028', '0699624617', #'0922210996'] While this way of coding enables one to *think* about the problem more efficiently it is not necessarily the most efficient algorithm for accomplishing this specific effect. If it's fast enough however, why not reduce ones mental computing cycles and let the computer do all the leg work? It might even ameliorate entropy problems later on in the evolution of the universe since the operations could probably be reversed more efficiently even if the computer moves more electrons through the silicon? Anton From jepler at unpythonic.net Mon May 17 07:33:29 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 17 May 2004 06:33:29 -0500 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <m3brknh1m7.fsf@pc150.maths.bris.ac.uk> References: <67B3A7DA6591BE439001F2736233351202B479BA@xch-nw-28.nw.nos.boeing.com> <mailman.31.1084583605.4157.python-list@python.org> <m3brknh1m7.fsf@pc150.maths.bris.ac.uk> Message-ID: <20040517113327.GA25004@unpythonic.net> On Mon, May 17, 2004 at 08:57:52AM +0000, Michael Hudson wrote: > The spec files are in Misc/RPM. I have no idea what you have to do to > make an rpm from there though (hey, I've only just learnt how to build > binary rpms from .src.rpms after, what, 6 years of being a redhat > user...). When a tar, gzipped tar, or bzip2'd tar contains a .spec file, you're supposed to be able to build it into a binary RPM with rpmbuild -ta <tarball> Unfortunately, with the spec file in this tarball, I get an error: $ rpmbuild -ta Python-2.3.4c1.tar.bz2 error: %changelog not in descending chronological order Jeff From hadi at nojunk.com.au Fri May 14 08:21:45 2004 From: hadi at nojunk.com.au (Hadi) Date: Fri, 14 May 2004 22:21:45 +1000 Subject: beginner's question Message-ID: <c82d51$78s$1@lust.ihug.co.nz> Hi, I have two files and the array that contains 20 words in it. I'm trying to write python script that suppose achieve the following: -Open file-1, read the line that contains 20 words separated with commas -Compare each word with words in the array -Open file-2 -if the word appears in the array write 'true' in file-2 -if not write 'false' -repeat this for every line in the file-1 so, two file will be identical in terms of number of lines and number of words in each line. However, file-2 will only contain wods 'true' and 'false'. Can anyone give some example or point me to som useful web sites please. Thanks, hadi From qjmbmw at mail333.com Sun May 30 12:42:12 2004 From: qjmbmw at mail333.com (Flora Griffin) Date: Sun, 30 May 2004 14:42:12 -0200 Subject: hadamard Message-ID: <432617044704190038874165.453E41139gf@netian.com> Bonita Bonilla,) The cable-filter will all0w you to receive,} All the channels that you 0rder with your remote control,) No Charge any more on payperviews,XXXX-movies,Sp0rt events,special-events ,( http://peter234234.com/cable/ ,clergy ,corp ,nymph ,nabisco . From sean_berry at cox.net Mon May 10 19:23:45 2004 From: sean_berry at cox.net (Sean Berry) Date: Mon, 10 May 2004 16:23:45 -0700 Subject: Writing Formatted txt to a file (xtreme newbie q) References: <8a0bb987.0405101503.2656788a@posting.google.com> Message-ID: <x9Unc.103838$Jy3.55459@fed1read03> How this will actually be written is dependent on how you have your data stored. If it is in a list is it like this [[question1, answer1], [question2, answer2], etc...] or ['question1=answer1', 'question2=answer2', etc...] or some other way. Once you can tell me that, I am sure I can give you a pretty easy way to write it out to a formatted file. "Uri" <phrogeeb at hotmail.com> wrote in message news:8a0bb987.0405101503.2656788a at posting.google.com... > I am working on a program that reads (through Tkinter and a form of > text boxes, checkboxes, radio switches, sliders, etc) a set of values, > saves them to a file, and is also capable of loading from the file so > that the sliders switches checkboxes etc will have the paramaters > defined in the text file (that last part is peripheral, eventual, but > if there's something i have to do to set that up immediately I'd like > to do that.) > > Right now, I'm basicly doing this in simple question-answer text > no-GUI format. > > I've managed to set up the q&a scenario, and using a print statement > set it up like I'd like it to go into the file (space-dileneated) > > However, I'm lost as far as writing it to the file in a formatted > form. I've looked around, and I'm pretty sure I can rule out pickle as > not what i want, but I'm having trouble figuring out what i do want. > The data is in the format of a list right now (maybe a dictionary at > some point) and there is one question and one answer per column. I > would like to set it up as "Question: Answer" in side-by-side > formatted columns, or perhaps "Question" over "Answer" in two rows, > answers on bottom. > > Thanks in advance! > > (Also, is there a pretty popular web-based forum for python or no?) From cybermanxu at hotmail.com Thu May 20 21:15:35 2004 From: cybermanxu at hotmail.com (Jinming Xu) Date: Thu, 20 May 2004 20:15:35 -0500 Subject: How to convert a Python Tuple into a C/C++ array? Message-ID: <BAY9-F4811BPkoNGCAV000579a0@hotmail.com> Rick, I got it by following your instructions! Thank you very much! Jinming >From: "Rick L. Ratzel" <rick.ratzel at scd.magma-da.com> >To: python-list at python.org >Subject: Re: How to convert a Python Tuple into a C/C++ array? >Date: Thu, 20 May 2004 16:37:30 -0500 > > > Here is one way to do it (untested...consider it pseudo-code): > >... > my_array = (double*) malloc(sizeof(double) * PyTuple_Size(pyObj)); > > tupleSize = PyTuple_Size(pyObj); > > for( i=0; i < tupleSize; i++ ) { > tupleItem = PyTuple_GetItem(pyObj, i); > > if( !PyFloat_Check(tupleItem) ) { > printf("Error: tuple contains a non-float value"); > exit(1); > } > my_array[i] = PyFloat_AsDouble(tupleItem); > } >... > > >Jinming Xu wrote: >>Hello everyone, >> >>While embedding my C++ program with Python, I am impeded by the conversion >>from a Python Tuple to a C++ array. I hope to get some assistance from >>you guys. >> >>I have a sequence of float numbers to be passed from Python to C++, with >>indefinite size. So I chose to use Tuple on the Python side. Since >>PyArg_ParseTuple() has no appropriate format to parse Tuple (The Tuple I >>am saying is not the Tuple of arguments) of arbitray size, I simply passed >>the tuple as follows >> >>PyObject* myTuple; >> if(!PyArg_ParseTuple(args,"O",&myTuple)) >> return NULL; >> >>Now I have the pointer, myTuple, to the Tuple passed in. How can I convert >>the the entired tuple, myTuple pointing to, into a float array, or convert >>an individual element into a C/C++ float number? Are there any conversion >>functions? >> >>Any suggestions or hints will be deeply appreciated! >> >>Thanks in advance! >> >>Jinming >> >>_________________________________________________________________ >>Express yourself with the new version of MSN Messenger! Download today - >>it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ >> >> >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From ville at spammers.com Thu May 27 02:31:34 2004 From: ville at spammers.com (Ville Vainio) Date: 27 May 2004 09:31:34 +0300 Subject: Python Shorthand (was Re: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <pan.2004.05.26.01.02.00.429236@sbcglobal.net> <du7fz9ni0ny.fsf_-_@amadeus.cc.tut.fi> <1X4tc.71833$hH.1301889@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <du78yfes7nd.fsf@mozart.cc.tut.fi> >>>>> "Andrew" == Andrew Koenig <ark at acm.org> writes: Andrew> "Ville Vainio" <ville at spammers.com> wrote in message Andrew> news:du7fz9ni0ny.fsf_-_ at amadeus.cc.tut.fi... >> Prefixing names with symbols like $ and @ is a great idea - it >> makes the "nouns" (variables) stand out from "verbs", and makes >> the code flow like a natural language, making reading it easy >> and writing it fun! Andrew> Interesting idea. Let's try it with English, using @ for Andrew> nouns and $ for verbs: Lest the humor (of contorted inside variety, I admit) be missed, it was a parody of Larry Wall's argument for why $ prefix does not in fact suck. -- Ville Vainio http://tinyurl.com/2prnb From rupole at hotmail.com Thu May 6 18:28:27 2004 From: rupole at hotmail.com (Roger Upole) Date: Thu, 6 May 2004 18:28:27 -0400 Subject: Debuggin a ptyhon extension References: <rzxmc.26524$j11.254148@weber.videotron.net> Message-ID: <409ab831_3@127.0.0.1> It's probably looking for the debug version of win32api (win32api_d.pyd, which will also require a debug build of Pywintypes). You can grab the pywin32 source and roll your own debug binaries, or alternately you might be able to get away with creating a release build of Python that contains debug info. hth Roger "Steve Menard" <devilwolf22 at hotmail.com> wrote in message news:rzxmc.26524$j11.254148 at weber.videotron.net... > I am writing a python extension module in VC++ on windows. At some > point, my extension crashes. > > Now I want to debug exactly why. I built the python projects in VC++, > and put the resulting python_d.exe in my ptyon home directory, and the > python23_d.dll in the windows/system32 directory. I also tried to put > the python23_d.dll in python's home directory, to the same result. > > Problem is, running my scripts/extension with python_d.exe, it always > complains it can't find win32api. Yes, I am using win32API to preload a > dll, and can't really get rid of it. > > To try and solve this, I tried replacing the "stock" python.dll with my > python_d, so at least VC++'s debugger would see the debug info. but I > got the same result, of win32api not being found ... > > What is the best way to go about this? My extension will require a fair > amount of native code and interacting with the Python code, so being > able to trace into python would be invaluable. > > Are my problems caused because python 2.3.3 (and possible win32all) were > build using VC.net? > > I am grateful for any help you guys can provide. > > > Steve Menard > devilwol22 at hotmail.com > From roy at panix.com Wed May 12 08:11:43 2004 From: roy at panix.com (Roy Smith) Date: Wed, 12 May 2004 08:11:43 -0400 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> <du7hdum415y.fsf@amadeus.cc.tut.fi> <slrnca3t0e.2asc.kirk@eyegor.jobsluder.net> Message-ID: <roy-B66843.08114312052004@reader2.panix.com> Kirk Job-Sluder <kirk at eyegor.jobsluder.net> wrote: > And here is the fundamental question. Why should I spend my time > writing a module in python to emulate another tool, when I can simply > use that other tool? Why should I, as a resarcher who must process > large quantities of data, spend my time and my employer's money > reinventing the wheel? At the risk of veering this thread in yet another different direction, anybody who does analysis of large amounts of data should take a look at Gary Perlman's excellent, free, and generally under-appreciated |STAT package. http://www.acm.org/~perlman/stat/ It's been around in one version or another for something like 20 years. It fills an interesting little niche that's part data manipulation and part statistics. > Here is the solution in awk: > BEGIN { FS="\t" } > {printf("%s %s %s %s", $4, $3, $2, $1)} In |STAT, that would be simply "colex 4 3 2 1". There's nothing you can do in |STAT that you couldn't do with more general purpose tools like awk, perl, python, etc, but |STAT often has a quicker, simpler, easier way to do many common statistical tasks. A good tool to have in your toolbox. For example, on of the cool tools is the "validata". You feed it a file and it applies some heuristics trying to guess which data in it might be invalid. For example, if a file looks like it's columns of numbers, and the third column is all integers except for one entry which is a floating point number, it'll guess that might be an error and flag it. It's great when you're analyzing 5000 log files of 100,000 lines each and one of them makes your script crash for no apparent reason. From babs at sntteam.org Wed May 26 07:21:28 2004 From: babs at sntteam.org (BaBS) Date: Wed, 26 May 2004 13:21:28 +0200 Subject: Bad interpreter References: <pan.2004.05.26.10.53.22.466189@sntteam.org> <Vs2dnYk8pZhf5yndRVn-gw@powergate.ca> Message-ID: <pan.2004.05.26.11.21.20.395901@sntteam.org> Le Wed, 26 May 2004 07:08:50 -0400, Peter Hansen a ?crit?: > BaBS wrote: > >> I've a problem whith my python script, >> i chmod'ed it to +x, addes the line : >> #!/usr/bin/python2.3 >> and i verified that /usr/bin/python2.3 exists >> but i've something like >> : bad interpreter: No such file or dir ... >> >> What's the matter ?? > > Remove the hidden CR character which you got at the end of the > lines by moving the file to a Windows system and editing it. ;-) > > This one is pretty tricky to figure out the first few times... > > -Peter Thanks for the tips but ... i don't have CR Character ... i edit my file with notepad and editplus but no matter what It's the same message :/ -- Damien From michele.simionato at poste.it Sat May 15 11:12:24 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 May 2004 08:12:24 -0700 Subject: Stackless python and microthreads References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <just-AEC793.15303514052004@news1.news.xs4all.nl> <2gk1k2F3li0jU1@uni-berlin.de> <just-0A0302.16084014052004@news1.news.xs4all.nl> <2gk2mtF3mcnaU1@uni-berlin.de> Message-ID: <95aa1afa.0405150712.2d63d6a5@posting.google.com> Michael Walter <cm at leetspeak.org> wrote in message news:<2gk2mtF3mcnaU1 at uni-berlin.de>... > What I meant was using continuations for "linear" code flow, such as > mentioned in > http://www.ai.mit.edu/~gregs/ll1-discuss-archive-html/msg02456.html, > described in http://www.double.co.nz/scheme/modal-web-server.html and > applied in Seaside, Borges, PLT Web Server etc. This is a most interesting reference, thanks! Incidentally, I am in the process of learning Zope TAL/TALES/METAL, which I do not like that much; I would rather prefer to generate HTML pages with Lisp macros and use real s-expressions instead of XML/HTML, but I can't :-( Lisp/Scheme is much more suitable for web applications (in principle) than any other language I know, it is unfortunate that (in practice) it is not that used ... Michele Simionato From dmq at gain.com Sun May 2 20:35:36 2004 From: dmq at gain.com (David MacQuigg) Date: Sun, 02 May 2004 17:35:36 -0700 Subject: prototypes in Python [was: what is good in Prothon] References: <95aa1afa.0404280120.30176ca9@posting.google.com> <sue79090tf0ja6rp63hsuj851l3dad0l44@4ax.com> <95aa1afa.0405012134.2b43ad6f@posting.google.com> Message-ID: <hepa90p4bcrr4sl3rveg3e39vdrrpuu00o@4ax.com> On 1 May 2004 22:34:27 -0700, michele.simionato at poste.it (Michele Simionato) wrote: >David MacQuigg <dmq at gain.com> wrote in message news:<sue79090tf0ja6rp63hsuj851l3dad0l44 at 4ax.com>... >> The unification of methods and functions is the one I am most interested >> in. The code below seems to have the machinery to do that, with the >> elimination of 'self' from the argument list. That alllows static >> methods to have exactly the same form as normal methods. ( The 'show' >> methods below are actually static methods if you remove any references >> to 'self', and replace them with explicit references, i.e. >> self.numAnimals --> Animal.numAnimals ). > >Probably you do not realize that methods and functions are *already* >unified in Python: they are both examples of descriptors. Descriptors >are maybe the most important thing in Python 2.2+, since the whole new style >object system is based on them. Not only: you can use descriptors to >implement an object system of your choice, as I did in the prototype >module; metaclasses just provide convenient syntactic sugar. Interesting! I wish that unification at the primitive level had been provided in the original design of Python. Seems like the multiple method styles we have now are just an historical accident. >BTW, descriptors are very well discussed here: >http://users.rcn.com/python/download/Descriptor.htm Good article, but beyond my current capabilities and available time. I'll keep this on my reference list. >> I agree with you that Python has the capability to implement >> prototypes. Perhaps we can do that using metaclasses for some initial >> experiments. Then if we get some constructive feedback, we can put >> together a PEP to make prototypes part of the core language, add >> better syntax, and fix whatever might not work quite right using >> metaclasses. > >Actually, I do NOT support the idea of making prototypes part of the >core language. If somebody wants to write and mantain a prototype module >that's fine, but I would be opposed to have it in the standard library. >There should be only one obvious object system in Python, and that >object system is not a prototype based one ;) >OTOH, there is nothing wrong about having a prototype module for people >wanting to experiment with prototypes without being forced to >abandon Python and its libraries. I'm coming to the same conclusion, especially now I see that prototypes can be done so easily in Python. If there is serious interest in prototypes, someone will make the effort to finish your module and commit to maintaining it. So far, I've seen too few reasonable people favoring prototypes, and too many thoreticians, egotistical fools, and anonymous trolls. :>) >> I'm collecting ideas for Python 3 and 4 and putting them on my webpage >> at http://ece.arizona.edu/~edatools/Python Python 3 includes features >> that are not compatible with Python 2, but I believe are consistent to >> the extent that Python 2 programs can be automatically translated to >> Python 3. Python 4 has no such contraint. All that matters is that >> the language is simple and elegant, and does useful things, as opposed >> to things that are theoretically interesting. Your comments and >> suggestions are welcome. > >If I was writing a new language, I would do Python with prefix notation ;) > >Seriously, I think that everybody interested in language design should >first study the existing languages and see what has already been >tried in the last fifty years: then probably 99% of "new" proposal >would be dismissed. I have not studied prototypes, so I may be wrong, >but I have a gut feeling that they are not such a good idea. So many languages. So little time. :>) Actually, I have found my study of Ruby and Prothon to be helpful in learning Python better, and it re-inforced my opinion that Python is the best choice for my own project -- a circuit-design platform that I hope will be useful for many years. Key factors in this choice are the excellent libraries, third-party software, books, and large community that have been built over the last ten years. The flaws in Python syntax are really minor compared to all this. Still, I wish there was something I could do about the flaws. From my study of Ruby, I know that Python's string methods could be improved. >From Prothon, I know that all forms of functions and methods could be unified in one simple form. It doesn't look like there is much interest in these problems in the Python community, however, so I think it is time to get back to my real job. >One thing I like about classes is that they are self-documenting: when you >see a class, you know which methods are in it. Of course, you can add >methods at run-time, but this is not good style: it is good to have the >ability, but you should not abuse it. OTOH, in prototype languages you >dynamically add methods all the time and the definitions are scattared in >different places, so it is not obvious to know what an object is doing >unless you read all the program (including imported modules). >This is already a problem with regular inheritance, prototype inheritance >would worsen the situation, at least ISTM and IMHO. I couldn't have said it better. With an interactive interpreter and a good editor, it is real easy to change any class or module. When I want to make such a change, I don't rely on my memory to make changes "on-the-fly". I find that class and spend a few minutes looking at it to make sure my changes don't have unintended consequences. Then I spend even longer re-running old tests to make sure I haven't broken something totally unexpected. The new IDLE editor is nice, because I can just hit F5 after every edit, and it re-initializes everything. This is not to say that "on-the-fly" programming is wrong. It just doesn't fit my need, which is a well-organized hierarchical system of classes and instances, one that I can maintain, and expect others to work on. I just can't imagine writing something like this by sticking in last-minute "with" blocks containing numerous variables I forgot to put in the original class definition. -- Dave From joewong at mango.cc Wed May 19 23:53:42 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 20 May 2004 11:53:42 +0800 Subject: question on DCOracle2 Message-ID: <013c01c43e1e$0b3e9bd0$7f00a8c0@scl01.siliconcreation.com> Hi, I have two system running with DCOracle2 library. On one system, the data is returned as 'float' but the other system return the value as 'string'. What could be the problem here? Best regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040520/644cb781/attachment.html> From theller at python.net Thu May 6 03:04:34 2004 From: theller at python.net (Thomas Heller) Date: Thu, 06 May 2004 09:04:34 +0200 Subject: What does 'is' do? References: <4099de7e$0$4321$5a62ac22@freenews.iinet.net.au> Message-ID: <oep2ghod.fsf@python.net> Derek Fountain <devnull at example.com> writes: > I recently saw a use of 'is' in a piece of Python code. I was trying to find > out what it does. I can't find it in the online docs. I have the "Python in > a Nutshell" book and that mentions it as a keyword, but I can't find a > description of it in there either. It's not in the index. > > Can someone tell me where to look? Second hit if you enter 'is' and press the search button: <http://starship.python.net/crew/theller/pyhelp.cgi> <http://starship.python.net/crew/theller/pyhelp.cgi?keyword=is&version=current> Thomas From fadelorme at free.fr Sat May 1 09:27:18 2004 From: fadelorme at free.fr (3Zen) Date: Sat, 1 May 2004 15:27:18 +0200 Subject: Dictionnary vs Class for configuration References: <40929016$0$8635$626a14ce@news.free.fr> <5p6dnTePS_YtPg_dRVn-hw@comcast.com> Message-ID: <4093a6a2$0$20754$626a14ce@news.free.fr> Thank you, I think a ini file is better for configuration. I will look the ConfigParser module. "Larry Bates" <lbates at swamisoft.com> a ?crit dans le message de news:5p6dnTePS_YtPg_dRVn-hw at comcast.com... > Ultimately you must answer to your professor, but... > > I firmly believe that configuration parameters belong > in a configuration file. ConfigParser module handles > these very well. Essentially it builds the dictionary > for you in the form of a ConfigParser class instance. > Then when you wish to change a parameter, edit the > config file and the next time the program runs it reads > the new parameters. You didn't mention your platform, > but I do a lot on Windows and "freeze" my programs using > py2exe, so configuration files come in really handy to > make those "run-time" variables available to the program. > I also find that people are quite comfortable editing > these files. > > Config file would look something like: > > [database] > name=nanana > userdb=bob > password=******** > > [other] > timetosleep=100 > path=/home/script > > program to read this: > > import sys > def ini_error(section, option): > # > # Insert code here to handle missing parameters > # > print "Unable to locate section=%s, option=%s in .INI file" % (section, > option) > sys.exit(2) > > > import ConfigParser > ini_filename="/directory/where/config/stored/program.ini" > INI=ConfigParser.ConfigParser() > INI.read(ini_filename) > > section="database" > option="name" > try: database=INI.get(section, option) > except: ini_error(section, option) > > option="userdb" > try: userdb=INI.get(section, option) > except: ini_error(section, option) > > option="password" > try: password=INI.get(section, option) > except: ini_error(section, option) > > section="other" > option="name" > try: timetosleep=INI.getint(section, option) > except: timetosleep=100 > > option="path" > try: path=INI.get(section, option) > except: ini_error(section, option) > > You get the idea. > > Regards, > Larry Bates > Syscon, Inc. > > "Famille Delorme" <fadelorme at free.fr> wrote in message > news:40929016$0$8635$626a14ce at news.free.fr... > > Sorry if this discussion are already submited, but I don't find anything > > really interresting for me. > > And sorry for my bad english, it is not my native language. > > > > I wrote a program in Python for a school project and I am in trouble. > > I have make a Python script called conf.py. This file contains > dictionnarys > > for configuration like this: > > config_sql = { > > "DATABASE" : "nanana", > > "USERDB" : "bob", > > "PASSWORD" : "********" > > } > > config_script = { > > "TIMETOSLEEP" : 100 > > "PATH" : "/home/script" > > } > > The config_section variable is included in each modules (script python) > used > > in my program > > (with from config.py import config_section) > > And the use is like this > > from conf.py import config_sql > > print config["DATABASE"] > > > > But my master say it's better to do a class like this > > class config : > > def __init__(self, part=="") : > > if (part=="SQL") : > > self.database="nanana" > > self.userdb="bob" > > self.password="*******" > > elif (part=="SCRIPT") : > > self.timetosleep=10 > > self.path="/home/script" > > .... > > > > and the use like this > > from conf.py import config > > cfg=config("SQL") > > print cfg.database > > > > We have do only a file for configuration because the administrator is no > > searching for configuration. > > I want know : > > - what is more faster, dictionnary method or class method? > > - what use more ram memory ? > > - if you are administrator, what method you like for configure program ? > > > > Note: > > * the class will not have methods, it is not necessary. > > * the program is composed of several modules which import > > config_section. > > > > > > Thank you for futures answers, > > 3Zen > > > > > > > > > > > > > > From ssk at chol.nospam.net Wed May 12 20:26:22 2004 From: ssk at chol.nospam.net (Sam Sungshik Kong) Date: Thu, 13 May 2004 00:26:22 GMT Subject: if Request("something") == None: doesn't work References: <AVsoc.47661$FI7.6868@newssvr29.news.prodigy.com> Message-ID: <Ogzoc.47746$AQ2.5767@newssvr29.news.prodigy.com> Thanks for the replies. Based on the hints from the replies, I've tested some. When there's no argument in the request, Request("id") == None returns False if Request("id"): returns True str(Request("id")) returns "None" repr(Request("id")) returns <COMObject<unknown>> So my conclusion is that Request("id") is not None. It's an object, str() of which is accidentally "None". That confused me. If it's not None, str(something) should not return "None". ssk "Sam Sungshik Kong" <ssk at chol.nospam.net> wrote in message news:AVsoc.47661$FI7.6868 at newssvr29.news.prodigy.com... > Hello! > > I use Python for ASP programming. > I found something weird. > > Response.Write(Request("something")) > It draws "None" when there's no value for something. > Actually I expect "" instead of "None". > > So I changed it like > if Request("something") == None: > Response.Write("") > else: > Response.Write(Request("something")) > > Strangely, the result of comparison is False. > > if str(Request("something")) == "None": > works! > > Also, > if len(Request("something")) == 0: > works! > > What's wrong? > > ssk > > From PeterAbel at gmx.net Wed May 26 18:44:34 2004 From: PeterAbel at gmx.net (Peter Abel) Date: 26 May 2004 15:44:34 -0700 Subject: Defining Multiple Objects at Once References: <464afbb13c2bd25bb14351db772159e0@localhost.talkaboutprogramming.com> Message-ID: <21064255.0405261444.7d1738b1@posting.google.com> "SilverShadow" <GPodubs at hotmail.com> wrote in message news:<464afbb13c2bd25bb14351db772159e0 at localhost.talkaboutprogramming.com>... > Hello, > > I'm having trouble with something that may be easily remedied. I use > Cantera running on Python. I need to make multiple "Reactor()" objects > and have them assigned a different (user defined) name. For example: > > reactors = [R1, R2, R3...etc.] > for reac in reactors: > reac = Reactor() > > My problem is there is no way to operate on each reactor separately. > (e.g. R1.temperature()) The only thing that can be done is > reac.temperature(), but that gets overwritten each time. So, my question > is, is there any way to assign multiple names w/o having to write out > lines of explicit definitions in the code? Thank you in advance. Most of time one wants to put the instances in a definite namespace. And in pyhton namespace handling is mostly organized by dictionaries. So it's not necessary to declare an additional dictionary while the namespace dictionary already exists. And most of time the target namespace is the global namespace. The following example will show, how to instantiate a bunch of variables for the global namespace: >>> # An example Reactor class, to show different instances >>> class Reactor: ... number_of_instances=0 ... def __init__(self): ... Reactor.number_of_instances+=1 ... self.Reactor_Number=Reactor.number_of_instances ... def show(self): ... print 'Reactorname: Reactor#%d' % self.Reactor_Number ... >>> # A list of variablenames for Reactor-instances >>> # its a lazy declaration, cause I dont want to write commas >>> # and single quotmarks >>> reactor_name_list='R1 R2 R3 R4 R5'.split() >>> reactor_name_list ['R1', 'R2', 'R3', 'R4', 'R5'] >>> # Add the instances with the declared names to the global >>> # namespace (it could be any else) which is represented by globals() >>> reduce(lambda last,name:globals().__setitem__(name,Reactor()),reactor_name_list,0) >>> # I took reduce rather than map, cause it doesnt create a list, >>> # which will be thrown away >>> # Remark the startvalue "0", cause otherwise "R1" wouldnt be instantiated >>> R1 <__main__.Reactor instance at 0x00DFC9D8> >>> R1.show() Reactorname: Reactor#1 >>> R2.show() Reactorname: Reactor#2 >>> # etc. >>> R5.number_of_instances 5 >>> R5.show() Reactorname: Reactor#5 >>> Hope I could help you. Regards Peter From jason at tishler.net Tue May 4 08:29:27 2004 From: jason at tishler.net (Jason Tishler) Date: Tue, 4 May 2004 08:29:27 -0400 Subject: Urllib2/threading errors under Cygwin In-Reply-To: <40931230.84EECF31@hot.pl> References: <40931230.84EECF31@hot.pl> Message-ID: <20040504122927.GC2352@tishler.net> Jacek, On Sat, May 01, 2004 at 04:57:52AM +0200, Jacek Trzmiel wrote: > [snip] > 1. First error. > > $ python MtUrllib2Test.py | tee out.txt > 3 > 4 > 5 > > Leading prints has been eaten somewhere. Uncommenting disabled code > in ANY of the functions does make output correct, but none of the > solutions looks good for me: See below... > [snip] > 2. Second error. > > If I increase number of threads: > noOfThreads = 20 > and run this prog (you may need to run it several times, or rise number > of threads more to reproduce), then sometimes it does fail this way : > > $ python MtUrllib2Test.py | tee out.txt > 4 [win] python 1744 Winmain: Cannot register window class > C:\cygwin\bin\python2.3.exe: *** WFSO failed, Win32 error 6 The above has been reported before: http://www.cygwin.com/ml/cygwin/2004-01/msg01371.html > [snip] > Can anyone help me on those two? I would recommend trying the latest Cygwin snapshot: http://cygwin.com/snapshots/ If that doesn't help, then I would post the smallest possible test case to the Cygwin list -- you will hopefully get better traction there. 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 I-dont-gots-one at dot.com Tue May 25 23:33:15 2004 From: I-dont-gots-one at dot.com (p-nut) Date: Wed, 26 May 2004 03:33:15 GMT Subject: Pop3 autosave attachment. Message-ID: <%dUsc.10736$be.9671@newsread2.news.pas.earthlink.net> newbie here needing some help. Is there a way to set up a script that will check a pop3 account and autosave the file attachments to a folder specified? The thing is: I have 1 single email account that will always have emails with nothing but emails with attachments. Since there will be thousands of these emails , I would like to be able to check a couple times a day this account and have the script auto save all attachments by their actual attached name to a specified folder. Is this possible? From max at alcyone.com Wed May 12 20:37:42 2004 From: max at alcyone.com (Erik Max Francis) Date: Wed, 12 May 2004 17:37:42 -0700 Subject: Finding the name of a class References: <40a2be14$0$3014$61fed72c@news.rcn.com> Message-ID: <40A2C356.FB967FED@alcyone.com> "Edward C. Jones" wrote: > Is there a function or method that returns the name of a class or > class > instance? > > class X(object): > pass > > X.amethod() or X().amethod() should return the string "X". > > X().__class__ returns "<class '__main__.X'>" which I could parse. Ugh. > > Or I could use module pyclbr. Ugh**2. Use the __name__ attribute: >>> class C: pass ... >>> C.__name__ 'C' >>> C().__class__.__name__ 'C' -- __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis \__/ Without love, benevolence becomes egotism. -- Dr. Martin Luther King, Jr. From troy at gci.net Sat May 22 04:54:57 2004 From: troy at gci.net (Troy Melhase) Date: Sat, 22 May 2004 00:54:57 -0800 Subject: Determine Whether File Exists On HTTP Server In-Reply-To: <Xns94F1EA84483Byangstaoverbored@127.0.0.1> References: <Xns94F1EA84483Byangstaoverbored@127.0.0.1> Message-ID: <200405220054.57061.troy@gci.net> On Saturday 22 May 2004 12:28 am, OvErboRed wrote: > Hi, I'm trying to determine whether a given URL exists. I'm new to Python > but I think that urllib is the tool for the job. However, if I give it a > non-existent file, it simply returns the 404 page. Aside from grepping this > for '404', is there a better way to do this? (Preferrably, there is a > solution that can be applied to both HTTP and FTP.) Thanks in advance. Try urllib2.urlopen, and put a try/except block around it. Here's what an unhandled exception from a 404 response looks like: Python 2.3.3 (#1, May 14 2004, 09:49:22) [GCC 3.3.2 20031218 (Gentoo Linux 3.3.2-r5, propolice-3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> handle = urllib2.urlopen('http://google.com/this_page_doesnt_exist') Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.3/urllib2.py", line 129, in urlopen return _opener.open(url, data) File "/usr/lib/python2.3/urllib2.py", line 326, in open '_open', req) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 901, in http_open return self.do_open(httplib.HTTP, req) File "/usr/lib/python2.3/urllib2.py", line 895, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "/usr/lib/python2.3/urllib2.py", line 346, in error result = self._call_chain(*args) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 472, in http_error_302 return self.parent.open(new) File "/usr/lib/python2.3/urllib2.py", line 326, in open '_open', req) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 901, in http_open return self.do_open(httplib.HTTP, req) File "/usr/lib/python2.3/urllib2.py", line 895, in do_open return self.parent.error('http', req, fp, code, msg, hdrs) File "/usr/lib/python2.3/urllib2.py", line 352, in error return self._call_chain(*args) File "/usr/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/lib/python2.3/urllib2.py", line 412, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found -- Troy Melhase, troy at gci.net -- When Christ calls a man, he bids him come and die. - Dietrich Bonhoeffer From griebel at konzept-is.de Fri May 14 04:30:15 2004 From: griebel at konzept-is.de (Dr. Peer Griebel) Date: Fri, 14 May 2004 10:30:15 +0200 Subject: Speed up properties?! In-Reply-To: <20040514055428.GE24078@frobozz> References: <40A45DAD.2020906@konzept-is.de> <20040514055428.GE24078@frobozz> Message-ID: <40A48397.7010307@konzept-is.de> Andrew Bennetts wrote: > On Fri, May 14, 2004 at 07:48:29AM +0200, Dr. Peer Griebel wrote: > >>Hi, >> >>I have a class with some properties. I would like to verify that only >>valid values are assigned to the properties using assert. Therefore I >>code setters and getters and use property() to convert these to have a >>real property. >> >>Since the verification is only performed in __debug__ runs the >>property() is quite a lot of overhead. I tried to circumvent it. This >>is my result so far: >> >> >>class C(object): >> def __init__(self): >> self._x = 5 >> if not __debug__: >> self.x = property(self._x, self._x) > > > This doesn't really do what you want: properties (and descriptors in > general) only work their magic when they are attributes of classes, not > instances. Oh yes you are right. I didn't look at x to discover that it is a property object. > I think a simpler approach in your __init__ would do what you want: > > def __init__(self): > if __debug__: > self.x = 5 # ordinary attribute > else: > self._x = 5 # use properties But this means I have to replace _all_ occurences of _x by x (or vice versa). This has to be performed in all methods of C and all other methods using C! What I am looking for is a mechanism to create an alias x for _x so that in non __debug__ mode I can access _x by using x. (In debug mode the property creates this alias by using the setter and getter method.) > The rest looked fine to me. > > -Andrew. Thank you, Peer From apardon at forel.vub.ac.be Thu May 13 06:41:45 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 May 2004 10:41:45 GMT Subject: Scope rule pecularities References: <c7dm1v$q8f$05$1@news.t-online.com> <slrnc9mdn4.5fa.apardon@trout.vub.ac.be> <c7ff3o$2rk$1@news.service.uci.edu> <slrnc9mjds.5fa.apardon@trout.vub.ac.be> <2g8ag2F4re0lU1@uni-berlin.de> <slrnca428q.1i9.apardon@trout.vub.ac.be> <Xns94E78398B6CAAduncanrcpcouk@127.0.0.1> <slrnca4693.1i9.apardon@trout.vub.ac.be> <donn-A934F5.11082112052004@nntp2.u.washington.edu> <slrnca69ju.1i9.apardon@trout.vub.ac.be> <mailman.504.1084436448.25742.python-list@python.org> Message-ID: <slrnca6k7a.1i9.apardon@trout.vub.ac.be> Op 2004-05-13, Andrew Bennetts schreef <andrew-pythonlist at puzzling.org>: > On Thu, May 13, 2004 at 07:40:45AM +0000, Antoon Pardon wrote: >> >> But I don't ask for rebinding, I ask for easy in place copying. >> >> Lets name a new operator "@=" Now given variables A and C >> of the same class I would like to see the following: >> >> >>> B = A >> >>> A @= C >> >>> A is B >> True >> >>> A is C >> False >> >>> A == C >> True > > It's already easy: > > from copy import copy > > b = a > a = copy(c) Sorry, you are wrong. After this you get >>> a is b False > [I'm using lowercase variables for instances, which is the usual > convention... uppercase suggests that it's a class name (or maybe a > constant) to me.] > > No new syntax necessary. >> And maybe if D is of an other class >> >> >>> D @= C >> TypError > > Assignments in Python don't care about what the name is currently bound to, > if anything. This is not assignment (as is understood in python). > They just (re)bind the name to an object -- so having an > assignment to D depend on the type of D's old value would be inconsistent > with the rest of Python. > > Many classes support a convention where you can pass a single argument to > their constructor to construct a copy, e.g.: > > l2 = list(l1) > > So your example could become: > > d = d.__class__(c) No to get the same effect as what I want you need something like this: class M: def cp_from(self, a): for key in dir(self): value = getattr(a,key) setattr(self,key,value) d.cp_from(c) -- Antoon Pardon From ddenholm at theworld.com Wed May 19 09:00:32 2004 From: ddenholm at theworld.com (D Denholm) Date: 19 May 2004 06:00:32 -0700 Subject: problem with PYTHONPATH on WinXP References: <e71eaa43.0405091124.2f64f2a9@posting.google.com> <WqGdnYCgYuL7xALdRVn-uw@powergate.ca> Message-ID: <e71eaa43.0405190500.56924789@posting.google.com> Thanks, that did the trick. I am still puzzled why the PYTHONPATH environment variable didn't work. Is it overwritten if *any* *.pth files exist? Peter Hansen <peter at engcorp.com> wrote in message news:<WqGdnYCgYuL7xALdRVn-uw at powergate.ca>... > D Denholm wrote: > > > I recently installed Python 2.2 on my WinXP box. > > > > I am having problems figuring out how to create the PYTHONPATH > > correctly. > > I would suggest not using PYTHONPATH, but instead use the .pth > file capability defined in and used by site.py. Check the > comments at the top of that file in your python/lib folder, > and make a .pth file with the appropriate contents instead > of mucking with environment variables. One thing to note: > the file extension must be lower case or site.py won't > find the file. > > -Peter From greg at cosc.canterbury.ac.nz Tue May 4 22:54:37 2004 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 05 May 2004 14:54:37 +1200 Subject: Different values for property vs attribute??? In-Reply-To: <c78sn7$11n72$1@ID-76829.news.uni-berlin.de> References: <ec6dce8b.0405041123.19c4c6c3@posting.google.com> <c78sn7$11n72$1@ID-76829.news.uni-berlin.de> Message-ID: <c79l1i$1d5at$1@ID-169208.news.uni-berlin.de> Russell Blau wrote: > As someone else pointed out in another thread within the last 24 hours, > properties are only supported for new-style classes. Try changing the first > line to > > class Klass(object): > > and see if it works. Since this seems to be such an easy error to make, and the symptoms are so obscure, is there any way the interpreter could be made to check for it? E.g. maybe old-style classes could refuse to accept any attribute which is an instance of property. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From loic at fejoz.net Wed May 5 12:15:12 2004 From: loic at fejoz.net (Yermat) Date: Wed, 05 May 2004 18:15:12 +0200 Subject: the dreaded double fork In-Reply-To: <mailman.272.1083771384.25742.python-list@python.org> References: <mailman.272.1083771384.25742.python-list@python.org> Message-ID: <c7b442$fav$1@arcturus.ciril.fr> John Hunter wrote: > I am using python to run an xml rpc daemon using SimpleXMLRPCServer. > Following a cookbook recipe, I am trying to do a double fork so that > when I exit the shell the daemon remains running. But it doesn't. > Here is how I start the script > > >>ssh somehost >>sudo python mydaemon start& > > > But when I exit the shell, I lose the process. > > What am I doing wrong? Here is my script, with all the non server > stuff snipped. You will find here one(?) good way of doing it : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 -- Yermat From franck.lepoutre at caramail.com Sat May 15 04:50:55 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Sat, 15 May 2004 10:50:55 +0200 Subject: book on wxPython? References: <slrncab3p3.ou5.grante@grante.rivatek.com> Message-ID: <40a5d8fe$0$4363$79c14f64@nan-newsreader-06.noos.net> > Can anybody recommend a good book on wxPython? > Are there any books on wxPython? You're not alone waiting for the wxpython book. As a lot of python users, i just learned python from a couple of web resources, referring to books later and mostly for reference or unusal tricks. Learning a UI, specifically when you're not an MFC (or unix eq.) guru, is another matter. I expect that this wx* book, whatever its quality and price, would make more to the project than additional web resources or bug fixes... At some stage, when dealing with complexity, you 've got to: -solution 1, expect a quantic leap in terms of "making the thing simpler", something like a python way for UIs; In view of the recent discusssion on the wxpython mailing lists, it looks like the chances of a massive "simplification" are getting dimmer over time.. -solution 2 - read the carefully writtent book before diving. Dear O'Reilly, do you hear us? Fran?ois From has.temp2 at virgin.net Sat May 1 11:49:05 2004 From: has.temp2 at virgin.net (has) Date: 1 May 2004 08:49:05 -0700 Subject: What is good about Prothon? References: <bniq80hiib0gauiltuntk9jvia2getbnj4@4ax.com> <vDvjc.5555$Qy.2995@fed1read04> <108t2tlo06j8vb9@corp.supernews.com> <hzwjc.6087$Qy.2366@fed1read04> <69cbbef2.0404281446.4e0ab52e@posting.google.com> <ZHXjc.17225$Qy.13377@fed1read04> <69cbbef2.0404291609.72d391db@posting.google.com> <Awlkc.36778$Qy.19874@fed1read04> <69cbbef2.0404300855.4dce5e5@posting.google.com> <CYwkc.44066$Qy.9803@fed1read04> <donn-F264BC.12385330042004@nntp1.u.washington.edu> Message-ID: <69cbbef2.0405010749.5516508e@posting.google.com> Donn Cave <donn at u.washington.edu> wrote in message news:<donn-F264BC.12385330042004 at nntp1.u.washington.edu>... > He probably thought they were pearls of wisdom. Guess you don't > want any more, anyway. Yeah, well I'd personally be the first to acknowledge that every other "pearl" I throw is more commonly a lump of shit. So I actually appreciate it when folk take a sniff and tell me it's a turd. It's when they blat every single toss straight into the rough then promptly ask for another one that I eventually get a bit peeved. To be honest, however, I've got nobody to blame but myself for this particular outbreak. I unsubscribed from the prothon mailing list because I'd already recognised I wasn't getting anywhere and my continued presence would only waste my own time and energy and everybody else's. And I should _really_ have known better than to get re-involved over here. So I apologise to the rest of the comp.lang.python group - as friendly and civilised an online group as I've ever been in - for any disturbance caused, and now return you to your regular program. Let Mark have the last word; just for surviving me this far I think he deserves it. ;) Mr Intensity From godoy at ieee.org Thu May 13 12:29:53 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 13 May 2004 13:29:53 -0300 Subject: RPM generation with distutils: a little help, please. Message-ID: <4ekcn1-0ki.ln1@wintermute.g2ctech> Hi! For the following setup.py, I get this error: byte-compiling /var/tmp/bhsys-buildroot/usr/lib/python2.3/site-packages/bhsys/Impressao.py to Impressao.pyc byte-compiling /var/tmp/bhsys-buildroot/usr/lib/python2.3/site-packages/bhsys/bhsys.py to bhsys.pyc running install_scripts copying build/scripts-2.3/bhsys.py -> /var/tmp/bhsys-buildroot/usr/bin changing mode of /var/tmp/bhsys-buildroot/usr/bin/bhsys.py to 755 running install_data error: can't copy 'imagens/BH_Sys.png': doesn't exist or not a regular file erro: Status de sa?da ruim em /var/tmp/rpm-tmp.39012 (%install) ============================= setup.py ==================================== import os from distutils.core import setup import distutils.sysconfig setup(name="bhsys", version="0.1", description="BH Sys", author="G2C Tech Consultoria Ltda.", author_email="comercial at g2ctech.com", url="http://www.g2ctech.com/", packages=['bhsys.biblioteca', 'bhsys'], package_dir = {'bhsys': '.', 'biblioteca': 'biblioteca',}, scripts=['bhsys.py'], data_files=[(os.path.sep.join([distutils.sysconfig.get_python_lib(),'bhsys','imagens']), ['imagens/BH_Sys.png', 'imagens/BH_SysB.png', 'imagens/BH_logo.png', 'imagens/adm.png', 'imagens/clientes.png', 'imagens/compras.png', 'imagens/exit.png', 'imagens/financeiro.png', 'imagens/g2ctech.png', 'imagens/manutencao.png', 'imagens/notas.png', 'imagens/rh.png', 'imagens/sair.png', 'imagens/seta.png', 'imagens/seta2.png', 'imagens/tecnico.png', 'imagens/telefone.png']), (os.path.sep.join([distutils.sysconfig.get_python_lib(),'bhsys']), ['config.ini']), ] ) =========================================================================== Any hints on how I can make it work? And, please, is there a more effective way of putting the images (imagens, in pt_BR) below the site-packages/bhsys directory? This is working perfectly for tarballs and it is also able to create a ".exe" installer on Windows, but it fails for RPM. The image file pointed out in the error message is there... I think it's something related to copying it to the specific directory used by rpmbuild in the specfile, but is there any way to do that from distutils? Thanks, -- Godoy. <godoy at ieee.org> From tjreedy at udel.edu Thu May 13 12:35:48 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 May 2004 12:35:48 -0400 Subject: things I wish python could do References: <pan.2004.05.12.20.36.39.451799@sbcglobal.net> <tyfk6zgpx6w.fsf@pcepsft001.cern.ch> Message-ID: <c80857$vra$1@sea.gmane.org> "Jacek Generowicz" <jacek.generowicz at cern.ch> wrote in message news:tyfk6zgpx6w.fsf at pcepsft001.cern.ch... > Ryan Paul <segphault at sbcglobal.net> writes: > Yes, I find the whole statement expression dichotomy one huge PITA. Would you really prefer writing <target> = expression as set('<target>', expression) or as the 'special-form' pseudofunction call setq(<target>, expression)? Just about all Python statements are statements because they would also be a PITA, and possibly more so, as expressions. > > 4. assignments cant be made inside of anonymous functions. > > Actually, there's very little you can do in anonymous functions, given > that you are restricted to a _single expression_. Lambda expressions in Python are strictly an abbreviation for functions with a trivial body ('return expression'), nothing more. Anonymity is a wart, not a feature. The keyword is, to me, a mistake because of the false expectations it stimulates. > I'm feeling in a controversy-stirring mood. Can you tell? Bait taken ;-) Terry J. Reedy From peter.maas at mplusr.de Thu May 27 11:14:04 2004 From: peter.maas at mplusr.de (Peter Maas) Date: Thu, 27 May 2004 17:14:04 +0200 Subject: [newbie] conditional imports In-Reply-To: <mailman.361.1085666071.6949.python-list@python.org> References: <mailman.361.1085666071.6949.python-list@python.org> Message-ID: <c950ka$7lf$1@swifty.westend.com> vincent Salaun wrote: > Here is my idea: > > ############################################################# > #module myBothJavaAndPyParser : > > #if the module is used by the Java app :: > from javax.xml.parsers import DocumentBuilder, DocumentBuilderFactory > from org.w3c.dom import * > > factory=DocumentBuilderFactory.newInstance() > builder = factory.newDocumentBuilder() > parseString=self.builder.parse > > #else: > from xml.dom import minidom,Node > parseString=minidom.parseString My suggestion (untested): import sys if sys.platform[:4] == 'java': from javax.xml.parsers import DocumentBuilder, DocumentBuilderFactory from org.w3c.dom import * factory=DocumentBuilderFactory.newInstance() builder = factory.newDocumentBuilder() parseString=self.builder.parse else: from xml.dom import minidom,Node parseString=minidom.parseString Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24 Tel +49-241-93878-0 Fax +49-241-93878-20 eMail peter.maas at mplusr.de ------------------------------------------------------------------- From ville at spammers.com Thu May 13 01:37:00 2004 From: ville at spammers.com (Ville Vainio) Date: 13 May 2004 08:37:00 +0300 Subject: perl to python References: <mailman.478.1084391040.25742.python-list@python.org> Message-ID: <du74qqkdh1f.fsf@mozart.cc.tut.fi> >>>>> "Chris" == Hornberger, Chris <Chris.Hornberger at blackrock.com> writes: Chris> Why bother with getting perl code translated into python Chris> code? Because Python code is more readable and maintainable. That is a huge win in multi-maintainer situations (which is typical in production code). You can also bump up the functionality of the script while porting, and get better reuse. Porting perl code to Python is always very easy. Perl doesn't really do anything that isn't as easy to express in Python. Chris> Perl is probably one of the best string manipulation and Chris> RegEx processors ever. Yes, and so is Python. There have been several requests of examples where Perl does a better job at string manipulation/regexp processing than Python, and none have been presented. Perl regexps might execute slightly faster, but that is hardly a winning argument. Chris> They don't have to overlap. With Python's pipe handling But they do. Perl and Python completely overlap, to the extent car ("horseless carriage") and a horsefull variant of the carriage overlap. Chris> there's little reason not to simply leave the perl code Chris> where it is and run it from an orchestration script in Chris> Python. If the perl script is "complete" already, with no need to implement extra functionality ever, that is probably ok. Then you can think of the code as almost an executable third party binary, and have no responsibilities or attachment regarding the source code. -- Ville Vainio http://tinyurl.com/2prnb From segphault at sbcglobal.net Mon May 17 05:09:56 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 17 May 2004 09:09:56 GMT Subject: need help running python script in linux References: <81dff960.0405170002.5621ec20@posting.google.com> Message-ID: <pan.2004.05.17.09.05.44.552118@sbcglobal.net> On Mon, 17 May 2004 01:02:17 -0700, xunil wrote: > > #!/usr/bin/env python > "USAGE: echoserver.py <port>" > from SocketServer import BaseRequestHandler, TCPServer > import sys, socket > > class EchoHandler(BaseRequestHandler): > def handle(self): > print "Client connected:", self.client_address > self.request.sendall(self.request.recv(2**16)) > self.request.close() > > if len(sys.argv) != 2: > print __doc__ > else: > TCPServer(('',int(sys.argv[1])), > EchoHandler).serve_forever() > this defines a class, but you dont instantiate the class- so the code essentially doesn't do anything. I suggest you read some tutorials. From peter at engcorp.com Fri May 21 15:19:34 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 15:19:34 -0400 Subject: python hello.py hello_msg("Hello no", 3)??? Help, please! In-Reply-To: <10asfp2a30jsobc@corp.supernews.com> References: <Hb4rc.237$rc2.101@amstwist00> <1O-dnXbH1_NxTzHd4p2dnA@powergate.ca> <10asfp2a30jsobc@corp.supernews.com> Message-ID: <VYedndsn_vvayzPdRVn-tA@powergate.ca> Chris wrote: > Peter Hansen wrote: > > >>Carl wrote: >> >> >>>This is perhaps a very simple and stupid question! >>> >>>How do you run a specific function (with actual values for the >>>parameters) within a module from the command prompt? That is, with >>>"python ..." >>> >>>For instance, how do I run hello_msg("Hello no ", 3), which is a function >>>within the module hello.py, from the console? >>> >>>def hello_msg(msg, num): >>> print msg + str(num ** 3) +'!' >>>#hello_msg("Hello no ", 3) >> >>Use the -c option. >> >>python -c "import modulename; modulename.hello_msg('test', 5)" > > Or, from the command prompt, 'import modulename' ?? My example _was_ from the command prompt, and your approach doesn't execute hello_msg() as the OP requested. -Peter From mir4uu at yahoo.com Fri May 21 07:24:14 2004 From: mir4uu at yahoo.com (mir nazim) Date: 21 May 2004 04:24:14 -0700 Subject: newbie: sample code for wxpython/twisted References: <425cc8d1.0405190904.4b92a20b@posting.google.com> <425cc8d1.0405200558.5379884c@posting.google.com> <c8ifvv$gnn$1@ctb-nnrp2.saix.net> Message-ID: <425cc8d1.0405210324.3da87c9f@posting.google.com> > But if you just want to learn wxpython, do the tutorials, you don't need > to find lots of projects first, that'll give you a good idea of the > capabilities... > but where can i find that tutorial. i have seen wx docs, they r c++ thing. From peter at engcorp.com Fri May 21 12:32:37 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 May 2004 12:32:37 -0400 Subject: Specify start and length, beside start and end, in slices In-Reply-To: <c8l8pa$4n0$1@news.iucc.ac.il> References: <c8l3s3$27o$1@news.iucc.ac.il> <slrncas79j.41g.grante@grante.rivatek.com> <c8l6ro$3p7$1@news.iucc.ac.il> <Fc-dndNGTtNmvzPdRVn-uQ@powergate.ca> <c8l8pa$4n0$1@news.iucc.ac.il> Message-ID: <juidnTvQubq4sjPd4p2dnA@powergate.ca> Noam Raphael wrote: > Peter Hansen wrote: > >> Noam Raphael wrote: >> >>> Grant Edwards wrote: >>> >>>> It's a bit less efficient, but you can currently spell that as >>>> >>>> l[12345:][:10] >>>> >>> That is true, but if the list is long, it's *much* less efficient. >> >> >> >> Considering that the interpreter special-cases some integer math >> including the BINARY_ADD, it likely wouldn't take a very long list >> to pass the point where they're the same. >> > > I don't understand: If the list is of length 1000000, wouldn't Grant > Edwards' suggestion make 1000000-12345 new references, and then take > only the first ten of them? Sorry, it was perhaps unclear that I was agreeing with you. For an extremely short list, it's possible that it would be faster to do Grant's method, but what I was trying to say is that even if that's true, I expect that for a list of more than a few dozen elements it would not be faster. Looking at it again, I suspect that it would actually never be faster, given that probably about as many bytecode instructions are executed, and then there's the extra memory allocation for the temporary list, the copying, etc. -Peter From klapotec at chello.at Wed May 19 00:15:04 2004 From: klapotec at chello.at (Christopher Koppler) Date: Wed, 19 May 2004 04:15:04 GMT Subject: alternatives to making blocks like { } or other ?? References: <c8do0u$9fb$1@news.atman.pl> <u%yqc.15650627$Id.2594622@news.easynews.com> Message-ID: <ljnla09gtl4jpngpnpiim46r7paas78hp0@4ax.com> On Wed, 19 May 2004 01:46:02 GMT, "Chad Thompson" <chad at sabinasp.com> wrote: > >"CYBER" <usenet at zly_adres.com> wrote in message >news:c8do0u$9fb$1 at news.atman.pl... >> Hello >> >> Is there any other way under python to create blocks ?? >> >> instead of >> >> def sth(x): >> return x >> >> >> >> could i use something else like >> >> def sth(x): >> { >> return x >> } >> >> >> ??? > >http://www.python.org/doc/Humor.html#parsing > Ah yes, that was the link, I'd completely forgotten about the Python humour page! Oh, and CYBER: my post was *meant* ironic, but Python is flexible enough that it can be taken at face value - so glad to have been of help ;-) -- Christopher From http Wed May 19 21:59:14 2004 From: http (Paul Rubin) Date: 19 May 2004 18:59:14 -0700 Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <tyfu0yem07c.fsf@pcepsft001.cern.ch> <mailman.49.1084890435.6949.python-list@python.org> <HEyqc.132$Uq1.127@fe2.columbus.rr.com> <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> Message-ID: <7xfz9vamfh.fsf@ruckus.brouhaha.com> imbosol at aerojockey.com (Carl Banks) writes: > > >>> a.bar = lambda x: x*x*x > > >>> a.bar(3) > > 27 > > Well, come on, of course there's going to be some things here and > there you can do in one and not the other. In wat is Python dynamic > that Lisp isn't to such an extent that it would cripple any attempts > to compile it? The example above kills any attempt to turn a.bar() into a static procedure call. There's more like it, e.g. the existence of the locals() dictionary and the ability to modify it. However, it should be possible to define a reasonable subset of Python that can compile into good code. The stuff that makes compilation difficult makes the code unmaintainable too. I do think that Python's designers should wait til PyPy with native-code backends has been deployed for a while before defining too much of Python 3.0, so we can first gain some experience with compiled Python. Python should evolve towards being compiled most of the time. From niemeyer at conectiva.com Sat May 1 16:35:25 2004 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sat, 1 May 2004 17:35:25 -0300 Subject: Closures In-Reply-To: <Pine.LNX.4.44.0404292315080.3857-100000@pingu.thwackety.com> References: <20040429210402.GA7316@burma.localdomain> <Pine.LNX.4.44.0404292315080.3857-100000@pingu.thwackety.com> Message-ID: <20040501203524.GA32529@burma.localdomain> > > class Closure: > > def __init__(self): > > self.__dict__ = sys._getframe().f_back.f_locals > > Out of interest how portable is this? Strikes me as extremely useful > class to have lying around :) The only thing that makes me wonder is > the access to _getframe... I'd put it in the "hack" section. :-) As others have said, you may pass a locals() parameter to the class if you want to be in the safe side. But-it-wont-be-so-fun-ly y'rs -- Gustavo Niemeyer http://niemeyer.net From cbearden at hal-pc.org Fri May 7 18:07:29 2004 From: cbearden at hal-pc.org (Chuck Bearden) Date: 07 May 2004 22:07:29 GMT Subject: ClientCookie/urllib2 with persistent connections? Message-ID: <409c08a1$0$129$a726171b@news.hal-pc.org> My impression is that if I want to make several requests over a single, persistent HTTP 1.1 connection, I must use httplib rather than urllib2 or ClientCookies. Is that correct? To put it another way, can I have cookie support over persistent connections without having to code the cookie support myself? Thanks, Chuck From cpl.19.ghum at spamgourmet.com Sun May 23 08:52:52 2004 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sun, 23 May 2004 14:52:52 +0200 Subject: Issues in compiling Python to machine code References: <40b089a5$0$16599$5a62ac22@freenews.iinet.net.au> Message-ID: <Xns94F196177A599cpl19ghumspamgourmet@62.153.159.134> Johnathan > Are there any reasons why Python would be *impossible* to compile? there is quite a FAQ to this question :))) Why is there no Python compiler ? - because when it was time to do so, it was not possible to get a diploma for creating a compiler, so sufficent motivation was not available. Actually there are some projects towards a "python compiler": look at: http://codespeak.net/pypy/ -> Python in Python http://psyco.sourceforge.net/ -> Python special compiler. Creates x86 machine code out of Python "on the fly" http://web.mit.edu/msalib/www/urop/ Starkiller is some project to deal with types in Python http://ironpython.com/ Jim Hugunin is doing a projekt for "Python 'compilation' to the .NET / MONO platform" Maybe it could be valuable to you to visit EuroPython (http://www.europython.org/, the biggest Python Conference without US travelling restrictions. Especially http://www.europython.org/conferences/epc2004/info/talks/refereed/msalib0 1 http://www.europython.org/conferences/epc2004/info/talks/python_language/ arigo02 http://www.europython.org/conferences/epc2004/info/talks/python_language/ arigo01 may be of great interest for you. Registration is still open, you can attend for 220? normal fee. Harald From rawbobb at hotmail.com Sat May 1 14:07:10 2004 From: rawbobb at hotmail.com (bobb) Date: Sat, 01 May 2004 18:07:10 GMT Subject: IDE for Python References: <mailman.164.1083359859.25742.python-list@python.org> <pan.2004.05.01.00.55.19.899197@phreaker.net> <ZHKkc.90737$vn.256362@sea-read.news.verio.net> Message-ID: <iHRkc.15095$wY.6279@nwrdny03.gnilink.net> "Washu" <me at privacy.net> wrote in message news:ZHKkc.90737$vn.256362 at sea-read.news.verio.net... > Nuff Said wrote: > > > Why an IDE? Python is - IMO - (one of) THE languages, where > > a good editor (tabs2spaces, comment blocks, select encoding, > > syntax highlighting, auto-indentation, scriptable ...) is all > > you really need. > > I personally like the debugging capabilities of a good IDE, specifically the > ability to watch a variable as you step through it. I know you can perform > the same thing through debugging statements but it's not as slick. > IMO i like the auto-complete functions of an ide. > The IDE of my choice for debugging purpose is Komodo from Activestate. For > writing the scripts, I tend to like Glimmer, although most modern editors > have some type of scripting language hightlighting scheme. > From imbosol at aerojockey.invalid Fri May 21 18:54:42 2004 From: imbosol at aerojockey.invalid (Carl Banks) Date: Fri, 21 May 2004 22:54:42 GMT Subject: Python compilers? References: <38Yqc.166$eO6.128@fe2.columbus.rr.com> <7x1xlf8p9z.fsf@ruckus.brouhaha.com> <rkerc.426$MY4.301@fe2.columbus.rr.com> <m2n042ujbn.fsf@unique.phony.fqdn> Message-ID: <SMvrc.1178$2H2.1033@fe2.columbus.rr.com> Heather Coppersmith wrote: > > > On Fri, 21 May 2004 03:03:51 GMT, > Carl Banks <imbosol at aerojockey.invalid> wrote: > >> Paul Rubin wrote: >>> >>> >>> Carl Banks <imbosol at aerojockey.invalid> writes: >>>> > The example above kills any attempt to turn a.bar() into a static >>>> > procedure call. >>>> >>>> Of course it does--but it's one method. A compiler, if it's good, >>>> would only make the optization on methods named "bar", and it could >>>> probably pare the number of possible classes it could happen to down >>>> to only a few. >>> >>> How could it possibly know? The reassignment of a.bar could happen >>> anytime, anywhere in the code. Maybe even in an eval. > >> And if it happens anytime, anywhere in the code, the compiler will see >> it and create more general code. Or is that impossible? > > The compiler might not see it. Any function/method/module called while > a is in scope might change a.bar. It doesn't even take a perverted > introspection tool: > > module foo: > > import bar > class C: > pass > a = C( ) > a.bar = 'bar' > bar.bar( a ) > a.bar = a.bar + 'bar' # which 'add' instruction should this compile to? > > module bar: > > def bar( x ): > x.bar = 3 Compiler builds a big call-tree. Compiler sees that the object "a" is passed to a function that might rebind bar. Compiler thinks to itself, "better mark C.bar as a dynamic attribute." Compiler sees dynamic attirbute and addition. Compiler generates generic add code. You could have all kinds of setattrs, evals, and unanalysable data structures (a la pickle), that could turn the code into a nightmare that a compiler couldn't do anything with. But surely, guarding against all of that, a good enough static compiler can still reduce a lot of good, maintainable Python code to it's static case. And, frankly, I still don't see how this is different from Lisp. (defun foo () (let ((x 1)) (setq x (bar x)) (setq x (+ x 1)))) In another package: (defun bar (x) #C(2.0 1.0)) If I recall, + can work on ints, floats, bignums, rationals, and complex numbers, at least. What one instruction does + compile to here? >> As for eval, well it would be silly to even allow eval in a compiled >> program; kind of defeats the purpose of compling. You might let it >> run in its own namespace so it can only affect certain objects. > > I reiterate my comments regarding type declarations, add new comments > regarding backwards compatibility, and note that Lisp allows eval in > compiled code. It's highly frowned upon cause it interferes with everything it touches. -- CARL BANKS http://www.aerojockey.com/software "If you believe in yourself, drink your school, stay on drugs, and don't do milk, you can get work." -- Parody of Mr. T from a Robert Smigel Cartoon From liquid at kuht.it Thu May 20 16:47:51 2004 From: liquid at kuht.it (Gian Mario Tagliaretti) Date: Thu, 20 May 2004 22:47:51 +0200 Subject: stat module Message-ID: <200405202247.51967.liquid@kuht.it> Hi guys, maybe is an easy question but there is something I haven't understood I will post the example for better explain Python 2.3.4c1 (#2, May 13 2004, 21:46:36) [GCC 3.3.3 (Debian 20040429)] >>> import os >>> mode_list = os.lstat('/etc/passwd') >>> import stat >>> mode = stat.S_IMODE(mode_list[0]) >>> print mode 420 now if I chech the permission on /etc/passwd I get liquid at debian:~$ ls -la /etc/passwd -rw-r--r-- 1 root root 1077 Apr 28 17:48 /etc/passwd liquid at debian:~$ which is a 644 file permission. I've tried to read very carefully the manual and the module description but there is something that probably I don't understand Thank's for any help Mario aka Liquid From iamlevis3 at hotmail.com Wed May 12 12:22:22 2004 From: iamlevis3 at hotmail.com (Chris) Date: 12 May 2004 09:22:22 -0700 Subject: newb: object factory, and iteration Message-ID: <939f49f8.0405120822.7a22e1b6@posting.google.com> I'm developing a thing that gathers data as follows: 1. For all files of a certain name: I. for all lines in each of those files: i. split the /-separated values in each of those lines, and stuff them into a list (or dict or whatever) ... and this is for a hundred or so such files of that name, with each file having a hundred or so of such lines, with each line having 10 or so of such /-sep'd values. I thought that an instructive way of doing this would be to have a class describing each of these files and their contents, and create a new instance of this class for each file. As I'm writing this, it occurs to me that I could stick to a numbered naming convention (e.g., df1, df2, etc) for when I need to access this data later in the program. But is there a way for me to list all instances of a certain class? I.e., if the classname were FileInfo, and I had hundred objects of that class, could I somehow loop: for all objects created from FileInfo do some stuff TIA for any help. I'll get used to Python sooner or later =) -cjl From roy at panix.com Tue May 25 08:16:45 2004 From: roy at panix.com (Roy Smith) Date: Tue, 25 May 2004 08:16:45 -0400 Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> <Mbrsc.15253$bF3.12865@fed1read01> <m2k6z1ejcc.fsf@unique.phony.fqdn> <ad052e5c.0405242249.bc8fcf6@posting.google.com> Message-ID: <roy-A822B2.08164525052004@reader2.panix.com> danb_83 at yahoo.com (Dan Bishop) wrote: > Or credit card numbers. They're 16 digits long, and Microsoft Excel > has this inconvenient feature of displaying them with 15 significant > digits. I'm not sure credit card numbers are really numbers. I think of them more as strings. The fact that they're made up only of digits is almost meaningless, since you don't generally do any arithmetic operations on them. You record them someplace and spit them back when needed. Even as database keys, you're more likely to hash them than to use their arithmetic value directly. One common operation is to figure out which vendor owns a certain number, and you do that by looking at the first four digits. Thinking of it as a string, you would do "substring (digitString, 0, 4)". Thinking of it as an integer, you would do "int (value / 1000000000)". Which would you do? Another common example of digit strings which aren't really numeric values is a telephone number. If I've counted properly, to call a number in London, England using my calling card, I need to dial 31 digits (access number + 01 + country code + local number + auth code + PIN). Sure, they're all digits, but I think any sane system would store that as a string, especially given that the only operation I ever want to do with the sub-parts is concatenate them in various ways. From leoel at gmx.at Wed May 26 06:56:21 2004 From: leoel at gmx.at (Leopold Schwinger) Date: Wed, 26 May 2004 12:56:21 +0200 Subject: Some Newbie Questions Message-ID: <40b47710@e-post.inode.at> Hello! I am a really newbie to python, and I have some questions. I couldn't find anything in the manual, so it would be nice if you could help me. (1) Is there any operator in Python in order to call a Member-Function from a class without creating an instance of the class? (In C++ and PHP there ist this operator "::" <class>::<memberfunction>) (2) Is there any way to dynamically import modules, where the name of the module is not known during implementation but can be defined durch scipt execution? Think of lots of different config-Files, which differ by Path & Name but the variables are all named equal, and i want to import a special config-File during the execution of the script. (3) Is there any way to obtain a kind of "trace"-Info (the actual filename and codeline) in order to provide some debug-Info in the case of errors (In C++ and PHP there are these "__line__" and "__file__" functions, For Python I have only found <Class>.__dict__ and dir(<Class>)) Thank you very much, Leo From tdelaney at avaya.com Tue May 18 23:25:04 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 19 May 2004 13:25:04 +1000 Subject: Is WeakValueDictionary thread-safe? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0180DABC@au3010avexu1.global.avaya.com> Luke wrote: > Is weakref.WeakValueDictionary supposed to be thread-safe? No, nor are any of the other built-in mutable types. If you want thread-safety, you need to deal with it yourself. There is a thread-safe data structure in the standard library - Queue.Queue. > This small example script (attached) uses two threads to add and > remove items from a WeakValueDictionary. It is giving me a number of > error messages on stderr (with 2.3.3 & 2.3.4rc1) which look like this: > > Exception exceptions.KeyError: 'bar' in <function remove at > 0x4017372c> ignored > > Should this work without printing these errors, or have I > misunderstood? I just wanted to check with this newsgroup before > filing a bug... You've misunderstood. Tim Delaney From roy at panix.com Thu May 20 21:45:42 2004 From: roy at panix.com (Roy Smith) Date: Thu, 20 May 2004 21:45:42 -0400 Subject: Confused about while statement References: <dHcrc.86491$536.14466932@attbi_s03> <40AD5DF2.69F2015A@alcyone.com> Message-ID: <roy-B1E954.21454120052004@reader2.panix.com> In article <40AD5DF2.69F2015A at alcyone.com>, Erik Max Francis <max at alcyone.com> wrote: > EAS wrote: > > > In theory, the following code should ask for the user to enter a value > > for h > > until he/she enters hello or goodbye. > > > > h = "hi" > > while h != "hello" or "goodbye": > > h = raw_input("Value for h:") > > > > But the program keeps asking for a value no matter what I enter. Why > > doesn't > > it work? > > You meant > > while h != "hello" and h != "goodbye": ... Or, perhaps even better, while h not in ("hello", "goodbye"): The meaning is the same, but I think idiomatically, it's a closer match to the way you would say it in natural language. From resin-interest-request at caucho.com Tue May 25 20:11:21 2004 From: resin-interest-request at caucho.com (resin-interest-request at caucho.com) Date: Tue, 25 May 2004 17:11:21 -0700 (PDT) Subject: Your mail to resin-interest-request@caucho.com In-Reply-To: <20040526001037.58B052FEB1@caucho.com>, from python-list@python.org Message-ID: <20040526001121.A974230052@caucho.com> This pre-recorded message is being sent in response to your recent email to resin-interest-request at caucho.com. All routine administrative requests (including subscriptions and unsubscriptions) concerning this mailing list are handled by an automated server. Please read this message carefully to find the information relevant to you. SUBSCRIBING =========== To subscribe to resin-interest, send the following in the body (not the subject line) of an email message to "Majordomo at caucho.com": subscribe resin-interest This will subscribe the account from which you send the message to the resin-interest list. If you wish to subscribe another address instead (such as a local redistribution list), you can use a command of the form: subscribe resin-interest other-address at your_site.your_net UNSUBSCRIBING ============= To unsubscribe from resin-interest, send the following in the body (not the subject line) of an email message to "Majordomo at caucho.com": unsubscribe resin-interest This will unsubscribe the account from which you send the message. If you are subscribed with some other address, you'll have to send a command of the following form instead: unsubscribe resin-interest other-address at your_site.your_net If you don't know what address you are subscribed with, you can send the following command to see who else is on the list (assuming that information isn't designated "private" by the owner of the list): who resin-interest If you want to search non-private lists at this server, you can do that by sending a command like: which string This will return a list of all entries on all lists that contain "string". HELP ==== To find out more about the automated server and the commands it understands, send the following command to "Majordomo at caucho.com": help If you feel you need to reach a human, send email to: resin-interest-approval at caucho.com From sean_berry at cox.net Tue May 11 21:27:03 2004 From: sean_berry at cox.net (Sean Berry) Date: Tue, 11 May 2004 18:27:03 -0700 Subject: sending out XML from python. Message-ID: <03foc.111778$Jy3.44600@fed1read03> I am going to be doing some programming with a Flash programmer in my company. Most of the online docs about integrating Flash with another language use PHP. I am not a fan of PHP. What I would really like to do is use Python to create data in the form of XML to send back to Flash, since Flash MX has the ability to easily parse XML to get variables and values. I have done some reading on XML in Python, but only stuff I have seen has been geared toward reading in XML data, not spitting it out. Is there a module for doing this? I know that I can make something that would work, but wondered if it is already done. Thanks From ciccio at smilzo.net Thu May 6 10:33:35 2004 From: ciccio at smilzo.net (Fabio Corneti) Date: Thu, 06 May 2004 14:33:35 GMT Subject: PyQT developement for Windows References: <Aramc.39435$Qc.1546143@twister1.libero.it> <mailman.284.1083787533.25742.python-list@python.org> Message-ID: <31smc.40814$Qc.1595111@twister1.libero.it> Phil Thompson wrote: > It's up to you how you license your own application so there is no problem > with dual licensing it - the GPL and one that is compatible with a Windows > version of Qt and PyQt. So if I dual license the application as GPL under Linux and friends, and under a freeware license for Windows there should be no problems? Is there some application written in PyQT for Linux and Windows with a similar approach? -- ---------------------- Fabio Corneti ciccio at smilzo.net ---------------------- From peter at engcorp.com Fri May 14 07:16:01 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 May 2004 07:16:01 -0400 Subject: appending to dict In-Reply-To: <95f72778.0405140140.662d63fc@posting.google.com> References: <95f72778.0405140140.662d63fc@posting.google.com> Message-ID: <Hd6dnYZNj4_pNzndRVn-tA@powergate.ca> bucket79 wrote: > is there anyway appending to dictionary? > list has this feature > >>>>a = [] >>>>a.append(1) >>>>print a > [1] > > but dictionary can't > i wanna do like this thing > >>>>a = {1, 2} >>>>a.append(3, 4) -> This is just my idea :@ >>>>print a > {1:2, 3:4} Did you know that the following actually works? >>> a = {1: 2} # note: your syntax was wrong here >>> print a {1: 2} >>> a[3] = 4 >>> print a {1: 2, 3: 4} Since, as Holger pointed out, dictionaries aren't ordered, the concept implicit in "append" doesn't apply. The more appropriate concept "update", however, can be spelled either dict.update(), or like what I just showed, for dictionaries. -Peter From jepler at unpythonic.net Sat May 15 10:40:47 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 15 May 2004 09:40:47 -0500 Subject: web security question. In-Reply-To: <40A623E7.50807@cfl.rr.com> References: <40A623E7.50807@cfl.rr.com> Message-ID: <20040515144047.GB2832@unpythonic.net> There's no reason to believe that the implementation of Python, written in C, is free from buffer overflow bugs, string format bugs, or any other of the classes of bugs that affect C programs. There's no reason to believe that the implementation of Python doesn't behave according to documentation (in the case of some built-in type, standard module, or language feature), leading to seemingly correct code having security consequences. There's no reason to believe that any particular program written in Python doesn't have bugs that could negatively impact security. That said, I'm generally positive about Python security. The basic implementation is pretty solid (important object types, like dicts, lists and strings are all dynamically-sized and this code is tested every day by every Python user), there is a large test suite, the documentation tends to match the implementation closely, and programs written in the Python language do not perform the kinds of low-level operations that lead to buffer overflow bugs. Jeff From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon May 24 10:17:35 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 24 May 2004 16:17:35 +0200 Subject: Get Amount of Physical Memory References: <c8ssfm$95h$1@solaris.cc.vt.edu> Message-ID: <c8t096$a8p$1@news-reader4.wanadoo.fr> Hi ! Windows or other ? For windows, you can use WMI. @-salutations -- Michel Claveau From jmcalvar at telecable.es Wed May 12 06:33:16 2004 From: jmcalvar at telecable.es (=?ISO-8859-1?Q?Jos=E9?=) Date: Wed, 12 May 2004 12:33:16 +0200 Subject: process Message-ID: <c7suic$mi1$1@nsnmpen3-gest.nuria.telefonica-data.net> I have a farm with 4 web servers. I want to write a client-server program to rotate logs. Basically the server has only one file, if I run it, the server listens. The client has 2 files, one client and another server. If the log is greater than xxx bytes, then the client send a message to the server, then the server send another message to all the webservers, and they must to rotate logs. I'm too new in Python and I don't know a lot of modules, so the problem is: how can I know which processes are running?. I writed all, but I want that the "client server" look at the processes. In case it's rotating logs, it must pause all. In bash it could be: #ps ax|grep rotatelogs But how in Python? thanks in advance From paul at prescod.net Wed May 26 06:43:31 2004 From: paul at prescod.net (Paul Prescod) Date: Wed, 26 May 2004 03:43:31 -0700 Subject: Prothon should not borrow Python strings! In-Reply-To: <10b54lm45adrpab@corp.supernews.com> References: <mailman.241.1085435467.6949.python-list@python.org> <10b54lm45adrpab@corp.supernews.com> Message-ID: <40B474D3.6050909@prescod.net> [trying to migrate to prothon-user] > Mark Hahn wrote: > >>Wow, thanks, this is some really great stuff. I'm going to have >>to go off and study up on it. >> >>This may be a stupid question, but couldn't I have many "types" >>of strings and some be 8-bits, some 16-bits, and some 32-bits? >>Couldn't normal method overloading handle the type conversion? >>Why is there all this confusion? Isn't this what object-centric >>computing is designed for? First, you could have different strings, but it wouldn't help with the API question. The goal is that every time you work with "human language strings" you work with Cantonese as easily as English which means (at the very least) character ordinals up to 2**16 in any API dealing with text. Second, having multiple types of strings complicates things, just as having multiple types of anything does. Third, the only difference between 16-bit and 32 bit strings is memory usage: shouldn't that be an implementation detail rather than a choice each programmer needs to make? Michael Geary wrote: > In fact, there are several different encodings for Unicode strings: UTF-8, > UTF-16, and UTF-32. UTF-16 and UTF-32 each come in big-endian and > little-endian variations, or a Byte Order Mark (BOM) at the beginning of the > string can be used to tell you which it is. > > UTF-8 is pretty nice for a lot of purposes. It includes the 7-bit ASCII > character set unchanged and avoids the endian problems. You could specify > that Prothon source code uses UTF-8, although you'd still want to support > the other UTFs for data. Right, but the issue of what encoding the data used in a file is orthogonal to the issue of how many runtime types there should be in Prothon. Paul Prescod From brian at dorseys.org Thu May 20 01:19:02 2004 From: brian at dorseys.org (Brian Dorsey) Date: Wed, 19 May 2004 22:19:02 -0700 Subject: NORTHWEST PYTHON SPRINT June 19-20, 2004 Bellevue, Washington, USA Message-ID: <20040520051902.GA9830@dorseys.org> SeaPIG (the Seattle Python Interest Group) is excited to announce the NORTHWEST PYTHON SPRINT June 19-20, 2004 Bellevue, Washington, USA The cost is free thanks to our host Construx Software. There will be a large, comfortable room seating 50+ people at tables, wireless and wired Internet access, and a projector for demonstrations. We're currently looking for coaches to lead sprints, as well as a count of the number who might attend. The main day is Saturday (9am-5pm), but we've also reserved the room for Sunday in case people want more time. There will also be a time Saturday morning for lightning talks and demonstrations (both non-commercial and commercial). What is a sprint? A sprint is a group of people who gather for a day or more to work on a common software project. The members choose individual tasks and usually work solo or in pairs in the same room, then get together periodically to compare notes. We'll follow the model that has worked successfully at the past several Python conferences: several groups working on different projects in the same room. Past sprints have done development work on the Python core, Twisted, Docutils, Webware, Zope, Chandler, etc. Most projects have a variety of tasks that need to be done -- coding modules, designing test suites, squashing bugs, writing user documentation and developer documentation, brainstorming design strategies, planning promotional activities, etc -- so there's something for every skill level. You'll need to bring a laptop, or if you don't have one you can pair with somebody who does. So far there's one sprint scheduled, on Twisted. A few Twisted newbies will be writing an application to get their heads around this asynchronous beast. (We could really use somebody with more expertise around, hint, hint.) If you'd like to coach a sprint, sign up to attend, propose a lightning talk or demonstration, or just get more information, see our wiki page: http://seapig.org/NorthwestPythonSprint or contact: Brian Dorsey <brian at dorseys.org>, 206-619-6975 Mike Orr <mso at oz.net>, 206-240-4250 Construx is located at 11820 Northup Way #E200, Bellevue WA 98005. It's eight miles from downtown Seattle; twenty from Sea-Tac Airport. Carpools and homestays are available if you contact us in advance. From hadi at nojunk.com.au Fri May 14 10:24:04 2004 From: hadi at nojunk.com.au (Hadi) Date: Sat, 15 May 2004 00:24:04 +1000 Subject: beginner's question References: <c82d51$78s$1@lust.ihug.co.nz> <Xs3pc.34385$dr1.943764@news20.bellglobal.com> Message-ID: <c82kae$auh$1@lust.ihug.co.nz> Sean, file-1 contains about 500 lines. Also when I run the below script, I am getting following error in the command line: File "<stdin>", line 1 python test.py SyntaxError: syntax error Any suggestion about this? Thanks again. hadi > lexicon = ["our", "list", "of", "words", "to", "be", "compared"] > > # open the source and destination files > src = file("file1/path") # open for reading > dst = file("file2/path", 'w') # open for writing > > # Hadi: does file1 contain one or more lines? This only works for one line. > # For more lines, you'll need to do further processing ... > # > # Make a list of the words in src. We split the line at each comma, and > # remove any excess whitespace from around the word > words = [w.strip() for w in src.readline().split(',')] > > # Now we see if the words are in our list and write the results to dst > for w in words: > dst.write(str(w in lexicon)) # writes 'True, ' or 'False, ' > > # Python will eventually close the files for you, or you can do it > explicitly > src.close() > dst.close() > > > > Hope that helps, > > Sean > > From opengeometry at yahoo.ca Wed May 12 00:13:58 2004 From: opengeometry at yahoo.ca (William Park) Date: 12 May 2004 04:13:58 GMT Subject: Processing huge datasets References: <79Knc.15953$k4.322398@news1.nokia.com> <c7o3th$6lh$1@panix2.panix.com> <40a13353$0$267$edfadb0f@dread16.news.tele.dk> Message-ID: <2gdmk5F1kvc9U1@uni-berlin.de> Anders S. Jensen <doozer at freakout.dk> wrote: > I'm trying to produce a system that will analyze a filesystem for > 'dead leafs', large data consumption, pr. UID volume consumption, > trend analysis, etc. > > To do that I first save each directory along with sum of C, M and A > timestamps for the files in the directory (all in epoch secs.), number > of files, volume of files, list of UID's, list of GID's, dict of > volume pr. UID, dict of volume pr. GID and newest file. > > Then I build a hierarchy of instances that knows it's parents, > children and siblings. Each object is populated with the summarized > file information. When that is done, I traverse the hierarchy from > the bottom up, accumulating average C, M and A times, Volumes and > number of files. > > This hierarchy allows me to instantly query, say, the average > modification time for any given point in the directory structure and > below. That'll show where files that havent been modified in a long > time hides, and how much space they take amongst other things. > > The LCRS tree lends itself very well for recursion in terms of beauty > and elegance of the code. However keeping that amount of data in > memory obviously just doesn't fly. > > I'm at a point where the system actually just *barely* might work. > I'll know tomorrow when it's done. But the system might be used to > work on much larger filesystems, and then the party is over. > > I'm looking for the best suited way of attacking the problem. Is it a > memory map file? A Berkeley DB? A specially crafted metadata > filesystem? (that would be fun but probably overkill..:) or something > completely different. How about good old textfile in filesystem, ie. /some/dir/.timestamp ? This way, you don't use up memory, you get hierarchial data structure automatically, no need to mess with database interface, simple search mechanism, etc. And, most of all, no need to ask other people who have absolutely no idea what you're talking about... :-) > > The processing might be switched to iterative, but that's a 'minor' > concern. The main problem is how to handle the data in the fastest > possible way. > > Thanks for your pointers! > > Cheers, Anders -- William Park, Open Geometry Consulting, <opengeometry at yahoo.ca> Linux solution/training/migration, Thin-client From matthiasjanes at gmx.net Tue May 11 02:37:30 2004 From: matthiasjanes at gmx.net (matthiasjanes) Date: 10 May 2004 23:37:30 -0700 Subject: CGI Proplem displaying image References: <d588131f.0405071937.94e4f17@posting.google.com> <c5b3dbee.0405081454.5ef67653@posting.google.com> <d588131f.0405090912.560b51db@posting.google.com> Message-ID: <d588131f.0405102237.15106ea5@posting.google.com> matthiasjanes at gmx.net (matthiasjanes) wrote in message news:<d588131f.0405090912.560b51db at posting.google.com>... > > > > Use sys.stdout for output in CGI scripts. > > Escpecially with binary files. > > Try this and see if the problem goes away > > > > ################# > > #my CGISRIPT: test.py > > > > #! /usr/bin/env python > > > > import sys > > sys.stdout("Content-type: image/jpeg\n\n") > > > > filename="cgi-bin/dog.jpg" > > img = open(filename, 'rb').read() > > sys.stdout.write(img) > > > > ################## > > > > Remember Google is your friend > > http://starship.python.net/crew/davem/cgifaq/faqw.cgi > > > > waldek > Maybe my question was not clear enough: It is for me not a problem to print the Image to screen. (As I said in the beginning) if I use a form with method='post' example: ____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______ ################# #my CGISRIPT: test.py #! /usr/bin/env python print ("Content-type: image/jpeg"); print # End of headers! filename="cgi-bin//dog.jpg" infile = open(filename, 'rb') doginmemory=infile.read() print doginmemory ################## ################# #my html page with the image tag <html> <head> </head> <body> <form name="test" method="post" action="/cgi-bin/test.py" target="_blank"> <input type="submit" name="GO"> </form> </body> </html> ################ ____THIS WORKS FINE AND DISPLAYS ON ONE PAGE THE IMAGE AND ONLY THE IMAGE_______ BUT What I want is that I display the image on an HTML page with text together. tables and ....... something like that ################# #my html page with the image tag <html> <head> </head> <body> Some Text <img type="image" src="/cgi-bin/test.py" height="25" width="111"> some Text </body> </html> ################ A working example code - even very small one would be appreciated Matthias Janes From bnet at ifrance.com Sun May 30 21:26:53 2004 From: bnet at ifrance.com (=?iso-8859-1?q?Beno=EEt_Dejean?=) Date: Mon, 31 May 2004 03:26:53 +0200 Subject: API : constness ? References: <mailman.429.1085920304.6949.python-list@python.org> Message-ID: <pan.2004.05.31.01.26.45.633282@ifrance.com> Le Sun, 30 May 2004 08:31:36 -0400, Tim Peters a ?crit?: > [Beno?t Dejean] >> i don't understand why the ANSI const keyword is never used in the API. > > It is used in the API, and more than once, but it isn't used as often as it > could be used. It's more likely to appear in newer API functions. When > Python was first written, most compilers were K&R, and Python avoided ANSI > features until about a decade later (a C89 compiler is required now). A lot > of the C API survived unchaged across all that time. There's no objection > to slamming in consts now, but nobody has cared enough to bother doing so. it's also for a simple reason, eg using PyArg_ParseTupleAndKeywords using const helps gcc to move these data to the text segment static const char * const kwlist[] = { "uri", "open_mode", "exclusive", "perm", NULL }; or a better (but tricky) storage could be used to avoid relocation bust casting again again like this PyArg_ParseTupleAndKeywords(args, kwargs, "should be const char *", (char**)kwlist, ... is quite ugly ... From winexpert at hotmail.com Wed May 12 15:46:59 2004 From: winexpert at hotmail.com (David Stockwell) Date: Wed, 12 May 2004 19:46:59 +0000 Subject: Why is a None appearing in my output? Message-ID: <BAY2-F27iTkK8tjAsdR000121d1@hotmail.com> Hello, I'm a fairly new user of python. I am going through the tutorial on the python.org website and observed a weird thing around the 6.0 modules area. (http://docs.python.org/tut/node8.html) My python version: Python 2.2.3 (#1, Feb 26 2004, 14:37:42) [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 I entered the following text into a 'module file' and saved it: def fib6(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b else: print "done b[",b,"], n[",n,"], a[", a,"]" print "fib6:", fib6(50), "---" print "next" I then run it and get the results: fib6: 1 1 2 3 5 8 13 21 34 done b[ 55 ], n[ 50 ], a[ 34 ] None --- next The question I'm having is what is causing the 'None' to print? The example tutorial doesn't have the None, but when I run I am seeing it and I do not see what causes that. I added the 'else on the while and the "---" stuff to try to figure out what the None means. but i have no clue ... Thanks David _________________________________________________________________ Getting married? Find tips, tools and the latest trends at MSN Life Events. http://lifeevents.msn.com/category.aspx?cid=married From ajsiegel at optonline.com Fri May 21 21:34:06 2004 From: ajsiegel at optonline.com (Arthur) Date: Sat, 22 May 2004 01:34:06 GMT Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <40ae3ebe$0$17254$a1866201@newsreader.visi.com> <mailman.156.1085167577.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> Message-ID: <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> On Sat, 22 May 2004 01:07:05 GMT, Arthur <ajsiegel at optonline.com> wrote: >On Fri, 21 May 2004 13:30:23 -0700, Shalabh Chaturvedi ><shalabh at cafepy.com> wrote: > >>I believe it is conceptual homogeneity and not type homogeneity that >>characterises the difference between lists and tuples. > >"conceptual homogeneneity" defined - as far as I see it - by >reference to whether a rational Python programmer would group the >objects together in a list. > >A perfect tautology. > >Which always seems to me to create more confusion, than clarification. > Further to what bothers me here: Can't it be said, in helping to distinguish a Python list from the standard collections in, say, Java and C++ - that among its most important attributes is the ease with which one can work with a list as a collection of objects of *heterogenous* type. "Type" here being used in the sense that programmers generally use the word. In exploring Python early on, I found this to be a core feature, and a real attraction. Am I missing something again? Art From simoninusa2001 at yahoo.co.uk Sun May 23 01:53:01 2004 From: simoninusa2001 at yahoo.co.uk (simo) Date: 22 May 2004 22:53:01 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> Message-ID: <30260531.0405222153.5027c135@posting.google.com> One thing that might attract me from Python to Prothon is if it had proper private medthods - i.e. not just name mangling like __myDef which can be overridden using _myClass__myDef (as the interpreter does). Proper encapsulation is needed before the C++ brigade will take P[y/ro]thon seriously as an OO language, oh and a machinecode compiler ;-) From kwharrigan at yahoo.com Thu May 20 13:02:00 2004 From: kwharrigan at yahoo.com (Kyle Harrigan) Date: 20 May 2004 10:02:00 -0700 Subject: GetClipboardData(CF_BITMAP) unimplemented Message-ID: <90924643.0405200902.610baf23@posting.google.com> Win32all folks: I am attempting to use win32all to perform screen captures and save the bitmap to a file. The call to GetClipboardData fails saying GetClipboardData(CF_BITMAP) is unimplemented. Any ideas? My code looks something like this: win32api.keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0) win32clipboard.OpenClipboard() format = win32clipboard.EnumClipboardFormats() data = win32clipboard.GetClipboardData(format) win32clipboard.CloseClipboard() writeFile = open('outfile.bmp','w') writeFile.write(data) writeFile.close() From mike at nospam.com Fri May 7 13:38:02 2004 From: mike at nospam.com (Mike Rovner) Date: Fri, 7 May 2004 10:38:02 -0700 Subject: Debuggin a ptyhon extension References: <rzxmc.26524$j11.254148@weber.videotron.net> Message-ID: <c7ghhq$u4r$1@sea.gmane.org> Steve Menard wrote: > I am writing a python extension module in VC++ on windows. At some > point, my extension crashes. Welcome to the club. :) > Now I want to debug exactly why. I built the python projects in VC++, > and put the resulting python_d.exe in my ptyon home directory, and the > python23_d.dll in the windows/system32 directory. I also tried to put > the python23_d.dll in python's home directory, to the same result. > > Problem is, running my scripts/extension with python_d.exe, it always > complains it can't find win32api. Yes, I am using win32API to preload > a dll, and can't really get rid of it. > > To try and solve this, I tried replacing the "stock" python.dll with > my python_d, so at least VC++'s debugger would see the debug info. > but I got the same result, of win32api not being found ... "Everyone is getting lost to the measure of his abilities" (c) You choosed the hard way. > What is the best way to go about this? My extension will require a > fair amount of native code and interacting with the Python code, so > being able to trace into python would be invaluable. Here what I did: - Compile you _extension_ in debug mode. Name the output "myext.pyd". - Call it with simple test script from dos (hopefully cmd) prompt: python testmyext.py import myext stop=raw_input('connect now') myext.run_crash_func() -As script puses and prompt for input switch to VS and debug attach to running process. (Menu Tools/Debug Processes...; select your running python.exe and press Attach) Set appropriate breakpoints in your ext code. Continue. -Switch to script and press Enter. -Get breaked in C++ and enjoy debugging. > Are my problems caused because python 2.3.3 (and possible win32all) > were build using VC.net? I use to debug my extensions with stock python (2.2.x & 2.3.x - both compiled with MSVC6). I use MSVC7.1. However I don't use FILE* between extension boundaries. No problems so far. > I am grateful for any help you guys can provide. Hope this helps, Mike PS. If anybody is interested, there is a way to debug extension not leaving VS at all: In the extension solution properties set Debugging: -Command (extenal program) python.exe -Command Arguments: testmyext.py (or whatever your calling script is) and just hit Run to debug your code. From benn at cenix-bioscience.com Tue May 25 03:30:25 2004 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 25 May 2004 09:30:25 +0200 Subject: How to close a process in win32 Message-ID: <40B2F611.9080504@cenix-bioscience.com> Hello, I'd make a call between the processes - you can have the deamon listen on a port and the GUI app can then send a shutdown message onto that port (there are obviously much fancier ways of doing this - I just picked the most bread and butter one). This will allow you to shut down your deamon in an organised fashion - I don't know if the terminate process functions calls the TerminateProcess function in the win32api but it is not a recommended way of closing your process. If you wish more info on closing your app in win32 goto - (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/terminateprocess.asp). Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 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 tjreedy at udel.edu Fri May 21 15:08:10 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 May 2004 15:08:10 -0400 Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il> Message-ID: <c8lk2s$ede$1@sea.gmane.org> "Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message news:c8l3s3$27o$1 at news.iucc.ac.il... > Many times I find myself asking for a slice of a specific length, and > writing something like l[12345:12345+10]. > This happens both in interactive use and when writing Python programs, > where I have to write an expression twice (or use a temporary variable). With an expression, I'd go for the temp var. > Wouldn't it be nice if the Python grammar had supported this frequent > use? I take this as 'directly support' versus the current indirect support via start+len. My answer: superficially (in isolation) yes, but overall, in the context of Python's somewhat minimalistic grammar/syntax, no. Two ways to slice might easily be seen as one too many. In addition, the rationale for this, your favorite little addition, would admit perhaps 50 others like it. > My idea is that the expression above might be expressed as l[12345:>10]. Sorry, this strike me as ugly, too much like and easily confused with l[12345:-10], and too much looking like a syntax error. Given that some other languages slice with (start,len) arguments (but not then, that I remember or know of, also with a start,stop option), I am *sure* that Guido thought carefully about the issue. A plus with his choice is ability to offset (index) from the end *without* calling the len function. > This change, as far as I can see, is quite small: it affects only the > grammar and byte-compiling, and has no side effects. Except the cognitive dissonance of two *almost* identical syntaxes and the flood of other 'small', 'no side effect' change requests. > Well, what do you think? I would like to hear your comments. Your wish ... Terry J. Reedy From holger.tuerk at gmx.de Thu May 6 11:17:31 2004 From: holger.tuerk at gmx.de (=?UTF-8?B?SG9sZ2VyIFTDvHJr?=) Date: Thu, 06 May 2004 17:17:31 +0200 Subject: Scope rule pecularities In-Reply-To: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> Message-ID: <c7dks7$3eh$02$1@news.t-online.com> Hello Antoon, Antoon Pardon wrote: > Well to test things out I wrote the following: > > > class Int: > > def __init__(self, v): > self.value = v > > def __add__(self, term): > return Int(self.value + term.value) > > def __iadd__(self, term): > self.value += term.value > return self.value This should be "return self". > > def __str__(self): > return `self.value` return "Int %i" % self.value here will make it obvious. > > a1 = Int(14) > a2 = Int(15) > b = Int(23) > > print a1, a2 > > def foo(): > > a1 += b > a2.__iadd__(b) > > foo() > > print a1, a2 > > > Now the a1 += b line doesn't work, it produces the following error: > > UnboundLocalError: local variable 'a1' referenced before assignment. > > The a2.__iadd__(b) line however works without trouble. > > > Now I think I understand what is causing this, but I think this > kind of thing shouldn't happen. If a += b is just syntatic sugar > for a.__iadd__(b) then the first should be acceptable where the > second is acceptable. > a1 += b is not a shortcut for a1.__iadd__ (b) but for a1 = a1.__iadd__ (b) with the advantage of a1 evaluated only once. So, a1 is assumed to be locally available in foo (). Greetings, Holger From heikowu at ceosg.de Tue May 18 09:09:34 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Tue, 18 May 2004 15:09:34 +0200 Subject: Regexp to enclose text with P-tag In-Reply-To: <fc5622cb.0405180458.3c2dbe35@posting.google.com> References: <fc5622cb.0405180458.3c2dbe35@posting.google.com> Message-ID: <200405181509.34374.heikowu@ceosg.de> Am Dienstag, 18. Mai 2004 14:58 schrieb SubZane: > lorem ipsum <img src="image.gif" />dolor > > should become: > > <p>lorem ipsum</p><img src="image.gif" /><p>dolor</p> As far as I can see, there's no way to do this using Regexps... What you'd better do is parse the HTML using sgmllib, and on continuous data sections just output <p> <yourdata> </p>, and output each start/stop tag as it was in the sources. HTH! Heiko. From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Sat May 15 18:55:03 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Sun, 16 May 2004 00:55:03 +0200 Subject: Warning when testing 2.3.4c1 References: <m2brkph623.fsf@pchoel.psh> Message-ID: <c8675g$bjd$1@news-reader5.wanadoo.fr> 11 feb.04 14h.47 From grante at visi.com Tue May 25 10:56:58 2004 From: grante at visi.com (Grant Edwards) Date: 25 May 2004 14:56:58 GMT Subject: why i References: <40b2e204$1_1@news.iprimus.com.au> <slrncb5s1p.21a.bignose-hates-spam@rose.localdomain.fake> <Xns94F45CB2C1E18duncanrcpcouk@127.0.0.1> Message-ID: <slrncb6nlp.jiu.grante@grante.rivatek.com> On 2004-05-25, Duncan Booth <me at privacy.net> wrote: > The actual reason why everyone uses I and then J as the for loop indexes > was that Fortran, by default, assumed all variables starting with letters > from I-N were integer, That that was because people always used i,j,k as indexes. -- Grant Edwards grante Yow! Did you find a at DIGITAL WATCH in YOUR box visi.com of VELVEETA?? From geloilzi at hotmail.com Tue May 4 13:39:48 2004 From: geloilzi at hotmail.com (Gelo Ilzi) Date: Tue, 4 May 2004 19:39:48 +0200 Subject: problem with fnidl Message-ID: <c78h1m$mcs$1@news2.netvision.net.il> I installed fnorb (python corba) on my PC (WinXP). For some unclear reason fnidl (idl to python interpretator) does nothing. It doesn't produce any warning, error message. Project skeleton isn't built also. Any idea what's wrong? From bm007 at gmx.de Sat May 15 13:24:01 2004 From: bm007 at gmx.de (boris m) Date: 15 May 2004 10:24:01 -0700 Subject: MacPython applet problem References: <32e55451.0405100202.508aa914@posting.google.com> <mailman.393.1084187871.25742.python-list@python.org> Message-ID: <32e55451.0405150924.2a50083d@posting.google.com> After some tinkering with AppleScript, I found a workaround for my problem. I think it is worth sharing, so here we go... As Ronald pointed out, python applets currently do not support input/output functions like 'input' or 'print'. Of course, I could run the script from the command line, but then I would not have a nice drag and drop feature. I wanted to have both drag/drop (via sys.argv) *and* input/output functions. So I wrote an AppleScript droplet that allows me to do this. The droplet is currently limited to accept just one item, but it could easily be extended. This was one of my first explorations into AppleScript, so I am more than open to suggestions and improvements. Boris --- --> save as application on open dropItem set itemPath to POSIX path of dropItem set itemPathStr to (itemPath) as string set itemPathCLI to textReplace(itemPathStr, " ", "\\ ") tell application "Finder" set currentMacFolder to (container of (path to me)) as alias set currentFolder to POSIX path of currentMacFolder set folderPath to (currentFolder) as string end tell set folderPathCLI to textReplace(folderPath, " ", "\\ ") --> don't forget chmod +x myscript.py --> myscript.py is in the same directory as the droplet set scriptPath to folderPathCLI & "myscript.py" & " " & itemPathCLI activate application "Terminal" tell application "Terminal" do script scriptPath end tell end open on textReplace(theText, srchStrng, replStrng) tell (a reference to AppleScript's text item delimiters) set {od, contents} to {contents, {srchStrng}} try set {textList, contents} to {(text items of theText), {replStrng}} set {newText, contents} to {(textList as text), od} return item 1 of result on error errMsg number errNbr set contents to od error errMsg number errNbr end try end tell end textReplace >> My problem is that I the script needs some user input (I want to drag >> some >> text files to the applet and then specify some changes). For the user >> input >> I am using: >> >> inputStr = raw_input("Enter a number: \n>>> ") >> >> This, however, seems to produce the error. > > That's right. I'm pretty sure applets on OSX do no (yet) support user > input/output using the input function and print statement. > > IIRC this is on the TODO list for the next release of MacPython. > > B.T.W. with MacPython the default action for .py file is to execute > them in a Terminal window, which gives you complete support for input > and print. > > Ronald From vendas.jeansoftware at globo.com Tue May 18 08:07:13 2004 From: vendas.jeansoftware at globo.com (Jean Christian) Date: Tue, 18 May 2004 14:07:13 +0200 Subject: testing Message-ID: <c8cu8c$mat$1@news-reader2.wanadoo.fr> -- test. do not spam please. From simon at metaplay.com.au Thu May 13 22:51:22 2004 From: simon at metaplay.com.au (Simon Wittber) Date: Fri, 14 May 2004 10:51:22 +0800 Subject: Stackless python and microthreads In-Reply-To: <c80qqu$mdp$1@info4.fnal.gov> Message-ID: <200405140242.i4E2gwgr026036@redpill.digitalventures.com.au> >I'm trying to use microthreads under stackless python I'm not sure if this is what you are after, however, I have a simple module that provides a set of miscellaneous python optimization functions, and a lightweight/weightless/micro thread pool using generator functions. (With Priority Scheduling) http://www.metaplay.com.au/MEPH.html You can find a simpler implementation here: http://www.metaplay.com.au/microthreads.html HTH, Sw. From firephreek at earthlink.net Mon May 17 13:38:06 2004 From: firephreek at earthlink.net (firephreek) Date: Mon, 17 May 2004 10:38:06 -0700 Subject: Sqlite syntax Message-ID: <000e01c43c35$b71079a0$6f01010a@Rachel> Is there some documentation out there that actually lists the Sqlite syntax? Or even better, one that crosses over and talks about how it works with python? Sqlite seems quite the nifty little thing, but for some reason, I can't seem to get a list of tables in my databases through a python prompt. Help? And since the databases aren't 'centralized' there's no way of knowing what databases I have floating around is there? Stryder From bm007 at gmx.de Mon May 10 06:02:59 2004 From: bm007 at gmx.de (boris m) Date: 10 May 2004 03:02:59 -0700 Subject: MacPython applet problem Message-ID: <32e55451.0405100202.508aa914@posting.google.com> I am running Python 2.3 on Mac OS 10.3. My problem is that applets don't seem to work. If I run a python script in the terminal, everything is fine. If I run the same script as an applet, nothing happens. The applet starts up, but dies after a second or two. I used applets quite frequently unter OS9 and never had a problem with them. Has anyone any idea why applets on OS X don't work the way they did in OS 9? Thanks in advance, Boris From gumuz at NO_looze_SPAM.net Mon May 3 06:23:23 2004 From: gumuz at NO_looze_SPAM.net (Guyon Morée) Date: Mon, 3 May 2004 12:23:23 +0200 Subject: Outlook .msg file reader References: <40961b94$0$5249$4d4ebb8e@news.nl.uu.net> Message-ID: <40961d9c$0$5244$4d4ebb8e@news.nl.uu.net> I am sorry, I was supposed to send this to alt.comp.freeware! But, if anyone knows a nice python lib to read .MSG files, I might create this app myself! "Guyon Mor?e" <gumuz at NO_looze_SPAM.net> wrote in message news:40961b94$0$5249$4d4ebb8e at news.nl.uu.net... > Hi all, > > I want to backup my email to a cd. one way to do this is just drag all my > email to a folder and outlook will create .msg files automatically including > their attachments. > > now I want a simple stand-alone reader, which I can burn on the cd as well > so I can view the contents of it without requiring Outlook. If it can search > the contents, that would even be better! > > thanks, > > Guyon Moree > > From tim.one at comcast.net Fri May 14 14:26:07 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri, 14 May 2004 14:26:07 -0400 Subject: how to run an arbitrary function with timeout? In-Reply-To: <2004051413541084557280@k2.sage.att.com> Message-ID: <LNBBLJKPBEHFEDALKOLCMEOJKPAB.tim.one@comcast.net> [Garry Hodgson] > ok, let me rephrase my question. > > i would like a function RunWithTimeout( func, args, timeout ) > i would like it to invoke the function func on arguments args. > if timeout seconds elapse before func(args) returns, i would > like it to raise an exception. if func(args) returns before timeout > seconds, i would like it return the result. AFAICT, you already wrote one. I saw nothing in the output you posted that wasn't exactly as it should be: your func(args) required 10 seconds to run, and your RunWithTimeout function raised an exception after 2 seconds elapsed. That satsifies your "if timeout seconds elapse before func(args) returns" requirment. While you didn't show it, if you changed the call to print RunWithTimeout(snooze, (2,), 10) instead, so that your func(args) took 2 seconds while RunWithTimeout was willing to wait for 10, then the output would be going to sleep -- 2 second pause -- waking up ok and that may or may not satisfy your "if func(args) returns before timeout > seconds, i would like it return the result" requirment (I can't tell, because "result of what?" remains ambiguous -- you might have in mind the return value of RunWithTimeout(), or the return value of func(args)). Again, it would help a lot if you explicitly spelled out what output you *hoped* to get from it. From ville at spammers.com Thu May 13 15:21:25 2004 From: ville at spammers.com (Ville Vainio) Date: 13 May 2004 22:21:25 +0300 Subject: things I wish python could do References: <pan.2004.05.12.20.36.39.451799@sbcglobal.net> <tyfk6zgpx6w.fsf@pcepsft001.cern.ch> <mailman.523.1084466157.25742.python-list@python.org> Message-ID: <du7ekpoyvyi.fsf@mozart.cc.tut.fi> >>>>> "Terry" == Terry Reedy <tjreedy at udel.edu> writes: Terry> Would you really prefer writing <target> = expression as Terry> set('<target>', expression) or as the 'special-form' Terry> pseudofunction call setq(<target>, expression)? Just about Terry> all Python statements are statements because they would Terry> also be a PITA, and possibly more so, as expressions. Couldn't a = 10 still be an expression despite the syntax? Or at least behave like one, i.e. yield a result, probably 10 or None... These days I do think it's not that big a deal, though. Putting assignment into the condition part of while is a habit people will outgrow, and other statements would be very clumsy as expressions. -- Ville Vainio http://tinyurl.com/2prnb From snrkiwi-lists at yahoo.com Wed May 12 11:22:47 2004 From: snrkiwi-lists at yahoo.com (snrkiwi-lists at yahoo.com) Date: Wed, 12 May 2004 08:22:47 -0700 (PDT) Subject: Real-time graphs Message-ID: <20040512152247.68328.qmail@web40001.mail.yahoo.com> I've trolled the lists, FAQs, and Net as a whole, but can't find anything definitive to answer this. We're looking for real-time graph capability (bar, line, etc), so that we can display telemetry from a robot system. There are a bunch of packages out there, but many seem to provide only static graphs (e.g. for scientific, financial data, etc). Does anyone currently display real-time telemetry using Python? Can anyone provide any suggestions? TIA Stephen From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Fri May 28 20:38:37 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sat, 29 May 2004 02:38:37 +0200 Subject: ANN: Pyro 3.4 (remote objects IPC/RPC) Message-ID: <40b7db90$0$559$e4fe514c@news.xs4all.nl> After 9 months since the previous stable release, it's finally time to announce the final release of the next Pyro version: 3.4 ! You can get Pyro 3.4 via http://pyro.sourceforge.net, then go to the SF project homepage download area. Pyro 3.4 is mainly a "polished and tweaked" version. Not many new features are added, but many things have been improved. Users of older Pyro versions are recommended to upgrade. Most important changes: * fixed the SSL example * PYROLOCSSL protocol * no longer required to call initClient() / initServer() in most cases * the Win NT services (nssvc and essvc) can be given command line parameters * documentation improvements * various new examples (user_passwd_auth, filetransfer, rserve) * various other fixes and improvements. For the full list, see the 'changes' chapter in the Pyro manual. Have fun! --Irmen de Jong ---> What is Pyro? Pyro is an acronym for PYthon Remote Objects. Pyro is an advanced and powerful Distributed Object Technology RPC/IPC system, written entirely in Python, and designed to be very easy to use. It is extremely easy to implement a distributed system with Pyro, because all network communication code is abstracted and hidden from your application. You just get a remote Python object and invoke methods on the object on the other machine. Pyro offers you a Name Server, an Event Service, mobile objects, remote exceptions, dynamic proxies, remote attribute access, automatic reconnection, SSL support, a very good and detailed manual, and many examples to get you started right away. From ville at spammers.com Wed May 12 08:44:50 2004 From: ville at spammers.com (Ville Vainio) Date: 12 May 2004 15:44:50 +0300 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> <du7hdum415y.fsf@amadeus.cc.tut.fi> <slrnca3t0e.2asc.kirk@eyegor.jobsluder.net> Message-ID: <du7hdul7r25.fsf@amadeus.cc.tut.fi> >>>>> "Kirk" == Kirk Job-Sluder <kirk at eyegor.jobsluder.net> writes: Kirk> And here is the fundamental question. Why should I spend my Kirk> time writing a module in python to emulate another tool, Kirk> when I can simply use that other tool? Why should I, as a Perhaps you won't; but someone who isn't already proficient with the tool may rest assured that learning the tool really isn't worth his time. awk and sed fall into this category. Kirk> resarcher who must process large quantities of data, spend Kirk> my time and my employer's money reinventing the wheel? You are not reinventing the wheel, you are refactoring it :). I don't think your employer minds you spending 15 extra minutes creating some tool infrastructure, if it allows you to drop awk/sed dependency that your co-workers then won't need to learn. Kirk> I think you are missing a key step. You are starting off Kirk> with a solution (python scripts and modules) and letting it Kirk> drive your needs analysis. I don't get paid enough money to Kirk> write pythonic solutions to problems that have already been Kirk> fixed using other tools. I find writing pythonic tools a relaxing deversion from my everyday work (cranking out C++), so I don't really mind. As long as the time spent is within 5 minutes - 1 hour range. Kirk> I'll be more specific about the challenge. Using only stock Kirk> python with no added modules, give me a script that Kirk> pretty-prints a character-delimted file using one variable Kirk> assignment, and one function. Kirk> Here is the solution in awk: Kirk> BEGIN { FS="\t" } Kirk> {printf("%s %s %s %s", $4, $3, $2, $1)} for line in open("file.txt"): fields = line.strip().split("\t") print "%s %s %s" % (fields[2], fields[1], fields[0]) (untested code warning) Time taken: 56 seconds, give or take. Roughly the same I would expect writing your awk example took, and within the range I expect your employer would afford ;-). Technically it does two variable assignments, but I don't see the problem (ditto with function calls - who cares?) Assignment is conceptually cheap. It doesn't seem any less readable or elegant than your awk example. I could have maybe lost a few seconds by using shorter variable names. -- Ville Vainio http://tinyurl.com/2prnb From shalabh at cafepy.com Tue May 4 21:04:48 2004 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Tue, 04 May 2004 18:04:48 -0700 Subject: Python sets. In-Reply-To: <Pine.LNX.4.44.0405041335170.29617-100000@e5-05.ee.ualberta.ca> References: <Pine.LNX.4.44.0405041335170.29617-100000@e5-05.ee.ualberta.ca> Message-ID: <c79edi$264$1@sea.gmane.org> Grzegorz Dostatni wrote: > I've got a problem. > > Some time ago (I'm a bit fuzzy about the date) I read about sets in > python. I even tried the code. I remember it was something fairly simple - > just a base data type (like list or dictionary). I vaguely remember it > had a syntax similar to creating dictionaries. > > Problem is I can't find it anymore. I've searched around, but it doesn't > seem to exist. I know of "import sets" and creating classes like that, but > I'm sure it was a base data type. No import necessary. There were > operators for basic set operations like set difference, division, etc. You might have read "What's New in Python 2.4" which, as of now, really explains what is *going* to be new in Python 2.4. -- Shalabh From miki.tebeka at zoran.com Mon May 10 03:12:04 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 10 May 2004 09:12:04 +0200 Subject: python -c strangeness Message-ID: <c7n6io$f1r$1@news2.netvision.net.il> Hello All, Can you explain why: [09:06] - adp86: python -c 'import sys; print 1' 1 [09:10] - adp86: python -c 'for i in range(3): print i' 0 1 2 [09:10] - adp86: python -c 'import sys; for i in range(3): print i' File "<string>", line 1 import sys; for i in range(3): print i ^ SyntaxError: invalid syntax Thanks. Miki From ptmcg at austin.rr._bogus_.com Thu May 13 21:30:34 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 14 May 2004 01:30:34 GMT Subject: pyparsing (errata) References: <87fza46evn.fsf@bostjan-pc.mf.uni-lj.si> <XaQoc.102352$hR1.24143@fe2.texas.rr.com> Message-ID: <_iVoc.99699$NR5.77768@fe1.texas.rr.com> > Dang Griffith proposed one alternative construct, here's another, perhaps > more explicit: > lbrack + ( ( ddot + step + ddot + end ) | (ddot + end) ) + rbrack > should be: lbrack + start + ( ( ddot + step + ddot + end ) | (ddot + end) ) + rbrack > Note that the order of the inner construct is important, so as to not match > ddot+end before trying ddot+step+ddot+end; '|' is a greedy matching > operator, creating a MatchFirst object from pyparsing's class library. You > could avoid this confusion by using '^', which generates an Or object: > lbrack + ( (ddot + end) ^ ( ddot + step + ddot + end ) ) + rbrack should be: lbrack + start + ( (ddot + end) ^ ( ddot + step + ddot + end ) ) + rbrack > This will evaluate both subconstructs, and choose the longer of the two. > > Or you can use another pyparsing helper, the delimited list > lbrack + delimitedlist( Word(nums+"."), delim=":") + rbrack at least this one is correct! No, wait, I mis-cased delimitedList! should be: lbrack + delimitedList( Word(nums+"."), delim=":") + rbrack > This implicitly suppresses delimiters, so that all you will get back are > ["1","0.1","1"] in the first case and ["1","2"] in the second. > > Happy pyparsing! > -- Paul > > Sorry for the sloppiness, -- Paul From cthiele at akita.com Thu May 20 10:57:18 2004 From: cthiele at akita.com (cthiele at akita.com) Date: Thu, 20 May 2004 14:57:18 +0000 Subject: access In-Reply-To: <380F6E301I55J21B@python.org> References: <380F6E301I55J21B@python.org> Message-ID: <6D74JJ0IH2DH35H6@akita.com> A lot of people say: "It was really my happy day.It was the day when... ...Yes, when I saw Super H/G/H advertisement". So take a look and find out what it is!! What is Super H/G/H? This is side effects free diet ary supplement that stimulates the Human Growth Hormone reproduction. FDA approved. How Super H/G/H can help me? Here is a brief list of guaranteed effects: - Helps eliminate stress, fatigue and depression - Boosts your immune system - Makes you feel & look younger Is this for me? You definetely need to take Super H/G/H if: you are over 23 years, you often feel yourself tired, your memory becomes weaker, you feel that your immune system needs help. Stresses, irregularity of living... ... http://doctorhelps.com/hgh/index.php?pid=eph9058 fbpxrye zwhqd reuutb makfrlfh ubqpo xrf From ville at spammers.com Tue May 11 01:35:55 2004 From: ville at spammers.com (Ville Vainio) Date: 11 May 2004 08:35:55 +0300 Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <85sme8ug0l.fsf@stowers-institute.org> Message-ID: <du7y8nzbk5g.fsf@mozart.cc.tut.fi> >>>>> "Michael" == Michael Coleman <mkc at stowers-institute.org> writes: Michael> Olivier Scalbert <olivier.scalbert at algosyn.com> writes: >> Jarek Zgoda wrote: >>> Use sed. >>> >> yes, but in python ? Michael> Jarek's answer is the correct one, for almost any real Michael> situation. Not really. Using Python is more portable, and doesn't introduce a new dependency. And if it's trivial in Python, why introduce yet another dependency? -- Ville Vainio http://tinyurl.com/2prnb From __peter__ at web.de Wed May 26 08:45:32 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 May 2004 14:45:32 +0200 Subject: Cleaner idiom for text processing? References: <f2403000.0405251739.2a77b11d@posting.google.com> <c91got$vpi$00$1@news.t-online.com> <Xns94F559D4C3451duncanrcpcouk@127.0.0.1> <c91pft$rl0$04$1@news.t-online.com> <Xns94F5821692826duncanrcpcouk@127.0.0.1> Message-ID: <c923hc$vm3$01$1@news.t-online.com> Duncan Booth wrote: > What happens if someone works out that izip can be made much faster by > consuming its iterators from right to left instead of left to right? That > isn't nearly as far fetched as reading ahead. This would also affect the calling code, when the arguments are iterators (just swapping arguments to simulate the effect of the proposed optimization): >>> ia, ib = iter(range(3)), iter([]) >>> zip(ia, ib) [] >>> ia.next() 1 >>> ia, ib = iter(range(3)), iter([]) >>> zip(ib, ia) [] >>> ia.next() 0 >>> Optimizations that are visible from the calling code always seem a bad idea and against Python's philosophy. I admit the above reusage pattern is not very likely, though. > Passing the same iterator multiple times to izip is a pretty neat idea, > but I would still be happier if the documentation explicitly stated that > it consumes its arguments left to right. >From the itertools documentation: """ izip(*iterables) Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. Equivalent to: def izip(*iterables): iterables = map(iter, iterables) while iterables: result = [i.next() for i in iterables] yield tuple(result) """ I'd say the "Equivalent to [reference implementation]" statement should meet your request. Peter From http Tue May 11 04:00:48 2004 From: http (Paul Rubin) Date: 11 May 2004 01:00:48 -0700 Subject: Inverse of int(s, base)? References: <2gac73Fk1ooU1@uni-berlin.de> <ad052e5c.0405102113.2de5d7dc@posting.google.com> Message-ID: <7xhdungzpr.fsf@ruckus.brouhaha.com> danb_83 at yahoo.com (Dan Bishop) writes: > > while x: > > result = str_digits[x % base] + result > > x /= base > > The above line should be "x //= base", so it works under -Qnew. Or just say: x, r = divmod(x, base) result = result + str_digits[r] > That works (for positive integers), but it might be more efficient to > not create a new string each time through the loop. An alternative is: > > def str_base(n, base=10): ... Similarly: def str_base(n, base=10): results = [] sign,n = ('','-')[n < 0], abs(n) while n: n, r = divmod(n, base) results.append(str_digits[r]) results.reverse() return sign + ''.join(results) From jbarham at jbarham.com Sat May 1 15:20:44 2004 From: jbarham at jbarham.com (John E. Barham) Date: Sat, 01 May 2004 19:20:44 GMT Subject: Help with C API References: <f8097096.0404302152.38dd1eae@posting.google.com> <c6vfmv$grq$1@news1.tilbu1.nb.home.nl> <f8097096.0405010208.3fbc8e2d@posting.google.com> <f8097096.0405011015.6d2207e@posting.google.com> Message-ID: <gMSkc.333338$oR5.18941@pd7tw3no> "Nick Jacobson" wrote: > I don't think I'm stating my question clearly. :( > > Say I create a list in my C function: > seq = PyList_New(0); > Then append some numbers to it, whatever. > > Then, when I return from the C function and want to use that list in > my Python code, do I have to increment its refcount: > return Py_BuildValue("O", seq); > > Or do I leave it alone and say: > return seq; > > Thanks in advance. Grepping through the modules shipped w/ Python seems to suggest that you should just return it since calling PyList_New() returns a new reference. See for example its use in the strop module (http://tinyurl.com/25s4e) which does something similar to what you describe. HTH, John From jacek.generowicz at cern.ch Tue May 25 06:11:42 2004 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 25 May 2004 12:11:42 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> Message-ID: <tyf7jv0n7dt.fsf@pcepsft001.cern.ch> Ryan Paul <segphault at sbcglobal.net> writes: > On Sat, 22 May 2004 22:53:01 -0700, simo wrote: > > > One thing that might attract me from Python to Prothon is if it had > > proper private medthods - i.e. not just name mangling like __myDef > > which can be overridden using _myClass__myDef (as the interpreter > > does). > > > > Proper encapsulation is needed before the C++ brigade will take Don't confuse encapsulation with access restriction. > I dont understand why everybody seems to want a machinecode > compiler. Actually, my impression is that most (at least many) around here don't want one. > It wont make a high-level, dynamically typed language run any > faster. Your claim is false. Proof by counterexapmle: CL-USER 1 > (defun fib (n) (if (< n 2) 1 (+ (fib (- n 1)) (fib (- n 2))))) FIB CL-USER 2 > (time (fib 35)) Timing the evaluation of (FIB 35) user time = 66.330 system time = 0.000 Elapsed time = 0:01:06 Allocation = 5488 bytes standard / 328476797 bytes conses 0 Page faults Calls to %EVAL 8388522 14930352 CL-USER 3 > (compile 'fib) FIB NIL NIL CL-USER 4 > (time (fib 35)) Timing the evaluation of (FIB 35) user time = 1.000 system time = 0.000 Elapsed time = 0:00:01 Allocation = 1216 bytes standard / 2783 bytes conses 0 Page faults 14930352 Looks like compiling this partucular high-level dynamically typed language makes it run considerably faster. Let's repeat the exercise for 3 more implementations of this particular language I just happen to have lying around on my machine, and compare it to Python's performance on the equivalent program: >>> def fib(n): ... if n<2: return 1 ... return fib(n-1) + fib(n-2) ... >>> import time >>> a=time.time(); fib(35); time.time() - a 14930352 20.425565958023071 Here are the results gathered in a table: Name Interpreted Compiled LispWorks 66 1.0 s Clisp 41 9.5 s CMUCL Got bored waiting 1.5 s SBCL Compiles everything 1.6 s Python Compiles everything 20 s So, we have times of 1.0s, 1.5s, 1.6s, 9.5s and 20s. Now one of those Common Lisp implementations does NOT compile to native; it compiles to bytecode. Can you guess which one it is, by looking at the timings ? From rmkrauter at yahoo.com Fri May 14 12:35:48 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri, 14 May 2004 12:35:48 -0400 Subject: Unification of Methods and Functions In-Reply-To: <mmo7a0d17d0oigka5icevb9qj3ogudtvai@4ax.com> References: <16752bcc.0405070531.10dcc1fc@posting.google.com> <4a9o90pbu122npgf4m2hrgg04g2j0ic6ka@4ax.com> <16752bcc.0405080607.4bb18276@posting.google.com> <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <slrnca10tf.1i9.apardon@trout.vub.ac.be> <16752bcc.0405111754.35d0838a@posting.google.com> <11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <mmo7a0d17d0oigka5icevb9qj3ogudtvai@4ax.com> Message-ID: <1084552548.6569.1008.camel@vaio> On Thu, 2004-05-13 at 17:59, David MacQuigg wrote: > The one fundamental difference between methods and functions is the > presence of instance variables in methods. To me, that statement is missing the whole point. OOP is not procedural programming. That is the fundamental difference. "Unifying" the syntax in an attempt to make it easier for your students to learn probably won't accomplish what you want - one, I don't think what you propose is easier or better, and two, and more importantly, simply knowing python's (or any other language's) OOP syntax doesn't automatically make you an OO guru. Knowing when, where and why to implement classes is much harder than learning python's current syntax for building them. Your proposal doesn't change that. > You can hide that > difference with the self.var trick. You can hide it even further by > not using 'self', but some other word that looks just like the other > variable names in the function. None of this removes the actual > difference, or makes learning about instance variables any easier for > the student.The choice of how to identify instance variables is a minor issue. I > think it is actually better not to *hide* the instance variables, but > to *highlight* them. Ruby uses $var for instance variables. Prothon > uses a leading dot, which is quite visible in most code editors. > Actually, .var could be used in a function outside a class, just as > you can now use self.var in the current function syntax. Before using > a function with .var, the global variable __self__ must be set. I may be way off here, but I don't see how a global __self__ could work: <not python> class B: def __init__(name,data): .data = data*5 .name = '***%s***'%name class A: def __init__(name,data): .data = data # __self__ is a? .obj = B() # __self__ is now the B instance? .name = name # now what? a = A() </not python> Rich From BruceWhoHKL at gawab.com Thu May 20 21:57:50 2004 From: BruceWhoHKL at gawab.com (BruceKL WhoH) Date: Fri, 21 May 2004 09:57:50 +0800 Subject: Freeze and Resume execution Message-ID: <mailman.139.1572214934.32708.python-list@python.org> I come across the same problem. What I want to do is to write a vim script to debug python script. Bdb(exactly, a derived class of Bdb) will be called, and when it break at some breakpoints, it must freeze, and come back to vim, then later, user will call 'step' or 'trace' or 'continue', then Bdb will be called again and resume. Just last week I posted a mail to ask, but it seems that it's impossible to do it. >Hello All, > >I'm looking for a way to "yield" an exception. > >Background: I'm writing a hardware simulator. I have an output buffer >and need to freeze when it's full and then when called again to resume >execution from the point where it stopped. > >Currently all I can think of is to use a class and save the state when >throwing an exception. However this required manual book keeping of the >current state (and it is complicated). > >I'd like to use generators but can't see any "nice" way of doing it. >What I'd like it to throw an exception when the buffer is full and then >next time the generator is called to continue execution as after a >"yield". > >Is this possible? >Can you recommend a good way of doing this? Any state machine? > >Thanks. >Bye. >-- >------------------------------------------------------------------------- >Miki Tebeka <miki.tebeka at zoran.com> >http://www.cs.bgu.ac.il/~tebeka >The only difference between children and adults is the price of the toys. > > >-- >http://mail.python.org/mailman/listinfo/python-list > = = = = = = = = = = = = = = = = = = = = ????????BruceKL WhoH ????????BruceWhoHKL at gawab.com ??????????2004-05-21 From donn at drizzle.com Wed May 26 01:58:40 2004 From: donn at drizzle.com (Donn Cave) Date: Wed, 26 May 2004 05:58:40 -0000 Subject: terminological obscurity References: <1085248385.210031@yasure> <51iva05c4l3hveeeovm7oqpbhaqa45k9po@4ax.com> <1085328791.560793@yasure> <ohc2b01cfv084lntljp7oamsic0j92n2me@4ax.com> <1085378050.309299@yasure> <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <donn-F5877E.11513724052004@nntp1.u.washington.edu> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <donn-10607D.09032925052004@nntp1.u.washington.edu> <dam7b0dip3fi1dnicj4gmnb30d5vf2up88@4ax.com> Message-ID: <1085551118.250464@yasure> Quoth Arthur <ajsiegel at optonline.com>: | On Tue, 25 May 2004 09:03:29 -0700, Donn Cave <donn at u.washington.edu> | wrote: .. | You fundamentally miss my point. | | What you are saying is clear enough. You are also saying that this is | what Guido meant, when he said something different. And leaving as | anomolous why Guido didn't say what he meant himself. Well, to be honest, what Guido said or meant isn't the critical thing for me. But this isn't a choice between two reasonable alternatives. He did distinguish between the ideal applications for tuples and lists, describing them in terms that allow for one sensible interpretation, and one completely, utterly absurd interpretation. Maybe he could have said it better, seeing as some people read it and don't get the sensible interpretation right away. So they say `hey, what's up with this weird idea about lists vs. tuples?' For most, this seems to be a solvable problem. I don't know if everyone is convinced of the merits of the argument, but they at least roughly understand it. You, however, start from the observation that Guido said something bafflingly stupid, and then proceed to cling to that interpretation when everyone else has dismissed it. Why? Don't answer that, I don't care. Just forget about Guido for a while, OK? If you are constructing a conceptually homogeneous sequence, use a list. Donn Cave, donn at drizzle.com From fishboy at spamspamspam.com Sun May 30 15:10:19 2004 From: fishboy at spamspamspam.com (fishboy) Date: Sun, 30 May 2004 19:10:19 GMT Subject: noddy example, writing C modules for python References: <c9c93u$a8q$1@linux.site> Message-ID: <iackb0help9r5d752eilj4t8q2942j6kum@4ax.com> On Sun, 30 May 2004 11:22:06 +0200, Torsten Mohr <tmohr at s.netic.de> wrote: >pmod.cc(143) : error C2065: 'T_INT': nichtdeklarierter Bezeichner hmmm, looking at this makes me wonder if you need a: #include "structmember.h" since T_INT is defined there. ><{{{*> From jfabiani at yolo.com Sun May 16 13:55:49 2004 From: jfabiani at yolo.com (john fabiani) Date: Sun, 16 May 2004 17:55:49 GMT Subject: Python for Large Projects In-Reply-To: <c9lkn1-1ck.ln1@wintermute.g2ctech> References: <10ae406ck3q1gb1@corp.supernews.com> <DL6dndD3f71g8jrdRVn_iw@powergate.ca> <bKLpc.9370$WT1.4439@newssvr27.news.prodigy.com> <c9lkn1-1ck.ln1@wintermute.g2ctech> Message-ID: <FWNpc.67744$5V2.39535@newssvr25.news.prodigy.com> Jorge Godoy wrote: > On Dom 16 Mai 2004 12:25, john fabiani wrote: > > >>I'm a newbie so take what I say with a grain of salt! >>In the VFP (visual foxpro) world the runtime environment is loaded on >>the local computer (client) and the program is often loaded on to the >>server. I'm wondering if there would be any advanage to placing the >>python runtime on the clients along with the standard modules. Then >>placing the program code on to a server where all the clients/users >>would access the code. It would seem that the advanage would be that >>program load time would about the same but the excutions would be faster >>because of the local runtime. Can this even been done? Would it be >>faster? > > > If I understood you correctly, this is what we do on our clients. It also > makes it easier to make bugfixes, updates, etc. in our code. > So it can be done. I'll have to learn a little more about path-ing. Thanks John From goodger at python.org Tue May 25 18:44:21 2004 From: goodger at python.org (David Goodger) Date: Tue, 25 May 2004 18:44:21 -0400 Subject: optparse docs? In-Reply-To: <16563.50468.555281.536241@montanaro.dyndns.org> References: <16563.50468.555281.536241@montanaro.dyndns.org> Message-ID: <40B3CC45.1040307@python.org> The library docs are all I know of. On the optik-users list, Greg Ward recently posted links to updates to Optik/optparse's docs: """ I would appreciate some careful proof-reading from those of you who use Optik every day, as well as from anyone who's new to it. Please sharpen your red pencils and pore over: http://www.gerg.ca/software/optik/doc/stable/tao.html http://www.gerg.ca/software/optik/doc/stable/basic.html http://www.gerg.ca/software/optik/doc/stable/advanced.html http://www.gerg.ca/software/optik/doc/stable/callbacks.html http://www.gerg.ca/software/optik/doc/stable/extending.html I spent the most time revising the tutorial (aka "Basic Usage") after receiving a well-thought-out critique by private email a few months back. If you have any sort of pedagogical skills, please turn your attention to basic.html and see what else could be improved there. """ If the updated docs aren't enough, perhaps a doc bug report and/or a message to Greg? -- David Goodger From jdhunter at ace.bsd.uchicago.edu Thu May 6 23:01:43 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 06 May 2004 22:01:43 -0500 Subject: classes vs dicts In-Reply-To: <be05f1d.0405060212.43929fe1@posting.google.com> (charlvj@yahoo.com's message of "6 May 2004 03:12:15 -0700") References: <be05f1d.0405060212.43929fe1@posting.google.com> Message-ID: <m2y8o5djoo.fsf@mother.paradise.lost> >>>>> "Charlie" == Charlie <charlvj at yahoo.com> writes: Charlie> Greetings, I am pretty new to Python and like it very Charlie> much, but there is one thing I can't figure out and I Charlie> couldn't really find anything in the docs that addresses Charlie> this. Charlie> Say I want to write an address book program, what is the Charlie> best way to define a person (and the like): create a Charlie> class (as I would do in Java) or use a dictionary? I Charlie> guess using dictionaries is fastest and easiest, but is Charlie> this recommended? For simple data with just a few fields, a tuple may be all you need people = ( ('John', 'D', 'Hunter', 36), ('Miriam', 'A', 'Sierig', 33), ('Rahel', 'S', 'Hunter', 6), ) for first, middle, last, age in people: print '%s %s %s is %d years old' % (first, middle, last, age) When you use named tuple unpacking, ie, first, middle, last, age = row rather than indexing operations, ie row[0], I find using tuples can be as readable as classes or dicts. Again only for simple data structures... John Hunter From csgcsg39 at hotmail.com Thu May 13 03:13:52 2004 From: csgcsg39 at hotmail.com (C GIllespie) Date: Thu, 13 May 2004 08:13:52 +0100 Subject: max value in list References: <c7te26$8q1$1@ucsnew1.ncl.ac.uk> <c7u21d$6gm$05$1@news.t-online.com> Message-ID: <c7v77a$150$1@ucsnew1.ncl.ac.uk> Dear All, Thanks for all the responses. Very helpful (again) Colin From moma at example.net Thu May 27 02:22:05 2004 From: moma at example.net (moma) Date: Thu, 27 May 2004 08:22:05 +0200 Subject: why learn In-Reply-To: <40b58695_1@news.iprimus.com.au> References: <40b58695_1@news.iprimus.com.au> Message-ID: <hNftc.4195$eH3.74779@news4.e.nsc.no> mr_vocab wrote: > hey i finished working through alot of python stuff and no a fair bit bout > it > > now what can i do with it??? > > Goto http://www.markshuttleworth.com/bounty.html and... // moma http://www.futuredesktop.org From kdahlhaus at yahoo.com Tue May 11 11:17:51 2004 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 11 May 2004 08:17:51 -0700 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> Message-ID: <283adf56.0405110717.799d08fc@posting.google.com> There's a sample of an overloading mechanism implemented in the python fltk wrappers on sourceforge. From peter at engcorp.com Mon May 10 06:28:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 May 2004 06:28:54 -0400 Subject: problem with PYTHONPATH on WinXP In-Reply-To: <e71eaa43.0405091124.2f64f2a9@posting.google.com> References: <e71eaa43.0405091124.2f64f2a9@posting.google.com> Message-ID: <WqGdnYCgYuL7xALdRVn-uw@powergate.ca> D Denholm wrote: > I recently installed Python 2.2 on my WinXP box. > > I am having problems figuring out how to create the PYTHONPATH > correctly. I would suggest not using PYTHONPATH, but instead use the .pth file capability defined in and used by site.py. Check the comments at the top of that file in your python/lib folder, and make a .pth file with the appropriate contents instead of mucking with environment variables. One thing to note: the file extension must be lower case or site.py won't find the file. -Peter From kkulak at shaw.ca Wed May 5 19:37:40 2004 From: kkulak at shaw.ca (Kim Kulak) Date: Wed, 05 May 2004 23:37:40 GMT Subject: prefix for installed scripts Message-ID: <8Vemc.384062$oR5.32412@pd7tw3no> Hello, I've run into a small problem with my first python program. I'm writing this program on Debian Linux so python is installed in /usr and sys.prefix is '/usr'. I've written a setup.py script and installed my program and it's configuration data with prefix = '/usr/local'. It installs exactly where I want it, but when I run my program 'sys.prefix' is '/usr' (where python is installed) and not '/usr/local' (where my program is installed. My question is: how do I find where _my_ program was installed? TIA, Kim P.S. Is anybody working on: "python setup.py uninstall" ? From noamr at correctme.users.sourcephorge.net Fri May 21 11:55:22 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Fri, 21 May 2004 18:55:22 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: <Fc-dndNGTtNmvzPdRVn-uQ@powergate.ca> References: <c8l3s3$27o$1@news.iucc.ac.il> <slrncas79j.41g.grante@grante.rivatek.com> <c8l6ro$3p7$1@news.iucc.ac.il> <Fc-dndNGTtNmvzPdRVn-uQ@powergate.ca> Message-ID: <c8l8pa$4n0$1@news.iucc.ac.il> Peter Hansen wrote: > Noam Raphael wrote: > >> Grant Edwards wrote: >> >>> It's a bit less efficient, but you can currently spell that as >>> >>> l[12345:][:10] >>> >> That is true, but if the list is long, it's *much* less efficient. > > > Considering that the interpreter special-cases some integer math > including the BINARY_ADD, it likely wouldn't take a very long list > to pass the point where they're the same. > I don't understand: If the list is of length 1000000, wouldn't Grant Edwards' suggestion make 1000000-12345 new references, and then take only the first ten of them? From kj7ny at charter.net Sat May 15 00:46:47 2004 From: kj7ny at charter.net (kj7ny) Date: Fri, 14 May 2004 21:46:47 -0700 Subject: C++ runtime Message-ID: <10ab81nkihhj168@corp.supernews.com> I was at a class for a system I work on and the instructor was talking about how the system worked with any language that supports C++ Runtime. I'm not sure what that means :) Does that mean anything to you folks? And... does Python support C++ Runtime? Thanks, From paulvh at direcway.com Mon May 3 14:07:06 2004 From: paulvh at direcway.com (Paul VanHouten) Date: 3 May 2004 11:07:06 -0700 Subject: Tangle of Extension Rebuilds? Message-ID: <15419b3d.0405031007.2f3cde86@posting.google.com> I am attempting to build the bsddb3-4.2.4 extension for incorporating the Berkeley Db (4.2.52) into Python on a Win XP platform. I used VC++.Net to build the Berkeley Db dll/lib/exe files. I don't have VC++ 6 nor can you but it now. The bsddb3-4.2.4 build failed complaining that Python was built with VC++ 6. I assume I can rebuild Python with VC++.Net but if I do will other existing extensions cease to work and require rebuilding? Yikes! Suggestions? From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Mon May 10 04:50:38 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Mon, 10 May 2004 10:50:38 +0200 Subject: Python for Nokia Series 60 References: <jollinofrenoamano-D94CBF.10345409052004@individual.net> <c7lls2$4i1$1@news-reader1.wanadoo.fr> <2g7c6lF52kr4U1@uni-berlin.de> <c7mb1g$f2g$1@news-reader2.wanadoo.fr> <2g7siqF57e6rU1@uni-berlin.de> Message-ID: <c7nfpm$ah2$1@news-reader2.wanadoo.fr> Re Sorry, but : - I don't have a nokia (at this moment) - I never tested Jython (times... times...) - I never developped in Java thus - I prefer to see coming - To drink aperitif @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From peter at engcorp.com Mon May 3 08:48:11 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 May 2004 08:48:11 -0400 Subject: printing float as formatted dollars In-Reply-To: <mailman.199.1083564883.25742.python-list@python.org> References: <mailman.199.1083564883.25742.python-list@python.org> Message-ID: <Ev-dnTppwuOMogvdRVn-tw@powergate.ca> Martin Slouf wrote: > On Sun, 2 May 2004, Tim wrote: > > >>Is there a simple way to output float values as formatted dollar amounts? >>i.e. 127379.42 as $127,379.42 > > from python doc (itertools module): > > >>>>amounts = [120.15, 764.05, 823.14] >>>>for checknum, amount in izip(count(1200), amounts): > > ... print 'Check %d is for $%.2f' % (checknum, amount) > Check 1200 is for $120.15 > Check 1201 is for $764.05 > Check 1202 is for $823.14 The OP asked for commas, too... -Peter From martin at v.loewis.de Fri May 28 16:12:03 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 May 2004 22:12:03 +0200 Subject: terminological obscurity In-Reply-To: <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> References: <1085378050.309299@yasure> <nd83b0dgrt0su2cbrqm5gtsur49p3oj19u@4ax.com> <0a84b0t7hplgkepa9tcdduv5a0pgu5ltcr@4ax.com> <7u94b0hi6mgfbdipirk03dksovmkd6886u@4ax.com> <donn-F5877E.11513724052004@nntp1.u.washington.edu> <1l25b0damv22nmja2na0i3k55e0p3jsef4@4ax.com> <donn-10607D.09032925052004@nntp1.u.washington.edu> <dam7b0dip3fi1dnicj4gmnb30d5vf2up88@4ax.com> <40B625C0.3040605@v.loewis.de> <0dvcb0dtdbelmjr9j4s0599unvebicd1ug@4ax.com> <40b6e3d6$0$12458$9b622d9e@news.freenet.de> <0gdeb016blqt7vhuor6j8j31bm3gdr4dqu@4ax.com> Message-ID: <40b79d0e$0$26997$9b622d9e@news.freenet.de> Arthur wrote: > Is the random set of, say, 10 human beings homogeonous or > hetereogenous? If they are random, than yes, they are homogenous as they are all human, and no, the are heterogenous, because they are random, i.e. they share no features. > Or is that a meaningless question, as the answer depends purely on > context? Not purely (as you can see above), but typically. You need some application context to know whether a set of objects is homogenous - with respect to properties that the application cares about. > Are objects that have hundreds of attributes each, and that conform as > to a single attribute, which attibute accounts for there presence > together in a list, meaningfully homogenous - outside of the fact of > their presence together in the list? Likely: no. It may still be that there is external state that makes them homogenous. E.g. they may all act as keys to some database, and be kept in a single collection so the application can find all items associated with the keys. Regards, Martin From davidf at sjsoft.com Thu May 27 16:53:28 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 27 May 2004 22:53:28 +0200 Subject: Adding your own site directories cleanly and supportedly? In-Reply-To: <fbc0f5d1.0405260633.54a2996e@posting.google.com> References: <fbc0f5d1.0405260633.54a2996e@posting.google.com> Message-ID: <c95kg5$1vs$1@ctb-nnrp2.saix.net> Tim Bradshaw wrote: > We have a situation where, on our production machines, we will > probably have a standard Python installation which is installed with > the system build, and which we want to use for various possible > applications. These applications will probably have different library > requirements, and may have conflicting requirements. We don't *know* > they will, but they may do and we don't want to have to worry about > it, basically. > > As an example, my application uses Numeric. I suspect that no-one > else does, but I don't want to find out that they do, and they use an > incompatible version. Of course, we should really establish a > standard version and install the centrally and so on, but we probably > don't have time for that. Different versions of the application might > also need different versions of Numeric, and they need to be able to > coexist painlessly. Aha! Another reason to use a multi-version script like we have been talking about for wxPython. If you search the newsgroup for wxselect you should find a script you may be able to adapt for selecting versions of other modules... > > This looks easy to solve: Numeric uses distutils, so we can just have > per-application site directories, where applications put the things > they need with no fear of interference. > We've been doing some modifications to the Numeric setup script that make it easier to include in your application installer. > Ah, but. How do I add an application-specific site directory, and do > all the .pth file searching? It looks like I can call > site.addsitedir() to add a directory of my choosing, and this will all > work. This is all fine. From myles at geocities.com Tue May 25 21:11:02 2004 From: myles at geocities.com (Myles) Date: 25 May 2004 18:11:02 -0700 Subject: Method binding confusion References: <mailman.212.1083600570.25742.python-list@python.org> <c760s2$ev4$04$1@news.t-online.com> <20r4b091eqq896s3gh858t3g3cvj51kpca@4ax.com> <c8u3pe$b4v$1@news.service.uci.edu> <feb6b0tqq5vt4i0fc25alpvsbamhl1j6mf@4ax.com> Message-ID: <a4638b9b.0405251711.75a8fe85@posting.google.com> > extra argument, should be sufficient clue to add the staticmethod > wrapper. I'm coming from a dabbler's viewpoint. Why the binding tricks ? Couldn't you just "wrap" the methods ? My solution: ---- import math def mypow(x, y): return x**y class MathA: def pow(self, x, y): return mypow(x,y) class MathB: def pow(self, x, y): return math.pow(x,y) ma = MathA() mb = MathB() print ma.pow(2, 3) print mb.pow(2, 3) ---- This seems more obvious and consistent to me, or am I missing the point of the discussion ? Regards, Myles. From slawek at cs.lth.se Thu May 20 07:59:45 2004 From: slawek at cs.lth.se (Slawomir Nowaczyk) Date: Thu, 20 May 2004 13:59:45 +0200 Subject: Help with large data set and fatal python error (pysqlite) In-Reply-To: <KPENJIMKHJPNKOLFIHBNKEPNCJAA.vineet@eswap.com> References: <m2ad08ypu1.fsf@mother.paradise.lost> <KPENJIMKHJPNKOLFIHBNKEPNCJAA.vineet@eswap.com> Message-ID: <20040520135937.9C98.SLAWEK@cs.lth.se> On Wed, 19 May 2004 17:56:37 -0400 "Vineet Jain" <vineet at eswap.com> wrote: #> I've been able to recreate the problem with the following code segment. It #> seems that the problem comes when you have multple db files open at the same #> time. In my application I have many database files open at the same time. #> I'm not using threads so all access to the db files are done sequenetially. #> At the end of the program I get the following error: #> Fatal Python error: deallocating None #> This application has requested the Runtime to terminate it in an unusual #> way. #> Please contact the application's support team for more information. #> If I change the numInnerLoop to 5, 10, 20, or 30 it works however anything #> over 35 gives the above error. In my actual application, when run for a #> larger set, the error can come in the middle of the program and is causing #> me a lot of grief. #> Any help would be really appreciated. I don't know how much help would it be, but the code below is working fine for me - for as much as "numInnerLoop = 150" and "k in range(5)". So it would seem like a problem specific to your system. I am using sqlite.version '0.5.0' on Windows XP. What is your configuration? One wild guess would be that you are reaching the system limit of open files (assuming each connection means opening a file, which seems likely). I recall Windows 9x having something like this, but I do not remember details and don't know how it looks like in newer versions. You may also want to check if you are able to open many connections with stand-alone sqlite program. That should, at least, give you a hint whom should you send a bug report :-) Even if there is a reason for sqlite to fail, it should do it more gracefully. -------------------Problem Code---------------------------- import sqlite import gc import sys, os #initialize database dbFileName = "c:/test.db" numRecords = 1000 os.remove(dbFileName) conn = sqlite.connect(database=dbFileName,autocommit=0) cur = conn.cursor() cur.execute("create table t (field1,field2,field3,field4,field5,field6,field7)") for i in range(numRecords): cur.execute("insert into t values(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0)") conn.commit() conn.close() numInnerLoop = 50 conn = [None]*numInnerLoop cur = [None]*numInnerLoop tempStore = [None]*numInnerLoop qry = "select * from t" for k in range(1): for i in range(numInnerLoop): conn[i] = sqlite.connect(database=dbFileName,autocommit=1) cur[i] = conn[i].cursor() sys.stdout.write('OuterLoop: %d Inner Loop : %d\r' % (k, i)) tempStore[i] = [] cur[i].execute(qry) dbRowList = cur[i].fetchall() for j in range(numRecords): for l in range(6): tempStore[i].append(float(dbRowList[j][l])) dbRowList = None gc.collect() for i in range(numInnerLoop): conn[i].close() -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) My goal in life is to be the sort of person my dog thinks I am. From jarausch at igpm.rwth-aachen.de Wed May 26 07:36:43 2004 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 26 May 2004 13:36:43 +0200 Subject: Get Amount of Physical Memory In-Reply-To: <c8ssfm$95h$1@solaris.cc.vt.edu> References: <c8ssfm$95h$1@solaris.cc.vt.edu> Message-ID: <40B4814B.7080807@igpm.rwth-aachen.de> Bart Nessux wrote: > Is there a function in Python that will get the amount of physical > memory from the machine the interpretor is running on? > For Linux for L in open("/proc/meminfo") : print L -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From dai4happy at yahoo.com Sat May 8 23:33:34 2004 From: dai4happy at yahoo.com (angel) Date: Sun, 9 May 2004 11:33:34 +0800 Subject: How python ActiveX to access DHTML document? References: <c7ibmb$24b2$1@news.f.de.plusline.net> Message-ID: <c7k92q$3s2$1@news.f.de.plusline.net> Hi everyone Thank you for your reply. The use case is: 1) I wrote a com server(progid is PythonCom.Test)in Python. It works well. 2) The com server expose some method func1 func2 ... 3) In a html I wrote a jscript var com = new ActiveXObject("PythonCom.Test"); com.func1(); // it's ok com.func2(); //it's ok too. 4)Now I want my com server can access the html document directly. I hope my com server can call document.all.id1.innerText ="Hello world!" I know the key is to get the html document's IDispatch. but how to do? I have tried let a jscript call: com.func3(document); but the page report error. Thanx again. angel From merkosh at hadiko.de Thu May 13 17:20:20 2004 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 13 May 2004 23:20:20 +0200 Subject: liburl cant load webpage with Javascript Message-ID: <c80oqk$t7$1@news2.rz.uni-karlsruhe.de> Hi, I want do use liburl to scan a webpage which is only accessible from within my LAN environment. While mozilla manages to load the target URL properly neither wget, nor liburl or liburl2 does. I had a closer look at the html source and discovered a lot of Javascript, including Cookies. My suspicion is that the Javascript code needs to be executed for the page to work properly. Also I don't know how liburl deals with Cookies, but since they are handled by the Javascript in the source code they are probably not considered at all. In any case I get an IOError: connection refused, Error Code 111. Does anyone know a way out of this? Thanks for any hints, Ciao Uwe From claird at lairds.com Fri May 7 12:52:15 2004 From: claird at lairds.com (Cameron Laird) Date: Fri, 07 May 2004 16:52:15 -0000 Subject: Tkinter on way out? (was: Newbe-books) References: <Uldkc.29554$Qc.1128956@twister1.libero.it> <Qfblc.59034$Jh7.50678@newssvr25.news.prodigy.com> <109hm398jc2uk3e@corp.supernews.com> <c7gaa1$jll$1@srv38.cas.org> Message-ID: <109nflv4sqeg8f7@corp.supernews.com> In article <c7gaa1$jll$1 at srv38.cas.org>, <lvirden at yahoo.com> wrote: . . . >:the last eight years. The ... prematurity of these claims in >:the past makes me hesitate to write Tkinter off now. > >Sorry - I hit the wrong button. I guess I misunderstood mxPython - >I thought it was designed around a specific toolkit. Does it >provide kde and gnome desktop compatibility? If not, then it >seems strange that pythonians would move from one non-standard >library to another. . . . I don't know what "kde and gnome desktop compatibility" means. I'm unconvinced the KDEers and GNOMEans do, though I'm willing to learn. I find it exceptionally difficult to think of *any* GUI toolkit as "standard", without considerable qualification. The wxPythoneers are a good group. From all I know, Tkinter remains more broadly portable than wxPython. -- Cameron Laird <claird at phaseit.net> Business: http://www.Phaseit.net From martin at v.loewis.de Thu May 6 17:38:49 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 06 May 2004 23:38:49 +0200 Subject: A simple xml.dom.minidom question In-Reply-To: <c7dbc8$i4l$1@sunnews.cern.ch> References: <c7dbc8$i4l$1@sunnews.cern.ch> Message-ID: <409ab05f$0$24803$9b622d9e@news.freenet.de> Paulo Pinto wrote: > I want to have some control of how the xml in writexml() is > written. Depending on precisely what kind of control you want to have: yes, that is possible. > Is that possible? Or do I have to do navigate the XML tree by > myself? That may also be the case. Regards, Martin From cookedm+news at physics.mcmaster.ca Mon May 3 15:57:46 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 03 May 2004 15:57:46 -0400 Subject: curses and python (linux, debian) References: <CXwlc.94750$4b.5553241@phobos.telenet-ops.be> Message-ID: <qnk65bde11h.fsf@arbutus.physics.mcmaster.ca> At some point, Guido <no.email at please.invalid> wrote: > Hello > > I'm new to python and i'm trying to write a script that shows a menu. > > Now, I have some troubles with curses.setsyx() > > I do: > > import curses > > curses.setsyx(2, 20) > curses.putp("TEST TITLE") > curses.setsyx(25, 35) > curses.putp("TEST CENTER") > curses.setsyx(12, 35) > curses.putp("TEST CENTER") > > but it just prints all the string after each other at the first > lines.. Er, that's really the wrong way to do it. For one thing, curses.putp doesn't do what you think you want it to do. Have a look at "Curses Programming with Python": http://www.amk.ca/python/howto/curses/ Something like this: import curses def main(stdscr): stdscr.addstr(2, 20, "TEST TITLE") stdscr.addstr(25,35, "TEST CENTER") stdscr.addstr(12,35, "TEST CENTER") while 1: c = stdscr.getch() if c == ord('q'): return curses.wrapper(main) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From simon at metaplay.com.au Thu May 13 21:58:12 2004 From: simon at metaplay.com.au (Simon Wittber) Date: Fri, 14 May 2004 09:58:12 +0800 Subject: make faster Richards benchmark In-Reply-To: <KuednYkdsKA0MT7dRVn-hw@powergate.ca> Message-ID: <200405140149.i4E1nmgr024593@redpill.digitalventures.com.au> >> And Simon: "I just tried the benchmark with Psyco, and cut the run >> time for input=10000 from 8.1 seconds to 3.4" >> >What platform is this on? WinXP, P4 2.6GHZ, 512MB RAM Sw. From fperez528 at yahoo.com Sat May 15 01:19:09 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Fri, 14 May 2004 23:19:09 -0600 Subject: plot two data sets on gnuplot References: <4CBS9k$wiV@redbbs.cc.ntut.edu.tw> <mailman.424.1084280148.25742.python-list@python.org> Message-ID: <c8498d$ebl$1@peabody.colorado.edu> John Hunter wrote: >>>>>> <casio.bbs at redbbs.cc.ntut.edu.tw> writes: > > > I'm trying to write a script to pass a file of stock > > prices and volumes, and plot the results on a gnuplot > > graph which is non-overlapped graph. > > > Fig. 1 ------------ Fig. 2 > > > Figure 1 is a graph of stock prices, and Figure 2 is a > > graph of stock volumes, I'm trying to implement it as > > following codes, > > I don't use gnuplot, but I just wanted to let you know that I recently > added a finance module for matplotlib > http://matplotlib.sourceforge.net that supports the kind of graph you > are trying to make. It's fairly minimalist now, but will grow in the > near future. > > Here is a screenshot of a financial chart I made to show off some of > the finance features > > http://nitace.bsd.uchicago.edu:8080/files/share/finance_demo.png I was going to tell you to look at 'multiplot' in gnuplot: The command `set multiplot` places `gnuplot` in the multiplot mode, in which several plots are placed on the same page, window, or screen. ... But after seeing John's example, I honestly doubt it's worth the hassle with Gnuplot. It would take a ridiculous amount of work with gnuplot to make that kind of plot (and I've been using gnuplot since 1991!). Time for me to finally check out matplotlib... Best, f From roy at panix.com Tue May 25 21:55:42 2004 From: roy at panix.com (Roy Smith) Date: Tue, 25 May 2004 21:55:42 -0400 Subject: Why a class when there will only be one instance? References: <40B3E861.29B033D5@shaw.ca> <roy-5EFE18.21121225052004@reader2.panix.com> <40B3F448.EB711333@shaw.ca> Message-ID: <roy-D2E6B4.21554125052004@reader2.panix.com> In article <40B3F448.EB711333 at shaw.ca>, SeeBelow at SeeBelow.Nut wrote: > > More than that, most times I've decided to not bother making something a > > class because it was too simple, I've eventually added enough > > functionality to it to change my mind and have to re-do things. That's > > real cost. Much simplier and cheaper to just make it a class from the > > get-go. > > Why does greater functionality make a class desireable, if there won't > be multiple instances created? For me, it's more about encapsulation than code re-use. If I've got a bunch of functions which operate on a collection of data, to me that says "object", which in Python (and most OOPL's) implies "class". Bundling it up into a class lets me think about it as a unit. Each class is a convenient thought unit for design and testing, and also for understanding somebody else's code. I don't think there's a need to be dogmatic about it. It's just what I find is a natural way to break a program down into smaller pieces you can get your brain around one piece at a time. From dmq at gain.com Fri May 21 07:23:49 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 21 May 2004 04:23:49 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com> <16752bcc.0405101553.785638fd@posting.google.com> <q313a0lroe1uiiu43nkhhnqnbcm4jhgkrk@4ax.com> <16752bcc.0405121951.7454b9be@posting.google.com> <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <16752bcc.0405171911.6f4bbb6f@posting.google.com> <47cna0d9cbkfr2vovdhs692cklnmu0oo6h@4ax.com> <2h2g50F87lb9U1@uni-berlin.de> <s13oa05mhn1584d2ljvij40ktrorpo432s@4ax.com> <2h551dF8d2p7U1@uni-berlin.de> Message-ID: <44pra0dii37dn247l8csp6ed49f3kq85aj@4ax.com> On Fri, 21 May 2004 13:40:59 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: >Kevin G wrote: >> Seems to me there's a semantic problem here: if you can't re-calculate >> it, then by definition it's not redundant.] > >Obviously if it's redundant then in principle you can >always recalculate it. But if you don't plan for that, >you can end up not having any piece of code in the >system you can call to recalculate it. Approaching the >problem from the cacheing perspective at least ensures >that you do have such a piece of code. Another good example is the redundant setup parameters in a circuit design system. A setting to designate the location of output files may start in some hidden setup file, get read in during startup, and get copied to a number of internal variables in various tools that have been "integrated" into the system. If you change that setting, there is no way to propagate the changes through all of the tools. You have to restart the whole system. Seems like there is an inverse relationship between the price of software and the quality. -- Dave From jason at __nospam__mobarak.name Tue May 18 12:31:07 2004 From: jason at __nospam__mobarak.name (Jason Mobarak) Date: Tue, 18 May 2004 10:31:07 -0600 Subject: "Extracting" a dictionary In-Reply-To: <c8crm8$8hb$1@nntp.ilk.net> References: <mailman.20.1084820319.6949.python-list@python.org> <c8crm8$8hb$1@nntp.ilk.net> Message-ID: <c8ddkf$60b$1@nunki.unm.edu> Arnold Filip wrote: > Daniel Klein wrote: > >> Hello, >> >> I'm quite new to Python, and since a not-so-superficial look into the >> docs didn't answer my question (although it still feels quite basic), >> I decided to turn to this place: >> >> Is there a way to 'extract' a dictionary into the current namespace? >> That is, if you have >> {'foo' : 23, 'bar' : 42} >> you would get a variable foo with value 23 and a variable bar with >> value 42? Such a function would of course only work on string keys and >> would probably have to check that, but still, it sounds practical >> enough that surely someone else thought of it before. >> >> Daniel >> > > How about this: > > In [1]: d = {'foo' : 23, 'bar' : 42} > > In [2]: for item in d.items(): > ...: exec "%s = %d" % item > ...: > > In [3]: foo > Out[3]: 23 > > In [4]: bar > Out[4]: 42 > That's disgusting. At least with manipulating __main__ your not also bringing in the possibility of excuting arbitrary code. >>> d = {'foo' : 23, '__import__("os").system("echo executed a system command"); bar' : 42} >>> for item in d.items(): ... exec "%s = %d" % item ... executed a system command >>> foo,bar (23, 42) Granted, the reasons for wanting to do this may be ill-concieved, there's probably a better, more obvious solution -- since doing the subject of this thread is neither easy nor elegant. -- Jason From python-list at richardcooper.net Wed May 5 17:48:42 2004 From: python-list at richardcooper.net (Richard Cooper) Date: Wed, 5 May 2004 22:48:42 +0100 Subject: Absolute Imports and PYTHONPATH Message-ID: <F9A660A7-9EDD-11D8-8A4D-000A27E3999C@richardcooper.net> I can't believe I've just been bitten by this again! I'm part of a team writing an application in python. We have an fairly extensive package structure and like sensible pythoneers we use absolute imports throughout. The top level of our package is in PYTHONPATH so that all the absolute imports can work. This is all fine and dandy until I start playing with two different versions of the code (working on 2 CVS branches for example). Whenever I do this I inevitably forget to change PYTHONPATH at some point and waste an hour or so debugging a problem that occurred because the __main__ module from one tree is now importing from the other. This has happened to me a few times now and is really irritating. Am I missing an obvious non-hacktastic way to avoid this problem? If not would it be possible to fix this problem in a future python? I'm thinking something along the lines of: When a module is imported its import search path includes everything it does now PLUS the directory that is the top of the module's enclosing package structure. That way you wouldn't have to add entries to PYTHONPATH for packages that only import from themselves (and stdlib and site-packages). Possible? Sensible? What do you think? Regards, Rich From franck.lepoutre at caramail.com Wed May 12 11:27:42 2004 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Wed, 12 May 2004 17:27:42 +0200 Subject: Dabo 3-tier desktop framework for data-aware apps References: <mailman.457.1084369988.25742.python-list@python.org> Message-ID: <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> Hi Ed and Paul, I've seen your announcement on comp.lang.* Findind ex-vfpers working on python is nice, on wxpython. This is a superb piece of news! I was in Europython last year but found not one european vfp-er among the folks there. Engineering people mostly. My feeling was: well i'm the only one with the typical "business + db experience" that vfp-ers have have for years. Sure python offers the kind of smart interpreter-based dev. environment that the foxpro community has enjoyed for years. Possibly I made the wrong choice... Your announcement may make a change within the vfp community. You're right. It's about time foxpro-ers to commit to the python community and even more important to the wxpython user group. A general feeling about community support for vfp-ers, wikis are nice but mailing-lists are a question of choice (i definitely dislike them)... What about a forum or newsgroup kind of support "? la UT" with personal pictures and other community stuff ? and why not a dabo annoucement on UT first? Fran?ois From humean at fea.st Fri May 28 03:29:42 2004 From: humean at fea.st (Steve M) Date: 28 May 2004 00:29:42 -0700 Subject: Two questions about efficiency References: <edcd85fb.0405261239.6381cf32@posting.google.com> <c93ug8$duc$02$1@news.t-online.com> Message-ID: <edcd85fb.0405272329.6547dff6@posting.google.com> Peter Otten <__peter__ at web.de> wrote <snip> > Two results stand out: misses are cheap for DictIn and expensive for > DictTry. That's very interesting, thanks so much Peter and the others. So, contrary to your (and, incidentally, Wittgenstein's) admonition to look not think, why, would you speculate, is this the case? The overhead from creating an exception object? From donn at u.washington.edu Fri May 7 13:03:13 2004 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 May 2004 10:03:13 -0700 Subject: Scope rule pecularities References: <slrnc9kilq.5fa.apardon@trout.vub.ac.be> <c7dium$ruv$1@arcturus.ciril.fr> <slrnc9kkdo.5fa.apardon@trout.vub.ac.be> <donn-7C0E85.12052506052004@nntp4.u.washington.edu> <gWEmc.93873$Vp5.88043@fe2.columbus.rr.com> Message-ID: <donn-B211FA.10031207052004@nntp2.u.washington.edu> In article <gWEmc.93873$Vp5.88043 at fe2.columbus.rr.com>, Carl Banks <imbosol at aerojockey.invalid> wrote: ... > A lot of nice little reasons to have it so I wouldn't call it a kludge > and certainly not abominable. I guess this boils down to semantics, but that's flawed reasoning. I can cite lot of nice reasons to have motor vehicles, but I won't try to tell you they smell sweet, or that the heavy metals and gunk washed off the road purify the soil, or that your friends who have been killed or maimed on the road are still alive and well. Whatever += buys us, it's a triumph of expedience over elegance. Donn Cave, donn at u.washington.edu From grante at visi.com Fri May 21 11:16:03 2004 From: grante at visi.com (Grant Edwards) Date: 21 May 2004 15:16:03 GMT Subject: Specify start and length, beside start and end, in slices References: <c8l3s3$27o$1@news.iucc.ac.il> Message-ID: <slrncas79j.41g.grante@grante.rivatek.com> On 2004-05-21, Noam Raphael <noamr at correctme.users.sourcephorge.net> wrote: > Many times I find myself asking for a slice of a specific length, and > writing something like l[12345:12345+10]. [...] > Wouldn't it be nice if the Python grammar had supported this frequent > use? My idea is that the expression above might be expressed as > l[12345:>10]. It's a bit less efficient, but you can currently spell that as l[12345:][:10] -- Grant Edwards grante Yow! We just joined the at civil hair patrol! visi.com From jirap at pinguin.arcs.ac.at Thu May 13 22:05:20 2004 From: jirap at pinguin.arcs.ac.at (jirap at pinguin.arcs.ac.at) Date: Fri, 14 May 2004 02:05:20 +0000 Subject: Python-list, IHow do they f@kk with snakes? In-Reply-To: <L96JI5026F9H8C36@python.org> References: <L96JI5026F9H8C36@python.org> Message-ID: <D6GJ74D3DE0B0KCJ@zditr1.arcs.ac.at> Looks like you've come to a real Z00 here! Yeap! We have goats, we have horses, sheep, snakes, even dogs! e have lots of @n1m at ls here and we also have lots of g1r|s who just love to have some s. e -x with these creatures? How do they do it? http://zoo-action.com/av/val/?nmZht How do they sa-ck those c0c.k-s? How do they f at kk with snakes? Snakes don't have c0c.k-s!!! Guys! Our g1r|s can do it with every creature they want! They are ready for it! They are tired from men! They do realize that wild @n1m at ls are f at kking like no man would ever f at kk them. Cause they are animals and they f at kk just like everybody did thousands and millions years ago! http://zoo-action.com/av/val/?pTwtn Stunning 1ma-.ges, v1de0s, art series, lots of @n1m at ls, y0.u-n.g horny g1r|s spre at d1ng their legs and s at kking c0c-k.s! This is a first ever -X-.-X-.-X- zoo where every g1r| can f at kk the creature she wants! LOOK AT THIS NOW! jNbbbbLZ opIHpcJlt From chuck.amadi at ntlworld.com Fri May 28 02:47:22 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Fri, 28 May 2004 07:47:22 +0100 Subject: a python script which will parse an email message Message-ID: <40B6E07A.5060202@ntlworld.com> Yes but I want to read the Mail Dir . prior to getting all those files into one file to then get into PostGresql or PgAccess db. Cheers From bdesth.quelquechose at free.quelquepart.fr Mon May 24 07:18:09 2004 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 24 May 2004 13:18:09 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <pan.2004.05.23.14.24.47.540278@sbcglobal.net> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <pan.2004.05.23.14.24.47.540278@sbcglobal.net> Message-ID: <40b1d311$0$3032$636a15ce@news.free.fr> Ryan Paul wrote: > On Sat, 22 May 2004 22:53:01 -0700, simo wrote: > > (snip) >>Proper encapsulation is needed before the C++ brigade will take >>P[y/ro]thon seriously as an OO language, oh and a machinecode compiler >>;-) > > (snip) > I dont understand why everybody seems to want a machinecode compiler. It > wont make a high-level, dynamically typed language run any faster. Err... You might want to check some Common Lisp implementations. > --SegPhault > Note that here it should read 'sigfault' !-) Bruno From kirk at eyegor.jobsluder.net Tue May 11 15:25:53 2004 From: kirk at eyegor.jobsluder.net (Kirk Job-Sluder) Date: Tue, 11 May 2004 19:25:53 GMT Subject: perl to python References: <409e86e9$0$22811$a0ced6e1@news.skynet.be> <c7m175$rab$2@atlantis.news.tpi.pl> <409e8a04$0$22988$a0ced6e1@news.skynet.be> <40a03b44_3@newsfeed.slurp.net> <40a08893$1@pfaff2.ethz.ch> <f3f3a10c43c1778f1b1ec51ad8b6193e@news.teranews.com> <2gbtt0Fvso5U2@uni-berlin.de> <roy-B33624.08475211052004@reader2.panix.com> <du7wu3j2isz.fsf@mozart.cc.tut.fi> Message-ID: <slrnca2a73.1sfs.kirk@eyegor.jobsluder.net> On 2004-05-11, Ville Vainio <ville at spammers.com> wrote: > The things you usually do with the non-python tools are trivial, and > trivial things have the habit of being, well, trivial in Python too. I've not found this to be the case due to Python's emphasis on being explicit rather than implicit. My emulation of "perl -pi -e" was about 24 lines in length. Even with the improvement there is still 10 times as many statements where things can go wrong. It is really hard to be more trivial than a complete program in one command line. > You can always implement modules to do the tasks you normally use sed > or awk for. I never saw much virtue in using the most specialized (or > crippled, if you wish) tool possible. Not even if it's "optimized" for > the thing. Actually, I tend to think that Python has to some extent > deprecated that part of the Unix tradition. However, that raises its own host of problems such as how do you import the needed modules on the command line? What do you do when that module is not available? What do you do when you need additional functionality that takes one line in awk but a major rewrite in python? It's a matter of task efficiency. Why should I spend a half hour doing in python something that takes 1 minute if you know the right sed, awk or perl one-liner? There is a level of complexity where you are better off using python. But why not use a one-liner when it is available? > And yes, I'm aware that I'm exposing myself to some serious flammage > from "if it was good enough for my grandad, it's good enough for me" > *nix crowd. Emotional attachment to various cute little tools is > understandable, but sometimes it's good to take a fresh perspective > and just let go. Write me a two-line script in python that reads a character delimited file, and printf pretty-prints all of the records in a different order. Sometimes, a utility that uses an implicit loop over every line of a file is useful. That's not emotional attachment, it's plain common sense. From dkuhlman at rexx.com Fri May 7 16:45:47 2004 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 07 May 2004 13:45:47 -0700 Subject: Python Resources References: <109l91isml27qe4@corp.supernews.com> <wKidne2uocom6QbdRVn-ug@powergate.ca> Message-ID: <2g2arlF3rvuhU1@uni-berlin.de> Peter Hansen wrote: [snip] >> >> if you have Python Links in your favourites Post them as well >> >> I have been searching google as well >> It'd be nice if you would send an update to the editor of the Python page at Dmoz with the links that you collect. And, you might want to look there for links to fill out your list. http://dmoz.org/Computers/Programming/Languages/Python/ [snip] Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From Mike at DeleteThis.Geary.com Tue May 11 00:39:35 2004 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 10 May 2004 21:39:35 -0700 Subject: Ideas for Python 3 References: <s1pt80h988ucqd8vbrd3occhpagtpssigg@4ax.com> <onrt805i8q1qv5amhk06pqpe8umm9i7mhc@4ax.com> <c6mtgm$e09bj$1@ID-88904.news.uni-berlin.de> <n9q490hbe2a2mp65e5rh59eb97r2k1b9hn@4ax.com> <c7b2h1$eo$1@news.service.uci.edu> <lqti90hga2d7s19r012tjfm9v1gku2glf0@4ax.com> <c7clt9$r3k$1@news.service.uci.edu> <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> <c7pi8h$pcp$1@news.service.uci.edu> Message-ID: <10a0m88d1lof458@corp.supernews.com> Josiah Carlson wrote: > I've previously taken a look at Prothon. Prototype syntax > does not suit my taste in programming languages. If > Python 3.0 becomes Prothon, I'll fork the most recent > Python 2.x codebase that I prefer, maintaining it > myself if necessary. Prothon syntax is changing daily (actually hourly right now). It's not going to end up looking anything like what you see on the prothon.org website. What's being discussed right now looks a lot better to me. You still may or may not like the way it turns out, but it will be worthwhile to check back in on it after things settle down a bit. -Mike From janezskubic at hotmail.com Fri May 7 08:24:33 2004 From: janezskubic at hotmail.com (janez) Date: Fri, 07 May 2004 12:24:33 GMT Subject: downloading packages Message-ID: <5eLmc.58391$mU6.237277@newsb.telia.net> Hi, Is there some tool to download/update python packages from repository like python.org/pypi? Something similar to update.packages() in 'R',... Janez From peter at engcorp.com Mon May 31 19:57:15 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 31 May 2004 19:57:15 -0400 Subject: exceptions In-Reply-To: <cthzn7olnxj.fsf@lcpxdf.wm.lc.ehu.es> References: <cth8yf8n77o.fsf@lcpxdf.wm.lc.ehu.es> <0s6dnS4bi552vybdRVn-jw@powergate.ca> <cth4qpwn5h9.fsf@lcpxdf.wm.lc.ehu.es> <G-OdnbDM6oaZrybdRVn-gg@powergate.ca> <cthzn7olnxj.fsf@lcpxdf.wm.lc.ehu.es> Message-ID: <nJKdnXJHOcDBWybdRVn-tA@powergate.ca> Zunbeltz Izaola wrote: > Peter Hansen <peter at engcorp.com> writes: >>Zunbeltz Izaola wrote: >>>I want to continue executing the try block from the point the >>>exception was raised. >> >>Not possible except, perhaps, with a significant amount of >>working involving sys.settrace(). I think you need to find >>another way to solve the problem. > > But what I'm doing is not unittest. Pardon: I don't know why I thought this was related to testing code. > My program is controling and instrument (an x-ray powder > diffractometer) and some parts of the instrument are not working for > the moment, so i want to disable all error i get from this instrument > (are coded like exceptions) What is the interface to the instrument? Is there some sort of driver/wrapper layer that handles the communication with the device? Your only hope, I think, is to intercept things at that level and avoid/trap the exceptions before they get up to the higher level. In effect, stubs as Irmen suggested... It sounds like you are quite capable of figuring it out at this point, though, since all you wanted to know was whether you could continue after an exception and now you know you cannot. :-) -Peter From gk_2345 at yahoo.com Wed May 26 20:33:43 2004 From: gk_2345 at yahoo.com (George Kinney) Date: Wed, 26 May 2004 20:33:43 -0400 Subject: Current drive and directory References: <LP7tc.64476$gr.6380832@attbi_s52> Message-ID: <i8ydnRv9E-oJqijdRVn-hA@bright.net> "EAS" <eriksp at attbi.nospam.com> wrote in message news:LP7tc.64476$gr.6380832 at attbi_s52... > Does anyone know how to display the current directory using DOS > and/or Python? I already tried os.pardir and os.curdir in Python, but all > they return are > a couple of periods... > > >>>import os > >>>print os.curdir > . > >>>print os.pardir > .. maybe this? import os os.listdir(os.path.abspath('.')) os maybe: os.walk(os.path.abspath('.')) ??? From jfabiani at yolo.com Thu May 13 01:54:03 2004 From: jfabiani at yolo.com (john fabiani) Date: Thu, 13 May 2004 05:54:03 GMT Subject: Dabo 3-tier desktop framework for data-aware apps In-Reply-To: <36799cf6.0405122147.6e5d93cb@posting.google.com> References: <mailman.457.1084369988.25742.python-list@python.org> <40a24182$0$29836$79c14f64@nan-newsreader-06.noos.net> <u_roc.7515$ft5.2134@newssvr27.news.prodigy.com> <87pt99tmyl.fsf@pobox.com> <jMxoc.47714$762.6724@newssvr29.news.prodigy.com> <36799cf6.0405122147.6e5d93cb@posting.google.com> Message-ID: <%3Eoc.47926$5B5.47735@newssvr29.news.prodigy.com> Mark D wrote: > john fabiani <jfabiani at yolo.com> wrote in message news:<jMxoc.47714$762.6724 at newssvr29.news.prodigy.com>... > >>John J. Lee wrote: >> >>>john fabiani <jfabiani at yolo.com> writes: >>>[...] >>> >>> >>>>I also have not discovered the way to print reports or any routines >>>>that will generate the detail bands etc... But I have faith that they >>>>are out there. I really hope that I don't have to hand code reports. >>> >>> >>>'Report' is a fairly broad concept. It sounds like 'report' means >>>something quite specific to a VFP-er, though. If so, what would that >>>be? >>> >>> >>>John >> >>Big subject reports - in VFP we have a visual way to create printed >>reports. Normally, the report is associated with data (a cursor). The >>report form program loops thru the cursor and outputs the data to the >>report form to be printed either to the screen or a printer. The visual >>report editor allows the programmer to work with bands (detail,group, >>title, summary and several others). If you have worked with other >>report writers they generally work the same way. In a broad sense it's >>sort like working with a forms editor (boa). The report information is >>kept in a table and a report program reads the table to generate the >>output to the printer (along with the data). I think this how pyQT >>works to generate a window but pyQT uses a glade file (I think). >>Anyway, at the moment I don't have a way to send data to a printer. >> >>I'm guessing but I bet that simple text can be sent to a printer using >>Python (looping of course). But in today's world most users want >>graphics along with the data. Like an invoice with a logo, boxes around >>the bill to and ship to, along with column lines. So I'm hoping that >>someone has at least started a project to print reports. >> >> >>John > > > > Regarding reporting. > I am new to python and have similar questions. I have briefly looked > at www.reportlab.org and found their "Platypus" module very > interesting and simple for creating PDF documents. A comprehnsive > document framework is offered. With just a few lines of code you are > able to generate professional reports. Handling tabular data via is > also very easy. > Have a look. > > Mark > ps: first post (hope no blunders) Thanks I have been reviewing the site and a few google messages. Looks like this might work for what I want/need... ohn From listsub at wickedgrey.com Wed May 5 17:20:21 2004 From: listsub at wickedgrey.com (Eli Stevens (WG.c)) Date: Wed, 5 May 2004 14:20:21 -0700 Subject: VIM and tab to space migration References: <c5bg1k$25vq$1@news.wplus.net> <c5c138$i91$1@news.service.uci.edu> <9be5e130.0404160049.257ce8e1@posting.google.com> <99230dbb.0405011406.7f37c033@posting.google.com> <128ek6bi6lu8z.1k9v3u0vyb2qa.dlg@40tude.net> <mailman.266.1083757569.25742.python-list@python.org><40992866$0$12738$636a15ce@news.free.fr> <409932D7.9030502@sweetapp.com> Message-ID: <04be01c432e6$d92bf4e0$b401010a@sparta> Brian Quinlan <brian at sweetapp.com> wrote: > Christophe Cavalaria wrote: > >> Try adding that line at the end of each modified file : >> >> # vim:sw=4:softtabstop=4:expandtab >> >> It tells vim all the commands it should automatically run when it >> opens the file and it should get you the correct behaviour for 4 >> spaces no tab indentation. > > Thanks for the suggestion but modifying all my files is a pretty ugly > solution. Not that I'm above using it if there is no better way :-) Is it safe to assume you are working in a *nix environment? If so, shell scripts can be your friend (I use bash below). The <ctrl-V><ctrl-I> below is a literal tab character (bash specific, I think). Note that this will convert all tabs, not just those leading the line. # Untested... for file in `find . -type f -name "*.py"` do cat $file | sed -e "s/<ctrl-V><ctrl-I>/ /g" > /tmp/tmp.py mv /tmp/tmp.py $file done Heck, if you wanted, you could even have the script add the vim: line for you. Of course, that would mean that running the below twice would start adding duped, junk lines. # Untested... for file in `find . -type f -name "*.py"` do cat $file | sed -e "s/<ctrl-V><ctrl-I>/ /g" > /tmp/tmp.py echo "# vim:sw=4:softtabstop=4:expandtab" >> /tmp/tmp.py mv /tmp/tmp.py $file done Managing the changeover so that multiple developers stay in synch without creating merge conflicts is left as an exercise for the reader and his/her version control software. ;) In a vain attempt to bring this back on-topic, how would people accomplish the same in Python? I can't imagine that it would be that hard, but I'm a relative newbie. :) Eli -- Give a man some mud, and he plays for a day. Teach a man to mud, and he plays for a lifetime. WickedGrey.com uses SpamBayes on incoming email: http://spambayes.sourceforge.net/ -- From rick.ratzel at scd.magma-da.com Wed May 19 15:20:29 2004 From: rick.ratzel at scd.magma-da.com (Rick L. Ratzel) Date: Wed, 19 May 2004 14:20:29 -0500 Subject: Getting output from embedded python program In-Reply-To: <2aa196bb.0404221050.38f806@posting.google.com> References: <2aa196bb.0404190554.74631058@posting.google.com> <4084B179.6020807@magma-da.com> <2aa196bb.0404221050.38f806@posting.google.com> Message-ID: <40abb37e$0$90384$39cecf19@news.twtelecom.net> I'm not sure, but I think your problem is related to the globals and locals args to PyRun_String(). If you're trying to use PyRun_String to evaluate within the scope of your module, you need to provide the globals dictionary (as returned by PyEval_GetGlobals() or similar) and the locals dictionary (the dictionary of the module itself), as well as the start token (like Py_eval_input as defined in Python.h). Also, if you're getting NULL back (which means an exception was raised), you might want to check for the exception value which could give you more clues as to what went wrong...PyErr_Print() will print the traceback to stderr. Kim wrote: > Hi Rich, > You post is extremely useful. However when I tried to run the > expression in My Module's context, instead of __main__ module. It > always retunns NULL. How can I do that? I tried PyRun_String().. but > didn't work. i don't really understand global and local arguments in > PyRun_String(), token is set to 0? > > THanks very much ! > Kim > > >>... >>PyObject* evalModule; >>PyObject* evalDict; >>PyObject* evalVal; >>char* retString; >> >>PyRun_SimpleString( "result = 'foo' + 'bar'" ) >> >>evalModule = PyImport_AddModule( (char*)"__main__" ); >>evalDict = PyModule_GetDict( evalModule ); >>evalVal = PyDict_GetItemString( evalDict, "result" ); >> >>if( evalVal == NULL ) { >> PyErr_Print(); >> exit( 1 ); >> >>} else { >> /* >> * PyString_AsString returns char* repr of PyObject, which should >> * not be modified in any way...this should probably be copied for >> * safety >> */ >> retString = PyString_AsString( evalVal ); >>} >>... >> >> In this case, you need to know that the expression will evaluate to >>a string result in order to call PyString_AsString(). If you don't know >>this, you will have to check the type of the PyObject first. From missive at frontiernet.net Fri May 21 17:56:34 2004 From: missive at frontiernet.net (Lee Harr) Date: Fri, 21 May 2004 21:56:34 GMT Subject: Command Prompt References: <Cnurc.5$hi6.3519@attbi_s53> Message-ID: <mWurc.17$Fa1.14@news01.roc.ny> On 2004-05-21, EAS <eriksp at attbi.nospam.com> wrote: > Is there any way of using Python to open a command prompt? > > Almost certainly going to depend on your system. I would use ... import os os.system('xterm &') From segphault at sbcglobal.net Tue May 11 22:47:43 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Wed, 12 May 2004 02:47:43 GMT Subject: sending out XML from python. References: <03foc.111778$Jy3.44600@fed1read03> Message-ID: <pan.2004.05.12.02.43.41.386309@sbcglobal.net> On Tue, 11 May 2004 18:27:03 -0700, Sean Berry wrote: > I am going to be doing some programming with a Flash programmer in my > company. Most of the online docs about integrating Flash with another > language use PHP. I am not a fan of PHP. > > What I would really like to do is use Python to create data in the form of > XML to send back to Flash, since Flash MX has the ability to easily parse > XML to get variables and values. > > I have done some reading on XML in Python, but only stuff I have seen has > been geared toward reading in XML data, not spitting it out. > > Is there a module for doing this? I know that I can make something that > would work, but wondered if it is already done. > > Thanks Absolutely! My favorite way is to use the minidom to construct an XML document in memory, and then use node.toxml() to generate the content. (You can also use toprettyxml() while you are debugging if you want it to be readable.) The python documentation has lots of good information about the available XML tools. I made a wrapper for the minidom that lets me use simple operators to append nodes and traverse the tree. Additionally, I sometimes find that it is easier to make an xml output function in a particular class that builds an xml document from the class dictionary. Also, in some situations, it may make more sense just to write out the xml code and replace parts of it with python: """ <doc> <test1 prop="%(test1prop)s"/> </doc> """%{'test1prop':'asdf'} --Segphault From tdelaney at avaya.com Thu May 6 16:59:35 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 7 May 2004 06:59:35 +1000 Subject: polymorphism w/out signatures? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE01729DE5@au3010avexu1.global.avaya.com> Roy Smith wrote: > The most common reason is the example you gave, where you want a > function which will operate on either an item, or a bunch of items. > You might want to be able to say: > > nuke ("Perl") > > to get rid of everybody's least favorite language, and also be able to > pass in a bunch of them: > > nuke (("C++", "Java", "Perl")) > > to get rid of all three at once. If you really wanted to do that, you > could define nuke something like: > > def nuke (lang): > if isinstance (lang, types.TupleType): > for oneLanguage in lang: > nuke (oneLanguage) > else: > whatever > > In general, however, I try to stay away from stuff like that. A better approach anyway IMO for the above is to either always require an iterable, or to accept a variable number of parameters i.e. def nuke (lang, *langs): # must have at least one parameter _nuke(lang1) for lang in langs _nuke(lang) I could of course have constructed a combined tuple, but that's silly. Then you can call the above as any of: nuke('Perl') nuke('C++', 'Java', 'Perl') nuke(*('C++', 'Java', 'Perl')) Tim Delaney From FrankBechstein at t-online.de Mon May 10 20:01:51 2004 From: FrankBechstein at t-online.de (Frank Bechstein) Date: Tue, 11 May 2004 02:01:51 +0200 Subject: error handling Message-ID: <c7p559$6nq$05$1@news.t-online.com> I hope somebody could tell me how i can make a python script handling errors i want that if a error is arise that the script starts all over from then beginning and not that is is printing the error. thank u for helping me! From beliavsky at aol.com Thu May 20 11:25:22 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 20 May 2004 08:25:22 -0700 Subject: comparing strings and integers References: <3064b51d.0405191326.124a3ab3@posting.google.com> <mailman.93.1085003994.6949.python-list@python.org> Message-ID: <3064b51d.0405200725.c19102d@posting.google.com> Thanks to S. Nowaczyk and others for the helpful replies. If one wants if (a > b) to raise an exception when the comparison is not "sensible", maybe an alternative way of writing it is if ((a - b) > 0) This should work when 'a' and 'b' are numerical and will fail if one is numerical and the other is a string. A down side is that it does not permit string comparisons, but I rarely compare strings except for equality in my code. From dieter at handshake.de Wed May 5 17:15:24 2004 From: dieter at handshake.de (Dieter Maurer) Date: 05 May 2004 23:15:24 +0200 Subject: PEP 328 update References: <mailman.191.1083525640.25742.python-list@python.org> <109d87iiu30ct7a@news.supernews.com> Message-ID: <x7smee60er.fsf@handshake.de> "John Roth" <newsgroups at jhrothjr.com> writes on Mon, 3 May 2004 15:42:16 -0400: > "Aahz" <aahz at pythoncraft.com> wrote in message > news:mailman.191.1083525640.25742.python-list at python.org... > > PEP 328 (``import`` changes) has been updated and is available at > > http://www.python.org/peps/pep-0328.html > > > > Comments on the revised version are welcome. One area where feedback is > > particularly desired is on the frequency of relative imports inside > > packages in current code, both in absolute terms and as a percentage of > > all imports. > > What worries me about the PEP is the way it breaks backwards > compatability. I'd much rather see some kind of decorator (possibly > an !) to indicate an absolute import, and leave the undecorated form > exactly the way it is, at least until 3.0. +1 > I also don't particularly see the reason for banning the relative form > from raw import statements. +1 From usenet_spam at janc.invalid Sun May 23 11:57:11 2004 From: usenet_spam at janc.invalid (JanC) Date: Sun, 23 May 2004 15:57:11 GMT Subject: alternatives to making blocks like { } or other ?? References: <c8do0u$9fb$1@news.atman.pl> <jfvka0hj6lvluieatohoqogvgshuuo99af@4ax.com> <c8e5sh$109b$1@news.atman.pl> <slrncalqqf.8f2.grante@grante.rivatek.com> <sjDqc.108220$NR5.92596@fe1.texas.rr.com> <faf44c99.0405190420.3619b943@posting.google.com> <2h2epuF8ckqaU1@uni-berlin.de> <faf44c99.0405200407.392ab006@posting.google.com> Message-ID: <Xns94F2B6A16F8D2JanC@213.118.38.102> timothy.williams at nvl.army.mil (Tim Williams) schreef: >>> I have to put my 2 cents in here. I love Python, but the one thing I >>> miss is using {} or something to enclose blocks. I edit in emacs >>> python-mode, and believe in indentation, but sometimes I'll >>> inadvertently change a line of code's indentation and it throws the >>> logic off. I found a bug in one of my programs recently where a line >>> of code should have been outside of an 'if', but wasn't because I hit >>> TAB one too many times. A {} block would've caught that. I know that's >>> just being careless, but I need all the help I can get! >> In a brace-delimited language, you can get the >> opposite problem, which is much worse: the code >> *looks* right judging by the indentation, but it >> doesn't match the brace structure. >> >> Python is a WYSIWYG language! > But at least there, I can turn on paren-match mode in emacs and see > what code is in the block. If it's indented inconsistenly, then I can > fix how it looks, but I'm not changing the logic with whitespace. In Scintilla-based editors like SciTE you (can) get a hint of the block structure as a by-product of the folding support. An example screenshot: <http://scintilla.sf.net/SciTEImage.html> Maybe something similar is possible in emacs? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tcronj2 at ananzi.co.za Wed May 12 08:01:28 2004 From: tcronj2 at ananzi.co.za (tcronj) Date: Wed, 12 May 2004 14:01:28 +0200 Subject: distutils question Message-ID: <q_-dnb6-0p-ljT_dRVn-gQ@is.co.za> Hi, I've written a disutils setup scripts to create a binary win32 installation package. All works fine but I have 2 questions. (usage: python setup.py bdist --formats=wininst) 1.) The is application is commandline driven. I want the distribution .exe to copy certian .py files into a spesified or current directory, rather than into the site-packages/package directory. 2.) How do I specify that only .pyc files gets distributed. (I want to hold on to the source until the money is in the bank :) thnx Tertius From aahz at pythoncraft.com Sat May 22 19:40:23 2004 From: aahz at pythoncraft.com (Aahz) Date: 22 May 2004 19:40:23 -0400 Subject: terminological obscurity References: <mailman.145.1085158045.6949.python-list@python.org> <1r9ta017o5n64gman6mkt2ufg4v6m2tv1u@4ax.com> <b2bta0pue2g52ha9uhunbmeunsh0art1l6@4ax.com> <40aec6ff$0$17254$a1866201@newsreader.visi.com> Message-ID: <c8ood7$77n$1@panix3.panix.com> In article <40aec6ff$0$17254$a1866201 at newsreader.visi.com>, Grant Edwards <grante at visi.com> wrote: > >I think the fact that Python lists can be heterogogenous is one of the >most brilliantly useful things in the language, but apparently we're >not supposed to use lists like that. Since tuples aren't mutable, I'm >completely at a loss as to how we're supposed to deal with mutable >heterogenous sequences. C always required tons of extra work to do >stuff like that -- creating unions of structures with common header >fields to tell you what type of union it was and so on. It's a *guideline*, not an iron-clad restriction. Python is a language for consenting adults, after all. Part of the point is that it rarely makes sense to have an immutable homogenous collection. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Adopt A Process -- stop killing all your children! From mogmios at mlug.missouri.edu Sat May 8 15:09:44 2004 From: mogmios at mlug.missouri.edu (Michael) Date: Sat, 08 May 2004 12:09:44 -0700 Subject: urllib user agent? Message-ID: <409D3078.9080407@mlug.missouri.edu> How do you change the user agent reported by urllib? I need to access a resource that rejects anything but IE. From tim.one at comcast.net Mon May 17 15:28:02 2004 From: tim.one at comcast.net (Tim Peters) Date: Mon, 17 May 2004 15:28:02 -0400 Subject: This program makes Python segfault - no other does In-Reply-To: <pan.2004.05.17.19.02.55.248340@but.no.spam> Message-ID: <mailman.141.1572215054.32708.python-list@python.org> [Juho Saarikko] > The function unQuoteBytea allocates memory with PyMem_Malloc, and frees it > with PyMem_Free. The segfault happens at freeing the memory (as the > backtrace shows). It seems to me that if Python's memory management > routines fail to free an object they've allocated, it must be a bug in > Python. That or some other bug corrupts memory structures, Bingo. > in which case it's almost impossible to track down. At this point > I'm considering either switching to a different database plugin, or > to Java. > > I tried the new Python version (3.3.4c1) and got the exact same behaviour. > Aarrgghh. > > Here, I'll attach the unQuoteBytea function, it's a short one. Maybe you > can find some problem in it I couldn't: Yes. > PyObject *unQuoteBytea(char *sin) > { > int i, j, slen, byte; > char *sout; > PyObject *result; > > slen = strlen(sin); > sout = (char *)PyMem_Malloc(slen); You're in trouble already here. strlen(sin) does not count the trailing NUL byte, so you haven't allocated enough memory for sout to hold a NUL-terminated copy of sin. There may or may not be other C bugs here, but for starters change the last line to > sout = (char *)PyMem_Malloc(slen + 1); BTW, running under a debug-build Python would have told you that the program wrote beyond the bounds of the memory allocated for sout. From jzgoda at gazeta.usun.pl Wed May 26 16:46:35 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 26 May 2004 20:46:35 +0000 (UTC) Subject: SQL Server References: <mailman.290.1085520264.6949.python-list@python.org> <TfQsc.182529$f_5.179710@lakeread01> <c91gq1$li1$2@ctb-nnrp2.saix.net> Message-ID: <c92vna$1at$1@nemesis.news.tpi.pl> David Fraser <davidf at sjsoft.com> pisze: > I reckon its easier to use ADO. pyado.sourceforge.net or > jtoolkit.sourceforge.net have tools to do this but are GPL Adodbapi (http://adodbapi.sourceforge.net/, LGPL) offers the same functionality. -- Jarek Zgoda http://jpa.berlios.de/ From svein+usenet01 at brage.info Tue May 18 11:43:09 2004 From: svein+usenet01 at brage.info (Svein Ove Aas) Date: Tue, 18 May 2004 17:43:09 +0200 Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <tyfu0yem07c.fsf@pcepsft001.cern.ch> <mailman.49.1084890435.6949.python-list@python.org> Message-ID: <H8qqc.2256$eH3.48827@news4.e.nsc.no> Heiko Wundram wrote: > Am Dienstag, 18. Mai 2004 13:41 schrieb Jacek Generowicz: >> Native compilers for other languages just as dynamic as Python >> exist. These compilers manage to achieve very significant speed >> increases[*]. > > You are again refering to LISP as an example of a dynamic language which > when compiled gives huge speed increases. This is true in some respect, > in others it isn't. LISP has the advantage that type-inference may be > used throughout the program to create one version of each function, > which can then be compiled. Of course it still has to call into runtime > functions to do the high-level work, but there is actually only one > representation of each finished LISP program, and only one set and one > proper order of runtime-functions to call. > > In Python this isn't true. Python, instead of LISP, is "completely" > dynamic, meaning that it's pretty impossible to do type-inference for > each function that is called (even checking types isn't possible). E.g. > how do you expect type-inference to work with the pickle module? string > -> something/Error would be the best description what pickle does. For > the function which calls pickle, do you want to create versions for each > possible output of Pickle? Which outputs of Pickle are possible? > (depends on the loaded modules, which can be loaded at runtime) There is > no (sane) way to create machine-code which calls into the appropriate > (low-level) Python-runtime functions (such as Py_List*, Py_Dict*, etc.) > for such a method, at least not at compile-time. I suppose that's true; pickle is an exception, and the compiler would pick that up. (The Lisp (print) function is approximately equivalent, at least when *print-readably* is true.) What you're claiming, though, is that it's possible to write Python code that can't easily be translated to equivalent Lisp code. Can you give an example? From rowen at cesmail.net Wed May 19 14:18:03 2004 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 19 May 2004 11:18:03 -0700 Subject: urllib hanging in thread:solved! References: <rowen-AB8751.13133104052004@nntp1.u.washington.edu> <rowen-344A91.16262213052004@nntp3.u.washington.edu> Message-ID: <rowen-A45E2F.11180319052004@nntp3.u.washington.edu> In article <rowen-344A91.16262213052004 at nntp3.u.washington.edu>, "Russell E. Owen" <rowen at cesmail.net> wrote: >>I am having trouble with some ftp code. On some platforms it works fine >>and on others it reliably hangs. ...and later followed up with: >After some experimentation, I found the hanging was occurring in ftplib. >It delays importing re and compiling two regular expressions until they >are needed, and the thread hangs both on the import and (if I modify >ftplib to import re in advance) on the compilation. Modifying ftplib to >do both jobs in advance (when first imported) fixes the problem. Michael Hudson (via a separate forum) suggested the issue was contention for the "import lock" (which I'd never heard of). He was right. I originally wrote my app to be run as follows: % python <tui_root>/TUI/Main.py Later, I added a script to simplify execution (no need to mess with PYTHONPATH) and bundling as a double-clickable app: <tui_root>runtui.py whose sole contents were: import TUI.Main I knew it was ugly, but didn't realize it was dangerous. Apparently when one executes an app by importing it, the main thread holds the "import lock", which prevents other threads from importing anything. ftplib imports re when first used, and was hanging at that point. What made it tricky to debug was I had forgotten to convert my own command-line environment to running the app via the new troublesome script. So I was seeing the problem on some systems but not others. Anyway, fixing <tui_root>/TUI/Main.py to be run via a function call fixed the problem, i.e. runtui.py now reads: import TUI.Main TUI.Main.runTUI() So...a big thank you to Michael for his help and to Jack Jansen as well for useful advice with debugging multi-threaded applications. -- Russell From kveretennicov at yahoo.com Mon May 24 06:20:29 2004 From: kveretennicov at yahoo.com (Konstantin Veretennicov) Date: 24 May 2004 03:20:29 -0700 Subject: Python compilers? References: <SMvrc.1178$2H2.1033@fe2.columbus.rr.com><7xzn81rue6.fsf@ruckus.brouhaha.com><kWBrc.1595$MY4.1562@fe2.columbus.rr.com> <m23c5smwos.fsf@unique.phony.fqdn> <mailman.183.1085238574.6949.python-list@python.org> Message-ID: <5155aad2.0405240220.173d49cb@posting.google.com> "Terry Reedy" <tjreedy at udel.edu> wrote in message news:<mailman.183.1085238574.6949.python-list at python.org>... > > Interesting. PyCode can be sped up by making the same assumptions. > Richard Hettinger's recent recipe implements these assumptions. (It was > rejected as part of the standard lib for being too implementation specific, > but remains available in the archives and Python Cookbook site.) > I believe that's /Raymond/ Hettinger. Anyway, the recipe is a great stuff: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 - kv From mrfaro at libero.it Tue May 11 14:46:15 2004 From: mrfaro at libero.it (Gabriele Farina) Date: 11 May 2004 11:46:15 -0700 Subject: [wxPython] changeing border color Message-ID: <96a60ad9.0405111046.c7ba9d7@posting.google.com> Hi, how can I change the border color od a widget?? I'd like to draw a white color instead of a Black one when I use wx.SIPLE_BORDER. Any one can help me? From mark at prothon.org Mon May 24 14:31:08 2004 From: mark at prothon.org (Mark Hahn) Date: Mon, 24 May 2004 11:31:08 -0700 Subject: Prothon vs. Python integers References: <mailman.233.1085421525.6949.python-list@python.org> Message-ID: <Mbrsc.15253$bF3.12865@fed1read01> "Paul Prescod" <paul at prescod.net> wrote > I think that in this case, Python is demonstrably better than Prothon. > > C:\temp\prothon\Prothon>python > ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on > Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > > >>> print 2**65 > 36893488147419103232 > > >>> print 2**65 == (2**65 + 1) > False > > > C:\temp\prothon\Prothon>prothon > > Prothon 0.1 Interactive Console, Build 532, May 21 2004 (Ctrl-D to exit) > > >>> print 2** 65 > 3.68935e+19 > > >>> print 2**65 == (2**65 + 1) > True > > If Prothon is a language designed for the next ten years then it should > be tuned for correctness and ease of use, not for limitations of today's > hardware. I'm sure this isn't the only place Python is better. Prothon has the long integer support in the parser if anyone wants to take the trouble to put the long object code in. I did nothing to preclude it. I just didn't see any need for it myself and didn't take the trouble to put it in. Longs seemed like a needless exotic kludge to me in the 64-bit world. Surely once you get to 3.7e19 you are in floating point territory. I can't imagine counting anything up to 10**19. From dmq at gain.com Tue May 25 07:15:35 2004 From: dmq at gain.com (David MacQuigg) Date: Tue, 25 May 2004 04:15:35 -0700 Subject: Method binding confusion References: <mailman.212.1083600570.25742.python-list@python.org><c760s2$ev4$04$1@news.t-online.com> <mm5va01vovoutp9dngtbdta59h314pqkn3@4ax.com> <mailman.187.1085256635.6949.python-list@python.org> Message-ID: <f0a6b01k9o18m0ok8k33m17sp03koqgg81@4ax.com> On Sat, 22 May 2004 14:10:28 -0600, "Dave Brueck" <dave at pythonapocrypha.com> wrote: >David MacQuigg wrote: >> All functions and methods *should* be unified. See the section >> "Unification of all function forms" in PrototypeSyntax.doc at >> http://www.ece.arizona.edu/~edatools/Python > >That's cool that you've taken the time to gather your thoughts onto some pages >that anyone can view. One thing that might make them even more useful to >illustrate your point would be to have a page that shows unification in the >absense of the other changes you're proposing (in the page listed above, the >reader has to set aside prototypes and miscellaneous syntax changes and try to >focus on just function/method unification). I wrote a short example in the first post of the "Unification of Methods and Functions" thread -- how unification would look without the other changes. I also made some notes in the OOP Chapter -- showing that I plan to drop the "classless prototype" stuff in the next revision. >Also, such a page would really benefit from a few simple but uncontrived >examples of how things work now, and how they'd work after your proposed >changes. From reading that page, I'm not entirely sure how the tasks I >currently solve with bound methods, unbound methods, static functions, etc. >would work under the new system - many people learn best by example, but that >page illustrates (as far as I can tell) how only one method of calling would be >affected, and the example is obscured by unrelated syntax languages. There are some short ( contrived ) examples showing how to translate each of the four function/method styles to the new syntax in Appendix 1 of Prototypes.doc at http://ece.arizona.edu/~edatools/Python I'm also planning on translating all the examples people have submitted for my Examples and Exercises under the same address. >So, for example, find the two or three most common use cases of unbound >methods, and simplify the examples to make them concise but not so far that >they becomes overly contrived (in the math example you've posted a few times, I >have a hard time imagining why I'd ever want to do that, so to me it's not very >compelling). Show the code for the implementation as well as how the calls >happen. Then show the same for how things would look after your changes. Repeat >this whole process for all calling conventions that would be affected. > >Short of this, the ability to convince people will be limited - the problem you >cite doesn't seem to affect me much in day-to-day development, and I haven't >seen it be a big hangup for people learning the language (most don't >notice/care, the rest get past it almost instantly with the simplest of >explanations). If on top of that it's also unclear to me how I'd get the same >things done if the language were changed (and it _is_ unclear to me), then it's >hard to maintain interest in this topic. I'm getting exhausted myself. I'll post again in a few months. Looks like there is no rush in planning for Python 3. Meanwhile, those who are interested can check on the page above for anything new. -- Dave From lbates at swamisoft.com Tue May 25 17:58:38 2004 From: lbates at swamisoft.com (Larry Bates) Date: Tue, 25 May 2004 16:58:38 -0500 Subject: alter / modify a list as well as iterate on its items / objects References: <mailman.285.1085515057.6949.python-list@python.org> Message-ID: <OMadnRKIY7wQXC7dRVn-tw@comcast.com> Most of the time this is done without a loop at all as follows: word = ["albert", "likes", "surfing!"] word = [x+"foo" for x in word] word = [""albertfoo", "likesfoo", "surfing!foo"] Much of what you use loops for in other languages you don't need in Python. List comprehensions is a very powerful tool and it is worth spending some time learning about. Some tutorial links: http://www.secnetix.de/~olli/Python/list_comprehensions.haw http://www.cosc.canterbury.ac.nz/~greg/python/listcomp/ Larry Bates Syscon, Inc. "Derek Basch" <dbasch at yahoo.com> wrote in message news:mailman.285.1085515057.6949.python-list at python.org... > Hello, > > Can anyone point me towards an article or explain > how to properly alter a list as well as iterate > on its items? For example: > > input: > > word = ["albert", "likes", "surfing!"] > > for word in sentence: > word += "foo" > > result: > > word = ["albertfoo", "likesfoo", "surfingfoo"] > > Thanks, > Derek Basch > > > > > > > > __________________________________ > Do you Yahoo!? > Friends. Fun. Try the all-new Yahoo! Messenger. > http://messenger.yahoo.com/ > From davidf at sjsoft.com Wed May 19 11:48:36 2004 From: davidf at sjsoft.com (David Fraser) Date: Wed, 19 May 2004 17:48:36 +0200 Subject: PEP: import version In-Reply-To: <40aa5988$0$22949$636a15ce@news.free.fr> References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> <40a52416$0$22119$636a15ce@news.free.fr> <c8a30o$3p8$1@ctb-nnrp2.saix.net> <40aa5988$0$22949$636a15ce@news.free.fr> Message-ID: <c8fv7r$hsj$1@ctb-nnrp2.saix.net> Christophe Cavalaria wrote: > David Fraser wrote: > > >>Have you actually used it extensively? If so, I doubt you would be >>saying this... >>wxWiindows (now wxWidgets) doesn't have aconstantly mutating API. >>But the new major revision does have some changes. The point is you can >>still get programs to work with both versions, so you don't need to have >>a new name. > > > Sorry but breaking existing code with some change and calling that a minor > version upgrade not worth a new name qualifies for my definition of a > constantly mutating API ;) > Then thats your problem but don't complain about it if you don't actually use it... if you did you'd realise the changes are more minor than you make out. This is 2.4 to 2.5, not 2.4.1 to 2.4.2, so the API is allowed to change. > >>But if a program does rely on a particular version, it would >>be nice to have a way to specify it. > > > Yes, and why couldn't you do it like that : > > import wxPython24 as wxPython > Because as I said above some programs can work with either version, some require a particular one ... and you don't want the user to change the source code. Anyway if its not important to you then thats fine but there are situations in which version selection is important... David From joewong at mango.cc Wed May 5 22:00:25 2004 From: joewong at mango.cc (Joe Wong) Date: Thu, 6 May 2004 10:00:25 +0800 Subject: MySQL timeout question Message-ID: <008a01c4330d$e65b6fc0$7f00a8c0@scl01.siliconcreation.com> Hi, Is there any way to control the timeout value on db.cursor.execute()? Best regards, -- Wong -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20040506/2b491577/attachment.html> From edcjones at erols.com Wed May 12 21:43:47 2004 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 12 May 2004 21:43:47 -0400 Subject: Finding the name of a class In-Reply-To: <40A2C356.FB967FED@alcyone.com> References: <40a2be14$0$3014$61fed72c@news.rcn.com> <40A2C356.FB967FED@alcyone.com> Message-ID: <40A2D2D3.9000307@erols.com> Erik Max Francis wrote: > "Edward C. Jones" wrote: >>Is there a function or method that returns the name of a class or >>class >>instance? >> ... > > ... > Use the __name__ attribute: Thanks. Once I knew the answer, I had no trouble finding it in the documentation. See Library Reference, 3.11.1 or Reference Manual 3.2. I didn't find it because "__name__" is not listed in dir(X) or dir(X()). From eriksp at attbi.nospam.com Fri May 21 17:19:30 2004 From: eriksp at attbi.nospam.com (EAS) Date: Fri, 21 May 2004 21:19:30 GMT Subject: Command Prompt Message-ID: <Cnurc.5$hi6.3519@attbi_s53> Is there any way of using Python to open a command prompt? From godoy at ieee.org Thu May 13 18:36:29 2004 From: godoy at ieee.org (Jorge Godoy) Date: Thu, 13 May 2004 19:36:29 -0300 Subject: Help with Distutils References: <slrnca77ma.5il.johan@svedberg.pp.se> <oiqcn1-0ki.ln1@wintermute.g2ctech> <slrnca7g67.5il.johan@svedberg.pp.se> <hhvcn1-0ki.ln1@wintermute.g2ctech> <qnkbrksuk2j.fsf@arbutus.physics.mcmaster.ca> Message-ID: <o1adn1-6lm.ln1@wintermute.g2ctech> On Qui 13 Mai 2004 17:51, David M. Cooke wrote: > Of course, you have to able to find the config file, but that's a > smaller kettle of fish. I suppose you could put the config file in > your modules directory (like I suggested), and have your other data > files sitting outside (in /usr/share/whatever). If all your concerns are with unix machines, taht would be great. I don't know if his software should also run on other platforms and OSs. Anyway, you have basically two points, for Unix and Windows: /etc/something/config and c:\Windows\something\config. You can check the OS and go to the correct directory... It makes it harder to find only one file: the config file. The other way you'd have to check all the other files... -- Godoy. <godoy at ieee.org> From htx1 at gmx.de Fri May 28 17:19:05 2004 From: htx1 at gmx.de (=?ISO-8859-1?Q?Holger_T=FCrk?=) Date: Fri, 28 May 2004 23:19:05 +0200 Subject: Non-programmer needs help with PyGTK-2.0.0 In-Reply-To: <EBJtc.3968$Yf6.272@bignews1.bellsouth.net> References: <29ytc.16981$ZM1.8028@bignews6.bellsouth.net> <c971rg$bif$00$1@news.t-online.com> <EBJtc.3968$Yf6.272@bignews1.bellsouth.net> Message-ID: <c98ad3$l60$06$1@news.t-online.com> Mark Mitchell wrote: >>Where's the python standard library? >>in /usr/lib/python?.? or /usr/local/lib/python?.? ? > > I have a /usr/lib/python2.3 that has a bunch of .py .pyo .pyc files, and Python got installed with prefix /usr > I also have a; > $ ls -l /usr/local/lib/python2.3/ > total 1 > drwxr-xr-x 3 root root 192 2004-05-26 23:56 site-packages/ > >>Where did it install pygtk? >>/usr/lib/python?.?/site-packages or /usr/local/lib/python?.?/site-packages ? > > I'm not sure what exactly you're referring to here. Looking at my install > log, I have a number of .py .pyc .pyo files in > usr/local/lib/python2.3/site-packages/gtk-2.0/gtk/ and > usr/local/share/pygtk/2.0/ pygtk got installed with prefix /usr/local _Your_ Python installation doesn't look there by default. >>What's your --prefix for ./configure ? > > I didn't use one, just straight ./configure. Which means /usr/local. Try setting PYTHONPATH to /usr/local/lib/python2.3:\ /usr/local/lib/python2.3/site-packages:\ /usr/local/lib/python2.3/site-packages/gtk-2.0 If that doesn't work, do ./configure --prefix=/usr instead of ./configure as Sridhar R already pointed out. Greetings, Holger From dmq at gain.com Mon May 24 19:17:59 2004 From: dmq at gain.com (David MacQuigg) Date: Mon, 24 May 2004 16:17:59 -0700 Subject: Unification of Methods and Functions References: <889t90tdl9o9t25cv5dj6k5rnktuce0jin@4ax.com><16752bcc.0405101553.785638fd@posting.google.com><slrnca10tf.1i9.apardon@trout.vub.ac.be><16752bcc.0405111754.35d0838a@posting.google.com><11b5a097lqblgoc8bqjtfm6lnk9o1f7en8@4ax.com> <slrnca6d58.1i9.apardon@trout.vub.ac.be> <mailman.516.1084460227.25742.python-list@python.org> <3c3va050r33br5ef1r521jdrpbceuetflv@4ax.com> <1085250512.626217@yasure> <6n7va0p924l05jvvjkkbblov0c6s77rk80@4ax.com> <2hd3t4Fbk8gkU2@uni-berlin.de> Message-ID: <1qv4b09f8sp8rtfcb0fai7u4gdecaj0as8@4ax.com> On Mon, 24 May 2004 14:10:44 +1200, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote: >David MacQuigg wrote: >> The need for static methods >> will arise when the student first writes a method that needs to work >> without a current instance. > >But why would he need such a method, as opposed to >a plain function? It may be that the method/function he has written fits most naturally in a particular class. This is for the programmer to decide, and we should assume he knows his program structure better than we do. class Bag: def __init__(self, **kwargs): self.__dict__.update(kwargs) def load(infile): strng = infile.read() exec( 'bag = Bag(\n' + strng + ')' ) return bag load = staticmethod(load) The load method is unique to Bags, and it belongs in the Bag class. To me this is a more fundamental consideration than whether or not the method uses instance variables. Distinguishing methods by whether or not they use instance variables seems about like distinguishing them by whether or not they use global variables. We wouldn't want to move all "global methods" outside their classes, just because of some quirk in the syntax required it. -- Dave From csad7 at yahoo.com Sun May 16 07:57:39 2004 From: csad7 at yahoo.com (chris) Date: Sun, 16 May 2004 13:57:39 +0200 Subject: general Wiki format question and Python Wiki markup parsing libraries In-Reply-To: <c87e40$mbj$3@nemesis.news.tpi.pl> References: <c87c38$otu$07$1@news.t-online.com> <c87e40$mbj$3@nemesis.news.tpi.pl> Message-ID: <c87kvl$5j5$02$1@news.t-online.com> Jarek Zgoda wrote: > chris <csad7 at yahoo.com> pisze: > > >>is there something like a "standard" wiki format at all, or at least one >>that is widely used? > > > Don't think so. I saw more than 10 "simplified markups", of which nearly > all was more complicated than original HTML. I wanted something like > this in my JPA, so I added possibility to use Mark Pilgrim's Python > implementation of Dean Allen's Textile (originally implemented in PHP, > Perl version also exists), but Textile is really "simplified", its > capabilities are rather limited. Go to http://diveintomark.org/ and > check if PyTextile will suit your needs. > thanks for the hint. PyTextile is almost too much already and i agree almost as "complex" as HTML. something simpler like a wiki syntax would be much better... chris From No.Spam.mc at No.Spam.mclaveau.No.Spam.com Thu May 13 12:18:41 2004 From: No.Spam.mc at No.Spam.mclaveau.No.Spam.com (Michel Claveau/Hamster) Date: Thu, 13 May 2004 18:18:41 +0200 Subject: make faster Richards benchmark References: <6748553f.0405122211.5be5a150@posting.google.com> <c7v786$cu7$1@swifty.westend.com> <c7v9vo$i7a$1@news-reader2.wanadoo.fr> <c7vltk$ru1$1@swifty.westend.com> Message-ID: <c8076k$484$1@news-reader5.wanadoo.fr> >>> Mit freundlichen Gruessen, D?sol?, je ne comprend pas l'allemand. Et pourtant, en octobre, je vais aller l? : http://www.babstsoft.com/Paradox/Convention04/Info_1.htm Je pr?senterai PONX (Python for Paradox) (cf http://ponx.org) @-salutations -- Michel Claveau m?l : http://cerbermail.com/?6J1TthIa8B site : http://mclaveau.com From tfb+google at tfeb.org Wed May 26 10:33:28 2004 From: tfb+google at tfeb.org (Tim Bradshaw) Date: 26 May 2004 07:33:28 -0700 Subject: Adding your own site directories cleanly and supportedly? Message-ID: <fbc0f5d1.0405260633.54a2996e@posting.google.com> We have a situation where, on our production machines, we will probably have a standard Python installation which is installed with the system build, and which we want to use for various possible applications. These applications will probably have different library requirements, and may have conflicting requirements. We don't *know* they will, but they may do and we don't want to have to worry about it, basically. As an example, my application uses Numeric. I suspect that no-one else does, but I don't want to find out that they do, and they use an incompatible version. Of course, we should really establish a standard version and install the centrally and so on, but we probably don't have time for that. Different versions of the application might also need different versions of Numeric, and they need to be able to coexist painlessly. This looks easy to solve: Numeric uses distutils, so we can just have per-application site directories, where applications put the things they need with no fear of interference. Ah, but. How do I add an application-specific site directory, and do all the .pth file searching? It looks like I can call site.addsitedir() to add a directory of my choosing, and this will all work. This is all fine. The question is: is this the right way to do this? The documentation for site doesn't describe any functions it exports, so I'm not sure if I'm relying on something that might change or go away at some point. It seems to me that there *should* be a standard way of doing this, because it must be a common need (mustn't it?): perhaps I'm missing something, or this function should be documented? Thanks --tim From peter at engcorp.com Thu May 20 16:00:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 May 2004 16:00:29 -0400 Subject: Newbie's rant's and question :) (long post) In-Reply-To: <1e6f6533.0405201134.138b752c@posting.google.com> References: <1e6f6533.0405201134.138b752c@posting.google.com> Message-ID: <weudnQDPaYfDkzDdRVn-tA@powergate.ca> Hendy Teguh wrote: > first, a little warning, may contain negative comments, this is truly > my humble opinion, please consider it as a curious comments, not > flaming or trolling (there're tendency i read on newsgroup (especially > linux newsgroups), that newbie's opinion are often considered > trolling, especially from diehard fans :P ). Actually, newbie comments are considered trolling most commonly only when they have been using Python for all of five minutes (or sometimes two days) and they think they know exactly what is wrong and how it should be "fixed". It would be hard to consider your post a troll, especially since you are clearly not presenting your position as absolute, but are merely expressing unhappiness and confusion about your situation. > 2. so far i learned python, i got the impression that python is more > like a scripting language than programming since python rely heavily > on external libraries ... In other word, somehow python is 'teethless' > in doing something 'powerful' by itself IMHO. You have a mistaken impression, I think, based on your relatively limited experience. I know you don't know C, but you've doubtless heard of it and would, I assume, consider it a "real" programming language (whatever that is to you). Are you aware that C doesn't even include *input and output* in the basic language definition? This and almost everything else of interest is provided only by external libraries. Python (and Java, and many many other languages) is no different in this respect. The fact that Python packages up so much of its overall functionality in external libraries is really a strength, not a weakness, allowing it to change more rapidly over time in response to changes in its environment. Look at, for example, the wide variety of third-party tools for handling XML. If you were limited to just what was in the standard library you wouldn't as easily be able to choose the right tool for the right job, if you had special needs for example (e.g. performance, or low memory usage). > I'm planning to write a simple graphic viewer in paralel learning GUI. > Since python don't support natively jpeg or png (am i right?), do i > need to find library to read those file Yes, this is what you should do. Few languages have only "native" support for things like that (nor should they). > 3. just a curious question, why doesn't python include a basic library > (GUI for example)? It does! Tkinter is the standard Python GUI, included in the regular download. -Peter From irmen at -nospam-remove-this-xs4all.nl Thu May 13 13:57:18 2004 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 13 May 2004 19:57:18 +0200 Subject: ANN: Snakelets 1.30 (simple-to-use web app server with dynamic pages) Message-ID: <40a3b6fe$0$574$e4fe514c@news.xs4all.nl> I'm happy to say that Snakelets 1.30 is available. Snakelets is a Python web application server, mainly for educational purposes (but it works fine, mind you). This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). Snakelets is fully unicode compatible and it's possible to run it from a CD (read-only mode). It's released under the open-source MIT Software license. You can download from http://snakelets.sourceforge.net (go to the SF project site, and then the file section). Most relevant changes since 1.24: * compatible with Python 2.2 (2.3 recommended) * now uses a standard User class for user authentication/authorization. Privileges can be used to control access to pages and URL patterns. The 'account' webapp has been changed to use the new user object. * uses standard Python logging package for logging. * fixed character encoding error that occured in included pages. * daemon.py and monitor.py improvements. To start, edit the vhost config file (see docs) and then run the serv.py script, or the monitor.py script if you want to start it as a daemon (on Unix). Enjoy, --Irmen de Jong. From mcherm at mcherm.com Wed May 5 07:48:26 2004 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 5 May 2004 04:48:26 -0700 Subject: Python sets. Message-ID: <1083757706.4098d48a0cf33@mcherm.com> Grzegorz Dostatni writes: > Some time ago (I'm a bit fuzzy about the date) I read about sets in > python. [...] Please tell me I'm not loosing my mind. Please tell > me that these kind of things did/still exist? Yep... introduced in python 2.3. Here is the description: http://www.python.org/doc/2.3.3/whatsnew/node2.html -- Michael Chermside From mfuhr at fuhr.org Thu May 27 08:55:40 2004 From: mfuhr at fuhr.org (Michael Fuhr) Date: 27 May 2004 06:55:40 -0600 Subject: PyPGSQL - OID References: <pan.2004.05.27.09.37.51.373803@gmx.net> Message-ID: <40b5e54c$1_4@omega.dimensional.com> Manuel Huesser <sylphaleya at gmx.net> writes: > Der Python DB API supports the method oidValue on a cursor instance. > On PostgreSQL I get the internal used oid from each row, but I need > the id from the primary key. Is there a way? If you're setting the primary key from a sequence then you can use CURRVAL('sequence_name'). For example, suppose you have this table: CREATE TABLE person ( id SERIAL PRIMARY KEY, name VARCHAR(64) NOT NULL ); PostgreSQL will create a sequence named person_id_seq that will be used to populate the id field (the primary key). After an INSERT, you can use CURRVAL('person_id_seq') to refer to the primary key: curs.execute("INSERT INTO person (name) VALUES (%s)", ["Guido"]) curs.execute("SELECT * FROM person WHERE id = CURRVAL('person_id_seq')") print curs.fetchone() CURRVAL() returns the most recently used sequence number in the current connection, so you don't need to worry about the value being incremented by other connections before you get a chance to query it. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From me at here.there.nowhere Thu May 6 08:26:42 2004 From: me at here.there.nowhere (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Thu, 06 May 2004 14:26:42 +0200 Subject: the dreaded double fork References: <mailman.272.1083771384.25742.python-list@python.org> Message-ID: <409a2f02@news.mt.net.mk> > I am using python to run an xml rpc daemon using SimpleXMLRPCServer. > Following a cookbook recipe, I am trying to do a double fork so that > when I exit the shell the daemon remains running. But it doesn't. > Here is how I start the script > >> ssh somehost >> sudo python mydaemon start& > > But when I exit the shell, I lose the process. You need to close the file descriptors to the controlling TTY. This is how I do it. ????f?=?file('/dev/null',?'r+') ????fd?=?f.fileno() ????os.dup2(fd,0) ????os.dup2(fd,1) ????os.dup2(fd,2) ????f.close() Beware, sys.stdxxx.close() is not enough. -- ?????? Speak softly and carry a cellular phone. From srumbalski at copper.net Wed May 12 11:30:05 2004 From: srumbalski at copper.net (Steven Rumbalski) Date: Wed, 12 May 2004 11:30:05 -0400 Subject: getting the index while iterating through a list References: <6vl3a0lm9ph64gn4a8is8f6skijla6lq6f@4ax.com> Message-ID: <40a2433d_5@newsfeed.slurp.net> Fernando Rodr?guez wrote: > Hi, > > While iterating through a list I'd like to know not just the current > element, but also its index. Is there a better way than this: > > i = 0 > newList = [] > for element in aList: > newList.append((i, element)) > i += 1 > > Is there a more elegant way of doing this with for? And with map()? > > Thanks Try enumerate: >>> newList = [(i, element) for i, element in enumerate(aList)] from Python-Docs-2.3/lib/built-in-funcs.html: enumerate(iterable) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3. -- Steven Rumbalski news|at|rumbalski|dot|com From fredrik at pythonware.com Tue May 25 02:32:28 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 May 2004 08:32:28 +0200 Subject: Tkinter - One Canvas to Rule Them All? References: <BAY3-DAV81bg5XmllgY0000a19b@hotmail.com> Message-ID: <c8up8a$jh4$1@sea.gmane.org> Dave Harris wrote: > I derived two Frame classes and created a Canvas in each. I was extremely > surprised when frame1.canvas.delete('all') erased the image in > frame2.canvas! > > I deduce from this behavior that there is a single database behind the > scenes for the Canvas implementation. nope. that's not how the canvas work, in any Tkinter version I've ever used. maybe you've messed up and assigned the same attribute to both instances (did you, perhaps, assign the attribute to the class instead of the instance?). do you perhaps have a canvas in the global namespace, and forgot to qualify the attribute access somewhere? if you're displaying the same image in both canvases, maybe you forgot to keep a reference to the PhotoImage object in your Python code (this seems less likely, but one never knows). do you get the same behaviour also for, say, rectangle items? > I resolved my trouble by assigning tags and doing the deletion by tag. No > big deal. reminds me a little of all those "here's something I don't understand, so it has to be a bug in Python" posts we're seeing these days... </F> From moma at example.net Sun May 23 05:24:35 2004 From: moma at example.net (moma) Date: Sun, 23 May 2004 11:24:35 +0200 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] In-Reply-To: <30260531.0405222153.5027c135@posting.google.com> References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> Message-ID: <H4_rc.3295$RL3.70883@news2.e.nsc.no> simo wrote: > One thing that might attract me from Python to Prothon is if it had > proper private medthods - i.e. not just name mangling like __myDef > which can be overridden using _myClass__myDef (as the interpreter > does). > > Proper encapsulation is needed before the C++ brigade will take > P[y/ro]thon seriously as an OO language, oh and a machinecode compiler > ;-) PROthon should implement {...} as optional block-beg and end marks. # Original PROthon code (uses indentation) def abc(_x): if _x ...: do_1() do_2() do_3() Could become #!/usr/bin/pROthon #pragma(C_STYLE_BLOCK=1) # <- Valid within this file/module scope def abc(_x): { if _x ...: { do_1() do_2() } do_3() } ---------------------------------------- The lack of "class" type and direct creation and use of objects is very handy for "Prototype-based Programming" (that's PROthon) Who said OO-programming must have a class type ? // moma http:/www.futuredesktop.org From heikowu at ceosg.de Thu May 6 10:38:29 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Thu, 6 May 2004 16:38:29 +0200 Subject: Web programming ... In-Reply-To: <c7b2er$1q2uv$1@ID-205437.news.uni-berlin.de> References: <c7b2er$1q2uv$1@ID-205437.news.uni-berlin.de> Message-ID: <200405061638.29494.heikowu@ceosg.de> Am Mittwoch, 5. Mai 2004 17:49 schrieb Sarah Tanembaum: > Is python good for creating Web application? I do like the OOness of > Python, as a newbie, I'm trying to find out if Python has all its necessary > modules/utilities for Web programming just as extensive as, say, PHP or > Ruby(some say that Ruby is not ready for this sort of application and is > not yet mature as Perl, Python, and PHP - is it true?). If you're interested in CherryPy, you might as well have a look at CheesyPy (http://sourceforge.net/projects/CheesyPy). Somewhat similar to CherryPy, but different (and IMHO cleaner, but who am I to say? I developed it ;)) implementation of the OO-framework on top of the base Web-Server. CheesyPy is in no way finished yet (not even documented well enough, but browse the source luke!), but the lower-level code which is demonstrated in a simple sample application at the root of the package works out of the box already. The main difference between CherryPy and CheesyPy is the fact that CheesyPy doesn't use a precompiler, but rather __metaclass__es to pull in all classes which are to be displayed and as thus doesn't feature embedding HTML-code in a file, but rather (a so far incomplete) HTMLgen-like html generation, features builtin session handling without use of cookies, and allows you to define Plugins for web-pages which can be easily plugged into a class. These plugins may define additional functionality (such as the included example Config plugin, which reads a configuration file and offers access to it through the class instance). The web-server supports Keep-Alive and verbose error output on internal server errors. HTH! Heiko. From dmq at gain.com Sat May 22 17:00:42 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 22 May 2004 14:00:42 -0700 Subject: Unification of Methods and Functions References: <4ka7a0t585802d81i417j5ufmrdjbq6hei@4ax.com> <2gip0dF3ffrjU1@uni-berlin.de> <eoh9a0dv5hr9afrc9ud4s609jc21tt0v55@4ax.com> <2gqu12F5qqk9U1@uni-berlin.de> <gtoja0h3jub75ocnr7da8ho8i5lpihc432@4ax.com> <16752bcc.0405181600.3b6d6373@posting.google.com> <df2na01012sd7bi3jisdch9lcltduupb8m@4ax.com> <16752bcc.0405192226.27b4a93b@posting.google.com> <9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej@4ax.com> <16752bcc.0405221050.4f8711fc@posting.google.com> Message-ID: <pndva0hi800r5c132j22jv42djd36not8m@4ax.com> On 22 May 2004 11:50:18 -0700, moughanj at tcd.ie (James Moughan) wrote: >David MacQuigg <dmq at gain.com> wrote in message news:<9hgpa0d2iq5bb2ko4sngs5i6v4og90vqej at 4ax.com>... >> On 19 May 2004 23:26:38 -0700, moughanj at tcd.ie (James Moughan) wrote: >> >David MacQuigg wrote: >> I like your example, but not as a *substitute* for Animals_2. It's >> just too complex for non-CIS students at this point in the course. I >> think I understand your concerns about Animals_2. I think the best >> way to deal with those concerns is not by complicating the example, or >> by taking out everything that could lead to problems, but rather by >> pointing out the problems, and showing subsequent examples that fix >> those problems, even at the expense of more complexity. >> >> If you have a simple all-in-one alternative to Animals_2, show me. >> > >Again, clearly I have not communicated myself well - I mean a >*completely* different example to the entire Animals approach. The >difficulty with writing a good Animals-type example comes from the >things which it is trying to do, which aren't especially well >expressed by a class-heirarchy. What I am trying to do in Animals_2 is provide the simplest, most learnable example of Python OOP, which has at least one of every basic structure the students will encounter in a real program. So I include bound, unbound, and static methods, but not metaclasses or descriptors. Creating a good example like this is turning out to be more of a challenge than I expected. I'm fairly happy with Animals_2, but I appreciate the "maintainability" problems you have pointed out, and have added footnotes accordingly. The examples in Learning Python are too spread out in little pieces, and of course, no attention to the issues you are concerned about. If you know of another place I can look for a good all-in-one teaching example, I am interested. >Why not just take one of your earlier program examples, show the >students what it looks like when object-oriented, then extend the >class(es)? > >As I've mentioned, I don't like my example *at all* for your teaching >purposes, and I'm not suggesting you use it. It was simply to >illustrate that there is another method of doing things, and what the >original problems were. (A good solution to the Animals 'problem' >would be simple, it just wouldn't demonstrate any of the things you >want to show.) Then it wouldn't be a good solution. What I want to show is at least one of every structure needed in a real program. I've made your example one of the exercises. It solves a particular problem, and it is worth showing. >> We also need to make sure we include *all* children of Reptile in the >> new numReptiles function. >> >> class Reptile(Animal): >> -numReptiles = 0 >> def numReptiles(): >> return ( Reptile._numReptiles + >> Snake.numSnakes() + Lizard.numLizards() ) >> >> Oops. We forgot Geckos !! >> >> To avoid these errors in programming, we may need a function that >> automatically searches for subclasses, and calls their num functions. >> I'm not sure how to do this without making it excessively complex. >> Suggestions will be appreciated. >> >> -- Dave > >Hmm, I think perhaps I like your original example better than this. >:-\ It's a bit like treating a cut throat with a tourniquet. > >Searching the subclasses will AFAIK still require some kind of >metaprogramming, which is not too suitable for a 4-hour beginner >course on OO. Most likely, we will not cover the solutions to the maintainability problems, but we will mention them so students are aware. Electronic design engineers are good at structured, hierarchical, robust design, so I won't have to spend a lot of time on encapsulation, modularity, maintainability, etc. They are well aware of the need for protection circuits on all inputs. Pointing out the problems in a simplified program example should be sufficient. -- Dave From mark at prothon.org Sun May 23 15:26:54 2004 From: mark at prothon.org (Mark Hahn) Date: Sun, 23 May 2004 12:26:54 -0700 Subject: Prothon gets Major Facelift in Vers 0.1.0 [Prothon] References: <6iTrc.9506$bF3.8687@fed1read01> <30260531.0405222153.5027c135@posting.google.com> <h4CdnWSW5qeOPy3dRVn-ug@powergate.ca> <roy-ACE606.09255123052004@reader2.panix.com> Message-ID: <2W6sc.11802$bF3.1553@fed1read01> "Roy Smith" <roy at panix.com> wrote > 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. I love that analogy. It works on so many levels. I picture the t-shirt as tie-died and the guy wearing it with a mustache in San Francisco while the C++ guy has a suit on under the armor. From jimka at rdrop.com Sat May 29 06:25:42 2004 From: jimka at rdrop.com (Jim Newton) Date: Sat, 29 May 2004 12:25:42 +0200 Subject: generic functions in python Message-ID: <2hr9vnFfaqsjU1@uni-berlin.de> hi all, i'm relatively new to python. I find it a pretty interesting language but also somewhat limiting compared to lisp. I notice that the language does provide a few lispy type nicities, but some very important ones seem to be missing. E.g., the multiple class inheritance is great, but there are no generic functions (at least that i can find). If i have classes X, Y, and Z, and subclasses X_sub, Y_sub, and Z_sub respectively. I'd love to write methods which speicialize on pairs of these classes. It works in lisp as follows (defmethod mymethod (( x X) ( y Y)) ;; # 1 ...) (defmethod mymethod (( x X_sub) ( y Y)) ;; # 2 ...) (defmethod mymethod (( z Z) ( x X)) ;; # 3 ..) Then for example if i call mymethod with an instance of X_sub and Y_sub then # 2 gets called. These multi-methods are extremely useful to the lisp programmer. How do python programmers work around this limitation? One option would be to force all methods to have a huge case statement inside them which tests the class of the second argument. And everytime a new class is added, all the case statements have to be revisited and updated accordingly? Is there a better way? perhaps there is a standard mult-method-dispatch package available for use? -jim From me at privacy.net Wed May 19 19:08:21 2004 From: me at privacy.net (Heather Coppersmith) Date: 19 May 2004 19:08:21 -0400 Subject: Python compilers? References: <HEyqc.132$Uq1.127@fe2.columbus.rr.com> <7xad0581ax.fsf@ruckus.brouhaha.com> <60dfb6f6.0405191354.2c04a105@posting.google.com> Message-ID: <m21xlg582i.fsf@unique.phony.fqdn> On 19 May 2004 14:54:48 -0700, imbosol at aerojockey.com (Carl Banks) wrote: > Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote in message > news:<7xad0581ax.fsf at ruckus.brouhaha.com>... >> Carl Banks <imbosol at aerojockey.invalid> writes: >> > I don't follow you. In what way is Python dynamic that Lisp isn't? >> >> >> >>> class foo: >> ... def bar(self, x): >> ... return x*x >> ... >> >>> a = foo() >> >>> a.bar(3) >> 9 >> >>> a.bar = lambda x: x*x*x >> >>> a.bar(3) >> 27 >> >>> > Well, come on, of course there's going to be some things here > and there you can do in one and not the other. In wat is Python > dynamic that Lisp isn't to such an extent that it would cripple > any attempts to compile it? It's not a matter of not being able to compile python; it's a matter of what sort of benefits you'd gain. For example: if x.y.z == a.b.c: print 'equal' What is x.y.z? Who knows? The object to which x is bound might create y on the fly, based on information not available to the compiler (see __getattr__ and properties). Once the run-time system asks object x for attribute y, it (the run-time) has to go through the whole process again to determine z (and, therefore, x.y.z). Similar for a.b.c, and any of that code might have redefined what it means for such objects to be equal, which means that the compiler can't even know what sorts of equality tests might be available at the time that the code executes, let alone generate a simple compare instruction. This is important: There is little, if any, difference between that code and running everything through the interpreter anyway. For that matter, simply accessing x.y might change a.b. (FWIW, though, the ensuing programmer-cide would be entirely justified.) "Plain" Common Lisp code has (mostly) the same issues, but performance critical Common Lisp programs contain strategically placed type declarations (thus reducing the dynamicity of the language) to help the compiler to know what it's up against. There are proposals to add type declarations to Python; google is your friend (see also 'decorators'). Similar for JIT compilers (psyco falls into this category). Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From riccardo_cut-me at cut.me.sideralis.net Mon May 24 13:44:44 2004 From: riccardo_cut-me at cut.me.sideralis.net (Riccardo Attilio Galli) Date: Mon, 24 May 2004 19:44:44 +0200 Subject: Problem building pygtk-2.3.92 References: <ec6dce8b.0405231401.625cfab1@posting.google.com> Message-ID: <pan.2004.05.24.17.44.44.272793@cut.me.sideralis.net> On Sun, 23 May 2004 15:01:18 -0700, j_mckitrick wrote: > > Hi, > > I'm trying to build the latest (beta) pygtk 2.3.92 on a FreeBSD > system. [...] Do you have latest gtk+ , glib, pango and family ? Ciao, -- -=Riccardo Galli=- From frank at chagford.com Mon May 3 06:01:54 2004 From: frank at chagford.com (Frank Millman) Date: 3 May 2004 03:01:54 -0700 Subject: How to tell which subclass was used to instantiate object References: <246a4e07.0405010447.11ed5400@posting.google.com> <m2ad0suuyl.fsf@unique.phony.fqdn> <246a4e07.0405012334.5e5474db@posting.google.com> <c72ch0$6nk$04$1@news.t-online.com> Message-ID: <246a4e07.0405030201.70db95e5@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:<c72ch0$6nk$04$1 at news.t-online.com>... > Frank Millman wrote: > > > I have recently introduced the concept of a 'table type', such as > > 'Master' or 'Transaction', and have written my own subclasses with > > standard methods to handle each type of table. The table type is > > passed as an argument to the 'open' function. which now checks for a > > user-defined subclass first, if not found checks the type to see if a > > standard subclass exists, if not found instantiates the main class. > > This works well. > > > > The concern is that a table may be of type Master, but a user may > > create their own subclass and inherit from Table instead of Master by > > mistake. I want to detect this error and raise an exception. > > How about providing a subclass for every table the user might want to > subclass: > > class Table: > def __init__(self, name=None): > if name is None: > try: > name = self.name > except AttributeError: > name = self.__class__.__name__ > self.name = name > > class Master(Table): > pass > > class Transaction(Table): > pass > > # provide a suggestively named class for every table in your application > class Employees(Table): pass > class Departments(Master): pass > class Invoices(Transaction): > name = "not-a-legal-identifier" > > > for cls in [Employees, Departments, Invoices]: > print cls().name > > > Now the user can just subclass Employees without having to care whether it > has to be derived from Transaction, Master, Table or whatever. > If he needs to know, he can discover it on the command line: > > >>> issubclass(Employees, Transaction) > False > >>> issubclass(Invoices, Transaction) > True > >>> > > An additional benefit is that user code is shielded to some extent from > modifications in your code, e. g., you could later change the base of > Employees from Table to Master without requiring changes in client code. > > Peter Thanks a lot for this, Peter. I will give it some thought. However, as John has given me an easy answer, I will stick with that for now. Frank From andrew-pythonlist at puzzling.org Wed May 5 17:45:05 2004 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Thu, 6 May 2004 07:45:05 +1000 Subject: improving the Python docs -- a wiki? copy PHP's model? In-Reply-To: <b16e4ef7.0405050516.4552c6c4@posting.google.com> References: <b16e4ef7.0405041554.33a03c05@posting.google.com> <mailman.250.1083718257.25742.python-list@python.org> <b16e4ef7.0405050516.4552c6c4@posting.google.com> Message-ID: <20040505214505.GA18868@frobozz> On Wed, May 05, 2004 at 06:16:06AM -0700, Stephen Ferg wrote: > > Is submitting a bug or patch to sourceforge really that much of a barrier? > > Yes, it is a significant barrier. It requires knowledge of both Latex > and a certain way of using diff. There are many, many Python users -- > especially Python-on-Windows -- who are not familiar with these > technologies and don't have the time to learn them for the sole > purpose of making a contribution to the documentation. This is demonstrably false. I've contributed to the docs with a bug where I suggested a sentence or two that should be inserted, and that was sufficient for my text to make it into the docs. No diff, no LaTeX. I doubt I'm alone. > > As a reader, I > > prefer properly written and edited and officially approved documentation to > > ten pages of advice from people I don't know ... > > I agree. But there are gaps in the documentation, where the > officially approved documentation is silent. In such cases, I prefer > advice from others, even though I've never met them, to no help at > all. > > After all, what is comp.lang.python except advice from people that > you've (for the most part) never met. :-) comp.lang.python is also a place where you can already most likely find advice on pretty much any un- or under-documented standard library module, if you check the archives. So even here we have everything the PHP docs do. > > I've never felt that the Python documentation was particularly lacking... > > In general, I'd agree that the Python documentation is outstanding. > But there are gaps -- a qualifying phrase here, a missing reference > there, a small example in many places. Filling those gaps would make > the difference in those places between documentation that is just > barely adequate and documentation that is really excellent. You seem to know of several cases of these -- so submit bugs about them! No diff or LaTeX required, as explained above. [...] > > WE NEED TO MAKE IT EASIER FOR MANY HANDS -- INCLUDING NEWBIE HANDS -- > TO CONTRIBUTE TO THE DOCUMENTATION. This is problematic. You're quite right that newbies rely more heavily on docs than experienced users, and so they're more likely to find any problems in the docs. But they're also the least qualified to know how to fix it (as amply demonstrated by your, ahem, "impressive" example of PHP's docs on sorting arrays). Because of this, newbies generally should be submitting bugs, rather than offering patches, an activity that clearly needs no diff or LaTeX. I realise I'm sounding repetitive here, but: The only barrier is being able to submit a bug to the bug tracker. > The PHP model is a good one. Many hands contribute online. > Periodically, expert hands incorporate the best of the online > contributions into the mainline docs. How long is that period? The example you gave had comments that were several years old. How many releases of PHP have there been since 2000? -Andrew. From michele.simionato at poste.it Sun May 16 00:35:44 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 15 May 2004 21:35:44 -0700 Subject: Stackless python and microthreads References: <c80qqu$mdp$1@info4.fnal.gov> <mailman.537.1084486879.25742.python-list@python.org> <95aa1afa.0405140121.52a6d8e0@posting.google.com> <2gjokgF3mvvdU1@uni-berlin.de> <just-AEC793.15303514052004@news1.news.xs4all.nl> <2gk1k2F3li0jU1@uni-berlin.de> <just-0A0302.16084014052004@news1.news.xs4all.nl> <2gk2mtF3mcnaU1@uni-berlin.de> <95aa1afa.0405150712.2d63d6a5@posting.google.com> <du7y8nt1ip7.fsf@lehtori.cc.tut.fi> <2gnhh0F4r098U1@uni-berlin.de> Message-ID: <95aa1afa.0405152035.e7aa3a0@posting.google.com> Michael Walter <cm at leetspeak.org> wrote in message news:<2gnhh0F4r098U1 at uni-berlin.de>... > Ville Vainio wrote: > >>>>>>"Michele" == Michele Simionato <michele.simionato at poste.it> writes: > > Michele> of learning Zope TAL/TALES/METAL, which I do not like > > Michele> that much; I would rather prefer to generate HTML pages > > Michele> with Lisp macros and use real s-expressions instead of > > Michele> XML/HTML, but I can't :-( > > What would you do with macros? [..] > Syntactic abstraction. I would love to see macros in Python (actually > working on some ideas for adding them to Python). NO!! I am really talking about prefix notation: I am pro macros when you have prefix notations and s-expressions (i.e. HTML/XML), whereas I am not advocating macros in Python, which has an infix notation. There are macro systems based on pattern matching which can work with infix notation (I hear Dylan has one), but I feel somewhat happier with Lisp-style macros where everything is a list. Michele Simionato From dmq at gain.com Fri May 7 20:09:08 2004 From: dmq at gain.com (David MacQuigg) Date: Fri, 07 May 2004 17:09:08 -0700 Subject: Ideas for Python 3 References: <s1pt80h988ucqd8vbrd3occhpagtpssigg@4ax.com> <onrt805i8q1qv5amhk06pqpe8umm9i7mhc@4ax.com> <c6mtgm$e09bj$1@ID-88904.news.uni-berlin.de> <n9q490hbe2a2mp65e5rh59eb97r2k1b9hn@4ax.com> <c7b2h1$eo$1@news.service.uci.edu> <lqti90hga2d7s19r012tjfm9v1gku2glf0@4ax.com> <c7clt9$r3k$1@news.service.uci.edu> Message-ID: <1m8o90hjv5feojo19mcupv9816drmuast6@4ax.com> On Wed, 05 May 2004 23:23:52 -0700, Josiah Carlson <jcarlson at uci.edu> wrote: > >>>>L = [:x:x**2, :x:x+4, :x:x/5, :x:2-x, :x:x*7 ] >>> >>>Ick. >> >> Could you be more specific? :>) > >Sure, the general format of your anonymous function syntax given above >does not offer anything that a new user can search for. This is a good point, and one I hadn't thought of. The counter is that function definition syntax is so basic and so prevalent that any user of Python will already know it. Lambdas are seldom used, but by making their syntax almost identical to normal functions, we can make them self-explanatory. I would add one very short paragraph at the end of an introduction to functions. """ Nameless Functions ------------------ There is a short form of a function definition, which is sometimes used in lists or other places where space is tight. If you can write your function as a single expression, you can use the short form by just leaving off the function's name and the return keyword. ... example above showing long form and short form. """ [snip further discussion on searchability] >> You seem to be suggesting that the current syntax is preferable. Is >> this really what you would prefer: >> >> L = [(lambda x:x**2), (lambda x:x+4), (lambda x:x/5), >> (lambda x:2-x), (lambda x:x*7)] > >You fail to notice that: > L = [:x:x**2, :x:x+4, :x:x/5, :x:2-x, :x:x*7] >needs to be: > L = [(:x:x**2), (:x:x+4), (:x:x/5), (:x:2-x), (:x:x*7)] >...unless of course you want to remove the ability for anonymous >functions/lambdas to return tuples. I'm not seeing the need for parentheses in the above example. The commas clearly show this is a five-item list. I think the parentheses should be optional, to be used in cases where there is ambiguity, like the one you have identified below. >The only difference between the syntax you offer is the replacement of >'lambda ' with ':', which I don't believe is an advancement in the language. The important difference is that it makes the short form (lambda) almost identical to the normal form. This makes it self-explanatory, and avoids five pages in an introductory text. >> The barrier *should* be low, but it isn't. In Learning Python, 2nd >> ed., there is a 5-page section under "Advanced Topics" devoted to >> lambdas. Some experts like the association with lambda calculus, even >> though that doesn't help beginners. In fact, it only serves to make >> lambdas seem even more mysterious. The benefit of lambdas *could* be >> provided in a simple, self-explanatory syntax that requires zero pages >> in a textbook and has none of the mystique that turns off beginners. > >How about this for a manual page for lambda... > >In other languages, Python's lambda would be considered an 'anonymous >function', that is, a function that does not require a name.: > > >>> (lambda arg: arg*arg)(9) > 81 > >Certainly you can give lambdas names with standard assignments.: > > >>> square = lambda arg: arg*arg > >>> square(9) > 81 > >The equivalent function definition is below.: > > >>> def square(arg): > ... return arg*arg > ... > >>> square(9) > 81 > >Generally, lambdas are functions with a single expression in its body >whose value is returned. Just like normal function definitions, lambdas >can take multiple arguments, contain keyword arguments, return any >Python type, etc., as long as the function body is a single expression, >and whose parameters match standard function definition syntax, the >lambda is valid. (leave annotation and/or link to what an expression is) > >An ugly example of this is as follows.: > > >>> f = lambda a, b=1, *args, **kwargs: (a, b, args, kwargs) > >>> f(1,2,3,c=4) > (1, 2, (3,), {'c': 4}) > >Which is equivalent to: > > >>> def f(a, b=1, *args, **kwargs): > ... return (a, b, args, kwargs) > ... > >>> f(1,2,3,c=4) > (1, 2, (3,), {'c': 4}) > I would like to eliminate this explanation entirely, and just include a simple paragraph at the end of the introduction to functions. >> Lamdas add an unnecessary keyword and unnecessary burdens to the >> syntax of the language. The benefit is very small -- being able to >> cram a function definition in a tight space. Due to the mystique of >> lambdas, it took me a while to realize that was their only benefit. > >And removing the keyword would remove their 'mystique'? Can you imagine some mathematician trying to foist "lambda calculus" on us, when everyone can clearly see a nameless function is nothing but a function without a name? Maybe you haven't seen some of the discussions of lambda calculus. >No, all it >would do is remove a keyword from Python. Which, in itself is a good thing. > If we used your alternative >syntaxes, the 'mystique' would still exist and be unsearchable. >Removing the functionality entirely would result in no longer seeing the >below (which you use as an example): > > L = [(lambda...), > (lambda...), > ...] > >But it being replaced with: > > def fun1(arg): return ... > def fun2(arg): return ... > ... > L = [fun1, fun2,...] > >Neither of which are terribly attractive, but I prefer the lambda version. And I prefer the second form. It's a little more space, but much more clarity. Space is rarely a worry for me. >>>>f :(x): return x**2 # a simple function >>>>:x:x**2 # equivalent lambda expression >>>> >>>>-- or -- >>>> >>>>f = def(x): return x**2 >>>>def x:x**2 >>> >>>Ick on the four options just given. >> >> The parentheses are optional when we have colons around the arguments. >> Leaving them out is my preference, but I would be just as happy with >> >> L = [:(x):x**2, :(x):x+4, :(x):x/5, :(x):2-x, :(x):x*7 ] > >I'm not icking on the parenthesis, I'm icking on the general syntax. >While Python 3 is supposed to be a mythical creature that fixes all of >the problems with previous versions, I don't believe that the syntax >options you provide are a fix. In fact, what about the following... > > L[:x:x**.5] > >Using current python syntax, that is a slice into a sequence. With your >syntax, that is an anonymous function that takes an argument and returns >its square root, that is used as an index into some mappable type. Are >you also talking about changing slice syntax? Nice work!! No, I would say this is a rare case where we need to add the optional parentheses if we really want a function not a slice. The slice syntax is more important, and should have priority. >As for > a. f :(x): return x**2 > b. f = def(x): return x**2 > c. def x:x**2 > >a. Also looks like a bad slice to me. I now think that f(x): would be the best option. A normal function definition always starts at the beginning of a line, so this won't get confused with a dictionary key or list index. >b. What was wrong with: > def f(x): return x**2 See pros and cons on this issue at http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm Pro1: See all the variables at a glance in one column. Pro2: Emphasize the similarity between data and functions as attributes of an object. Pro3: Eliminates the need for special syntax in lambda functions. >c. Now you're just replacing the lambda keyword with the def keyword. Which users already understand. Also two letters shorter, since the sole purpose of lambdas is to save space. >> This would more strongly highlight the argument x, and still have a >> form that parallels the standard function definition. >> >> How about this: >> >> f(x): return x**2 >> (x):x**2 > > > > Neat and clean, but I don't know if there would be parser problems > >First looks like magic. >Second looks like a slice. >Neither are neat and clean. I think we should leave these matters of personal preference and style to GvR, and focus here on finding hidden problems, like -- This syntax won't work because ..." >> with the short form. Unlike the long form, which can only occur at >> the beginning of a line, the short form might occur in a dictionary >> item, where the colon could lead to ambiguity. Maybe we could say >> lambdas in dictionaries must be enclosed in parentheses, or maybe just >> not allow them at all where they might cause ambiguity. > >With the 'lambda' (or other equivalent) keyword, there does not exist >ambiguity. Your removal of the keyword seems to not add any >understandability to the syntax (or the one-line-function 'problem'), >but adds ambiguity to the meaning of an equivalent anonymous function. >I thought Python was about removing ambiguity, not encouraging it. The ambiguity you have discovered ( and I appreciate these discoveries ) is still an edge case, best resolved by putting the burden of adding parentheses on the least used syntax ( these nameless functions ). >>>>I am especially interested in feedback from users who have recently >>>>learned Python. I suspect that many experienced users will have long >>>>forgotten any difficulties they had while learning. > >>>Learning lambda expressions are trivial when you have experience with >>>derivatives of LISP. While I generally don't like to point users off to >>>go RTFM, in this case, 5 minutes of manual reading (without LISP >>>experience) will go a long way toward understanding lambda expressions. > >> My users ( EE students and professional design engineers ) have no >> experience with LISP. I agree, 5 minutes should be enough to explain >> lambdas properly, but unfortunately, they are not explained properly >> in the texts I have seen. > >So why are you explaining lambdas to them? If they are having >difficulty understanding them, then don't teach it. Since you are also >advocating the removal of the lambda functionality entirely, I see no >reason to show them something that they are going to struggle with >understanding. The reason we need to include lambdas is because they are now a part of the Python culture, and users will be seeing them, encountering long discussions about "lambda calculus" and other useless obfuscations. I will give a short explanation, and advice to avoid them. Students should also be aware of the discussion on pages 219-224 of Learning Python, in case they need to decipher a really nasty lambda. >If you are still going to teach them lambdas, then do it by example. >Give a simple function definition, translate it into a lambda, then have >them do it. I find that learn-by-example works pretty well, at least >for simple algorithms like definition-to-lambda. If your students can't >translate a few simple function definitions to lambdas, then Iyou should >ask yourself if they deserve to get degrees in their field. Bad attitude. They have plenty of opportunites for mental masturbation in their own field of study, and lots of pressure to do something more useful with their time. :>) >> In my humble opinion, GvR should have ignored the experts who told him >> lambdas were great, and just applied some simple common sense to find >> a better solution. > >I don't believe that lambdas were a solution to a problem. I believe >the /desire/ was to have a way of defining simple functions in a general >fashion. They do just that, allow simple functions to be defined in a >general fashion, albeit using a slightly altered function syntax. Their >ability to be placed in lists, gain names, etc., was a side-effect of >them being Python objects. Are we talking about the same thing? The *sole purpose* of lambdas is to squeeze a function into a tight space. There is no other advantage over a simple, normal, general-purpose, function definition. -- Dave From newsgroups at jhrothjr.com Thu May 13 18:11:22 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 13 May 2004 18:11:22 -0400 Subject: struct doesn't handle NaN values? References: <mailman.533.1084478961.25742.python-list@python.org> <slrnca7qt2.bdf.grante@grante.rivatek.com> Message-ID: <10a7sklcp58eb5f@news.supernews.com> "Grant Edwards" <grante at visi.com> wrote in message news:slrnca7qt2.bdf.grante at grante.rivatek.com... > On 2004-05-13, Tim Peters <tim.one at comcast.net> wrote: > > >> the struct module docs say it's IEE 754, but I can't figure > >> out how to get it to handle NaN values correctly (either > >> packing or unpacking). > > > > All Python behavior in the presence of 754 special values > > (infs, NaNs, signed zeroes) is a platform-dependent accident. > > I guess the doc that claim struct supports IEEE 754 need to > have a few footnotes added. > > > There's a growing list of these in PEP 42 (under > > "Non-accidental IEEE-754 support"), but nobody even bothers to > > keep that up to date. > > > >> >>> x = float('nan') > > > > It's even an accident that this line didn't raise an exception > > (it does, for example, under the Windows Python). > > That would be fine. Either the correct answer or an exception > I can handle would be acceptable. > > >> >>> struct.unpack("<f",'\xff\xff\xff\xff') (-6.8056469327705772e+38,) > > > > The C routine that gets invoked here is _PyFloat_Unpack4(), in > > floatobject.c. As the comment there says, > > > > /* XXX This sadly ignores Inf/NaN issues */ > > > > That is, the outcome of this is also an accident. > > Ah. That needs to be fixed. It should either return a correct > value or raise an exception. Silently returning wrong answers > is hardly the way of "least surprises". A lot of people would like the whole mess to be fixed. Unfortunately, nobody has stepped forward to do it, considering that it's quite a job to do right. Given that there's probably a bunch of stuff out there that depends on the current system dependent idiosyncracies, it would have to be done with the "from future import ..." multi-release phase in. Now that I've found the reference module, I'll probably put it into PyFIT in the next few days, but that simply patches the problem for one application. John Roth > > -- > Grant Edwards grante Yow! I'm DESPONDENT... I > at hope there's something > visi.com DEEP-FRIED under this > miniature DOMED STADIUM... From heikowu at ceosg.de Sat May 8 03:40:39 2004 From: heikowu at ceosg.de (Heiko Wundram) Date: Sat, 8 May 2004 09:40:39 +0200 Subject: __import__ In-Reply-To: <f547ce3b.0405072331.7aa6a08e@posting.google.com> References: <f547ce3b.0405072331.7aa6a08e@posting.google.com> Message-ID: <200405080940.39769.heikowu@ceosg.de> Am Samstag, 8. Mai 2004 09:31 schrieb Coder Coder: > Can someone help me with how to overload the __import__ function, > so that I can call the old __import__ function and if it cannot find > the library to be able to do something else. You shouldn't overload a builtin (at least if you expect to be compatible with other programmers libraries), but rather do the following where you need it: try: import <my-package> except ImportError: <do something else> Repeat after me: "Overloading a builtin is evil! Overloading a builtin is evil!" HTH! Heiko. From johan at svedberg.pp.se Thu May 13 12:14:02 2004 From: johan at svedberg.pp.se (Johan Svedberg) Date: Thu, 13 May 2004 16:14:02 +0000 (UTC) Subject: Help with Distutils Message-ID: <slrnca77ma.5il.johan@svedberg.pp.se> Hi! I just started playing around with Distutils and there is one thing I could use some help with. I'm wondering if there is some convenient way to access the directories where the data_files was installed? -- Johan Svedberg, johan at svedberg.pp.se, http://johan.svedberg.pp.se/ From loic at fejoz.net Fri May 7 03:47:38 2004 From: loic at fejoz.net (Yermat) Date: Fri, 07 May 2004 09:47:38 +0200 Subject: classes vs dicts In-Reply-To: <V_idnQ4n1IviAQfdRVn-ig@comcast.com> References: <be05f1d.0405060212.43929fe1@posting.google.com> <V_idnQ4n1IviAQfdRVn-ig@comcast.com> Message-ID: <c7ff4k$rdm$1@arcturus.ciril.fr> Larry Bates wrote: > You will probably want a dictionary with keys to > find people with classes stored to hold the information > about the people. That way you can extend the class > easily without disrupting your data structures. > > class person: > def __init__(self, lastname, firstname, initial): > self.lastname=lastname > self.firstname=firstname > self.initial=initial > return > > # > # Main Program > # > all_people={} > > all_people['LarryABates']=person('Larry','Bates','A') > all_people['SomeOPerson']=person('Some','Person','O') > [...] Your all_people should also be a class then it can simplify stuff ! class PersonCollection: def __init__(self): self.all_people = {} def add(self, person): key = '%s%s%s' % (person.lastname, person.initial, person.firstname) self.all_people[key] = person def __getitem__(self, key): return self.all_people[key] then you will just do : all_people = PersonCollection() all_people.add(person('Larry','Bates','A')) all_people.add(person('Some','Person','O')) But you will still be able to do : all_people['SomeOPerson'].phone = "+44 3 54 65 85 96" If Objet-Oriented languages were invented, there was a reason ! -- Yermat From jbore at tjtech.com Mon May 17 09:33:59 2004 From: jbore at tjtech.com (Joseph T. Bore) Date: Mon, 17 May 2004 13:33:59 GMT Subject: how to run an arbitrary function with timeout? References: <mailman.15.1084553467.4157.python-list@python.org> <2004051413541084557280@k2.sage.att.com> <140520041613369125%mday@apple.com> Message-ID: <m31xljkwjc.fsf@union.tjtech.com> Mark Day <mday at apple.com> writes: > In article <2004051413541084557280 at k2.sage.att.com>, Garry Hodgson > <garry at sage.att.com> wrote: > >> i would like a function RunWithTimeout( func, args, timeout ) >> i would like it to invoke the function func on arguments args. >> if timeout seconds elapse before func(args) returns, i would >> like it to raise an exception. if func(args) returns before timeout >> seconds, i would like it return the result. > > I'm guessing you want the exception raised after func has executed for > timeout seconds (as opposed to waiting for func to complete). > > Since you can't stop func from the outside (as Tim said), I suppose you > could run func in a separate thread. From the original thread, you'd > have to wait for either timeout seconds or until func completes, > whichever comes first. If the timeout happened first, then raise the > exception (else you presumably return func's result). I'm no expert on > threading in Python, but I'll bet the Library Reference has the > information you need. just use alarm and use a signal handler to be called after N seconds, this is how I do it: (I've omitted the definition of the exception for brevity) ----------------------------------------------------------- import signal # # a alarm signal handler # def alarmHandler(signum, frame): raise TimeExceededError, "Your command ran too long" # # a function that would run for too long # def infinite(): while 1: pass return # # set the alarm signal handler, and set the alarm to 1 second # signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(1) # # the function infinite would never return, after 1 second the signalHandler # is called, which immediately just raises the exception. # try: infinite() except TimeExceededError: # but after 1 second, the alarmHandler raises this # exception print "code must have gone crazy..." ----------------------------------------------------------- From edvard+news at majakari.net Wed May 26 07:58:32 2004 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 26 May 2004 14:58:32 +0300 Subject: Creating Python class wrapper for a command line tool Message-ID: <87aczvxuvr.fsf@titan.staselog.com> Hi, I was wondering what would be the most elegant way for creating a Python class wrapper for a command line utility, which takes three types of arguments: 1. options with values (--foo=bar) 2. boolean options (--squibble) 3. data lines (MUNGE:x:y:z:frob) So, when you call the program from command line it looks like command --foo=bar --hip=hurray --squibble --optimize \ MUNGE1:x1:y:z:frob1 \ MUNGE2:x2:y:z:frob2 \ MUNGE3:x3:y:z:frob3 and it produces something. The idea is to make class with methods for setting the options and data, and then calling write() after all options have been set. My current model is like this: class Wrapper: def __init__(self, **kwargs): """Initialize object""" opts = [] for key, val in kwargs.items(): if isinstance(val, str) and val.find(' ') > -1: val = '"%s"' % val opts.append("--%s %s" % (key.replace('_', '-'), val)) def setbool(self, opt): pass def data(self, data): pass def write(self): pass The init method might look a bit odd; the reason is that I thought to call Wrapper like this: obj = Wrapper(use_bar=foo, treshold=10, name="alley cat") and __init__() would transform those keyword parameters to long string of the form '--use_bar foo --threshold 10 --name "alley cat"' However, using **kwargs I cannot use boolean values, because a key in a dictionary must have a value. Using parameter boolean=True would transform to --boolean 1, which is not correct. That's why I added a separate method setbool(), but that doesn't seem nice. To wrap the command line call command --optimize --use_bar foo --threshold 10 --name "alley cat" \ MUNGE1:x1:y:z:frob1 \ MUNGE2:x2:y:z:frob2 \ MUNGE3:x3:y:z:frob3 obj = Wrapper(use_bar=foo, treshold=10, name="alley cat") obj.setbool('optimize') obj.data("MUNGE1:x1:y:z:frob1") obj.data("MUNGE2:x2:y:z:frob2") obj.data("MUNGE3:x3:y:z:frob3") This is acceptable, but I'm sure many of you professional Pythonistas have a more elegant solution. What do you think? -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From michael at stroeder.com Wed May 19 08:29:11 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 19 May 2004 14:29:11 +0200 Subject: Manipulate Windows SAM In-Reply-To: <tstrn1-km8.ln1@nb2.stroeder.com> References: <tstrn1-km8.ln1@nb2.stroeder.com> Message-ID: <nh0sn1-b3e.ln1@nb2.stroeder.com> Michael Str?der wrote: > > Does anybody know some ressource (docs or samples) about how to > add/remove users in the Windows SAM with Python and win32 extensions? Found http://starship.python.net/crew/mhammond/ppw32/index.html section "Samples"... Ciao, Michael. From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Thu May 13 08:30:17 2004 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Thu, 13 May 2004 14:30:17 +0200 Subject: Qt, multiple inheritance: QApplication and new-style class not possible In-Reply-To: <mailman.488.1084396550.25742.python-list@python.org> References: <2geeh2F1vag1U1@uni-berlin.de> <mailman.488.1084396550.25742.python-list@python.org> Message-ID: <2gh82oF2kisaU1@uni-berlin.de> Phil Thompson schrieb: >>Now I see three different ways out of this: >> >>a) use SIP v4, but it's pre-release. Moreover I'm just starting with >>Linux anyway, so I'd like to keep to ready-made rpm packages for my >>distribution (SuSE 9.1) and I can't find any. >> > I'd recommend a). The only reason SIP v4 is still a pre-release is that I said > that I'd only release the final version when the documentation was complete. > The code itself is stable with no known outstanding issues. > In that case I think I'll try it, thank you! -- 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 phil at riverbankcomputing.co.uk Wed May 12 17:15:25 2004 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 12 May 2004 22:15:25 +0100 Subject: Qt, multiple inheritance: QApplication and new-style class not possible In-Reply-To: <2geeh2F1vag1U1@uni-berlin.de> References: <2geeh2F1vag1U1@uni-berlin.de> Message-ID: <200405122215.25049.phil@riverbankcomputing.co.uk> On Wednesday 12 May 2004 12:01 pm, Sibylle Koczian wrote: > I want to try out several applications, all doing the same thing but > using different GUI libraries (Tkinter, Qt, wxWindows). Using an example > I found in a book I wrote a class containing the GUI independent methods > of the application, let's call it MyAppClass. The book is written before > Python 2.2, so it uses classic classes, but I want some properties, so I > made MyAppClass a new style class. > > For the Tkinter GUI I derive another class, TkAppClass, from this, whose > methods use Tkinter. As Qt applications need an application class > derived from QApplication, I wanted to derive my QAppClass from both > classes, QApplication and MyAppClass, but got a TypeError: "cannot > create a class derived from a SIP generated class (QApplication) and a > new-style class - use SIP v4 or later instead". > > Now I see three different ways out of this: > > a) use SIP v4, but it's pre-release. Moreover I'm just starting with > Linux anyway, so I'd like to keep to ready-made rpm packages for my > distribution (SuSE 9.1) and I can't find any. > > b) make MyAppClass a classic class. > > c) instead of deriving my QAppClass from QApplication and from > MyAppClass, derive it only from QApplication and put a reference to a > MyAppClass instance into it as an attribute. > > What's the best way (and why), or is there a d)? I'd recommend a). The only reason SIP v4 is still a pre-release is that I said that I'd only release the final version when the documentation was complete. The code itself is stable with no known outstanding issues. Phil From skip at pobox.com Thu May 13 11:28:43 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 May 2004 10:28:43 -0500 Subject: PEP: import version In-Reply-To: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> Message-ID: <16547.37931.65846.269625@montanaro.dyndns.org> Manlio> This, I think, can be resolved by allowing an user to explicitly Manlio> say what version of a module it wants (sush as version numbers Manlio> in Linux shared objects). Manlio> A possible syntax is this: Manlio> import wxPython version '2.4' Somehow that version has to map to a different file being loaded, so it seems to me the proper place to record this information is in sys.path (or before the program runs, PYTHONPATH). Voila! No syntax changes required. Skip From dmq at gain.com Sat May 1 19:14:02 2004 From: dmq at gain.com (David MacQuigg) Date: Sat, 01 May 2004 16:14:02 -0700 Subject: Unification of Methods and Functions References: <ies4909uhi4okgfao9frqnnmsarqqjcpsg@4ax.com> <mailman.154.1083347993.25742.python-list@python.org> Message-ID: <cv7890t3dfecr13qerd62eg3q7unoj6u2s@4ax.com> On Fri, 30 Apr 2004 13:59:44 -0400, Jack Diederich <jack at performancedrivers.com> wrote: >On Fri, Apr 30, 2004 at 09:47:05AM -0700, David MacQuigg wrote: >> I'm not getting any feedback on the most important benefit in my >> proposed "Ideas for Python 3" thread - the unification of methods and >> functions. Perhaps it was buried among too many other less important >> changes, so in this thread I would like to focus on that issue alone. >> ======= Syntax Examples ============= >> >> ## Proposed Syntax: >> class Cat(Feline): >> numCats = 0 >> def __init__( n = "unknown", s = "Meow" ): >> Feline.__init__() >> Cat.numCats += 1 >> .name = n # Set instance variables. >> .sound = s >> def show(): # Define a "static method". >> Feline.show() >> print " Cats:", Cat.numCats >> def talk(): >> print "My name is ...", .name >> print "I am a %s from %s" % (.genus, .home) >> Mammal.talk() # Call an unbound function. >> print __self__ ### Diagnostic check. >> >> cat1 = Cat() # Create instance. >> bf = cat1.talk # Make a bound function. >> >> >> ## Equivalent Python: >> class Cat(Feline): >> numCats = 0 >> def __init__(self, n = "unknown", s = "Meow" ): >> Feline.__init__(self) >> Cat.numCats += 1 >> self.name = n >> self.sound = s >> def show(): >> Feline.show() >> print " Cats:", Cat.numCats >> show = staticmethod(show) >> def talk(self): >> print "My name is ...", self.name >> print "I am a %s from %s" % (self.genus, self.home) >> Mammal.talk(self) >> print self >> >> cat1 = Cat() # Create instance. >> bf = cat1.talk # Make a bound function. >> >> ========= End of Examples ======= >> > >Explicit is better than implicit. >or >Magic BAAAAAAAAD [Phil Hartman as Frankenstein] I agree that magic is bad, but I disagree that the magically inserted first argument on *some* function calls is less than the magic of setting the current instance to a global variable __self__. Students at this point already understand global variables. Yet they frequently stumble on the different calling sequences for bound and unbound functions. ( cat1.talk() vs Cat.talk(cat1) ) Using a global __self__ puts the current instance in a much more convenient place, always available, but never in your way. This "out-of-your-way" aspect of the proposed __self__ is the key to getting a consistent calling sequence for all functions and methods. If you want to call a method, but you don't have a current instance, no problem. Just call it like any other function. We don't need special syntax for a "static method". It is hard to judge the complexity of a proposed syntax by looking with a microscope at something as small as setting a global variable. The way I would make the comparison is by looking at the length of a "textbook" explanation of instance variables. I believe the proposed syntax will take about half the number of lines to write a good explanation. See the examples at the end of http://ece.arizona.edu/~edatools/Python/PrototypeSyntax.htm There is a discussion of this question under the subject "Explanation of Instance Variables in Python". Greg Ewing wrote a shorter explanation than the one I prefer or the one that is in the Python tutorial. I would like to get some more opinions, especially from users who remember their first encounter with instance variables in Python. >I suggest you check out perl to see mixing instance/class/static methods >in practice. Becuase perl is weakly typed this 'makes sense' in perl, even if >it causes problems[1]. What happens in practice is bad, people write functions >that can be used in two or more ways. This makes type checking hard, and >makes code unreadable. Functions frequently do slightly different things when >called one way or another. You seem to be saying that there is a lot of confusion in Perl due to mixing instance/class/static methods. I'm not familiar with Perl, but this doesn't surprise me. It seems to *support* my proposal that we do away with these variations in method calls. They serve no purpose other than patching holes in the syntax which arose only because we have this special first argument in *some* cases. >For a python version you could do type checking on the function by doing >static analysis of the code, but that would be unpythonic. I like it when >a static function breaks badly when some yahoo tries to use self -- it breaks >early and loudly. Your way might only break on a certain code path that >tries to access '.name' and turns the method from static to instance. >If you re-added staticmethod/classmethod to clear up the distinction then >the above example just becomes a new syntax for implicit 'self'. I'm not following this. In the proposed syntax, there is no distinction between static and class or instance methods. All methods are called the same way. If you call a method that has instance variables, it will look for __self__ to resolve those variables. If __self__ is set to None, or to some inappropriate type, you will get the same error message you get now from Python: TypeError: unbound method talk() must be called with Cat instance as __self__ (got Mammal instance instead) >A version of the ':vars: expression' lambda replacement gets suggested every >so often (and that exact syntax once by me). It ain't going to happnen, labmda >is more likely to be dropped than enhanced. I think there is some value in having an anonymous function syntax, not enough to justify a keyword, but certainly enough if it can be done with a standard function definition, just leaving off the name. Here is my latest favorite function definition syntax: f(x): return x**2 Lambda form: :x:x**2 The lambda form is close enough to the standard form that it is self-explanatory. So we can drop three more pages from the standard introductory text. > >-jackdied > >[1] standard perl interview question, what is the difference between these >calls? All of these end up calling meow() with one argument, but they all >behave differently - sometimes very subtly. > >$ob = new Cat; >$ob->meow(); # intsance method >Cat->meow(); # class method >Cat::meow($ob); # static method with first argument a Cat instance The equivalent question in Python is -- explain the difference in these uses of the talk method: cat1.talk() Mammal.talk(cat1) bound_func = cat1.talk unbound_func = Mammal.talk This is a clear violation of the "explicit" rule. Yet it is one that is justified, and one that I decided to keep in the prposed syntax. The alternative is a special syntax to provide explicit binding in all situations. After weeks of debate on the Prothon list, we were not able to come up with anything better than Python's syntax. So I have decided to accept the simple implicit rule -- you get a bound function from an instance and the equivalent unbound function from its parent class. Practicality beats purity. -- Dave From qrczak at knm.org.pl Sat May 29 16:46:06 2004 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sat, 29 May 2004 22:46:06 +0200 Subject: r'\' - python parser bug? References: <mailman.224.1085410416.6949.python-list@python.org> <5155aad2.0405250137.1cd7c53e@posting.google.com> Message-ID: <pan.2004.05.29.20.46.05.234942@knm.org.pl> On Tue, 25 May 2004 02:37:06 -0700, Konstantin Veretennicov wrote: > Ok. Does it mean i'm not encouraged to even try inventing a patch? > It won't break anything, or will it? It would make impossible to insert backslash-quote in a raw string, unless this is a single quote in a double-quoted string or vice versa. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From bkelley at wi.mit.edu Thu May 20 12:27:15 2004 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 20 May 2004 12:27:15 -0400 Subject: Freeze and Resume execution In-Reply-To: <mailman.106.1085054124.6949.python-list@python.org> References: <mailman.106.1085054124.6949.python-list@python.org> Message-ID: <40acdc9d$0$557$b45e6eb0@senator-bedfellow.mit.edu> Miki Tebeka wrote: > Hello All, > > I'm looking for a way to "yield" an exception. > > Background: I'm writing a hardware simulator. I have an output buffer > and need to freeze when it's full and then when called again to resume > execution from the point where it stopped. > > Currently all I can think of is to use a class and save the state when > throwing an exception. However this required manual book keeping of the > current state (and it is complicated). > > I'd like to use generators but can't see any "nice" way of doing it. > What I'd like it to throw an exception when the buffer is full and then > next time the generator is called to continue execution as after a > "yield". I'm not sure if this helps or not, but as Peter was saying, throwing an exception is counter to resuming a state machine as raising an exception will halt execution. You can however, yield exceptions through a generator, not raise them. I do this occasionally in threaded GUI work. Here is a simple micro-thread inspired interrupt. Note however, that the exception is syntactic sugar, you can (and maybe should) use your own class for managing your simulated hardware interrupts. def work(res, length=10): while 1: if len(res) > length: # oops, need an interrupt to handle the # global state, the buffer is full yield ValueError("length > %s"%length) else: res.append(1) l = [] g = iter(work(l, 10)) while 1: # work until an interrupt err = g.next() try: raise err except ValueError: print "clearing the list" del l[0:10] > > Is this possible? > Can you recommend a good way of doing this? Any state machine? > > Thanks. > Bye. > -- > ------------------------------------------------------------------------- > Miki Tebeka <miki.tebeka at zoran.com> > http://www.cs.bgu.ac.il/~tebeka > The only difference between children and adults is the price of the toys. > > From jepler at unpythonic.net Wed May 26 18:51:32 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 26 May 2004 17:51:32 -0500 Subject: Current drive and directory In-Reply-To: <6o8tc.784$n_6.611@attbi_s53> References: <LP7tc.64476$gr.6380832@attbi_s52> <40b50a15$1_1@127.0.0.1> <6o8tc.784$n_6.611@attbi_s53> Message-ID: <20040526225132.GA1143@unpythonic.net> You'll have to parse the command yourself. If it's an "internal command" (as cd must be), then execute it in Python, not via os.system(). > print """MS-DOS Prompt > 'Q' to Quit""" > > import os > command = "" > > while command.lower() != "q": > directory = os.getcwd() > print "\n", directory, "\b>", > command = raw_input("\b") first, rest = command.split(None, 1) if first.lower() == "cd": os.chdir(rest) else > os.system(command) ... but you have to do other stuff like interpretation of quoting (For example cd "C:\Program Files\" ), and os.chdir("c:\\Program Files\\") behaves differently than typing "cd "C:\Program Files\" in command.com/cmd.exe (because the latter doesn't change the current drive letter, it just changes the current directory associated with the given drive letter) Other things that must be done in Python, not by system(): * "set" for environment variables * "a:" "b:" etc to change * @echo off * flow control (IF ERRORLEVEL, GOTO, etc) Some things are traditionally implemented in the shell, but may not work if passed to system(): * redirection * pipelines * any advanced feature in a unix shell, like job control If you want to do a shell right, there's a lot of work involved. Jeff From michael at stroeder.com Tue May 18 15:38:43 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 18 May 2004 21:38:43 +0200 Subject: ANN: python-ldap-2.0.0 Message-ID: <mailman.1084970344.3145.clpa-moderators@python.org> Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.0 2004-05-18 Changes since 2.0.0pre21: ldif: * Empty records are simply ignored in ldif.LDIFWriter.unparse() Modules/: * New method result2() returns 3-tuple containing the msgid of the outstanding operation. ldap.ldapobject: * New _ldap wrapper method LDAPObject.result2() (see above) which is now used by LDAPObject.result(). From lbates at swamisoft.com Fri May 7 11:03:42 2004 From: lbates at swamisoft.com (Larry Bates) Date: Fri, 7 May 2004 10:03:42 -0500 Subject: polymorphism w/out signatures? References: <997a06e0.0405061128.6768676d@posting.google.com> <lMWdncBA4LRcAgfd4p2dnA@comcast.com> <Xns94E25EB583B9Bduncanrcpcouk@127.0.0.1> Message-ID: <Bqudnf07T-TTOAbdRVn-iQ@comcast.com> Duncan, Thanks for your reply to my post. As all programmers I have adopted coding "techniques" that I see in others code. The technique I suggested is lifted directly from ReportLab code. I don't know if it predates the isinstance function or not (which may explain why it is not used). BTW-Your example that includes basestring apparently only works on Python 2.3. Anyway, I learned something today. Thanks again, Larry Bates Syscon, Inc. "Duncan Booth" <me at privacy.net> wrote in message news:Xns94E25EB583B9Bduncanrcpcouk at 127.0.0.1... > "Larry Bates" <lbates at swamisoft.com> wrote in > news:lMWdncBA4LRcAgfd4p2dnA at comcast.com: > > > I use: > > > > class foo: > > _stringtype=type('') > > _tupletype=type(()) > > _listtype=type([]) > > You could just use the builtin names already supplied for these: str, > tuple, and list have the same values you just assigned to _stringtype, > _tupletype, and _listtype. Also, you forgot about unicode. > > > > > def __init__(self, variable): > > if type(variable) == _stringtype: > > self.variable=variable # check for string type > > if type(variable) in (_listtype, tupletype): > > self.variable=str(variable) # check for list/tuple > > . > > If anyone has been subclassing str, list or tuple this won't work. You may > not subclass builtin types very often, but it doesn't really hurt to use > isinstance instead. That's why it is better to write: > > if isinstance(variable, (str, unicode)): > ... > > or: > > if isinstance(variable, basestring): > ... > > as either of these will catch subclassing. > From thorsten at thorstenkampe.de Tue May 18 11:57:07 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 18 May 2004 17:57:07 +0200 Subject: Python compilers? References: <Qpaqc.2106$RL3.55810@news2.e.nsc.no> <Lbgqc.2183$Hf.1280764@newshog.newsread.com> <Q3lqc.2178$eH3.47040@news4.e.nsc.no> <slrncak7aq.21u.grante@grante.rivatek.com> <uk6z94uym.fsf@broadpark.no> Message-ID: <1mklty031ke5a.dlg@thorstenkampe.de> * Tor Iver Wilhelmsen (2004-05-18 17:26 +0100) > Grant Edwards <grante at visi.com> writes: > >> Dude, didn't you take high-school math? 1/3 _is_ 0.33333... > > No, because at some point you will stop writing 3's, either out of > boredom, exhaustion or because you need to pee. At that instant, you > introduce a rounding error, making 3 * 1/3 = 0.99999999999... instead > of 1.0 Must have been a long time since you went to school... 1/3 is /exactly/ 0.3...: http://mathworld.wolfram.com/RepeatingDecimal.html Thorsten From michele.simionato at poste.it Fri May 21 23:58:03 2004 From: michele.simionato at poste.it (Michele Simionato) Date: 21 May 2004 20:58:03 -0700 Subject: ANN: kronos, a task scheduler References: <40ad1f5c$0$36860$e4fe514c@news.xs4all.nl> Message-ID: <95aa1afa.0405211958.57ae218b@posting.google.com> Irmen de Jong <irmen at -NOSPAM-REMOVETHIS-xs4all.nl> wrote in message news:<40ad1f5c$0$36860$e4fe514c at news.xs4all.nl>... > Hello > I've written a task scheduler called "kronos". > This task scheduler is designed to be used from inside your own program. > (i.e. it is not a cron daemon replacement). > You can schedule Python functions to be called at specific intervals or > days. It uses the standard 'sched' module for the actual task scheduling, > but provides much more: > - repeated tasks (at intervals, or on specific days) > - error handling (exceptions in tasks don't kill the scheduler) > - optional to run scheduler in its own thread or separate process > - optional to run a task in its own thread or separate process > > It is available from http://www.razorvine.net/download/kronos.py > > Because it is the first version I'd like to request feedback from others! > Suggestions, bugs, improvements? Please let me know. > > Your input is highly appreciated. > > --Irmen de Jong I havent't looked at the code it is unclear to me if kronos is a kind of daemon or not: what happens if I reboot my machine? Is it enough to restart kronos in some init script to get the scheduled task to be executed at the right times or is it more complicate than that? Thanks, Michele Simionato From noamr at correctme.users.sourcephorge.net Sat May 22 15:34:15 2004 From: noamr at correctme.users.sourcephorge.net (Noam Raphael) Date: Sat, 22 May 2004 22:34:15 +0300 Subject: Specify start and length, beside start and end, in slices In-Reply-To: <mailman.155.1085166502.6949.python-list@python.org> References: <c8l3s3$27o$1@news.iucc.ac.il> <mailman.155.1085166502.6949.python-list@python.org> Message-ID: <c8o9vo$las$1@news.iucc.ac.il> Hello, Terry Reedy wrote: > "Noam Raphael" <noamr at correctme.users.sourcephorge.net> wrote in message > news:c8l3s3$27o$1 at news.iucc.ac.il... > > >>Many times I find myself asking for a slice of a specific length, and >>writing something like l[12345:12345+10]. >>This happens both in interactive use and when writing Python programs, >>where I have to write an expression twice (or use a temporary variable). > > > With an expression, I'd go for the temp var. > > >>Wouldn't it be nice if the Python grammar had supported this frequent >>use? > > > I take this as 'directly support' versus the current indirect support via > start+len. > My answer: superficially (in isolation) yes, but overall, in the context of > Python's somewhat minimalistic grammar/syntax, no. Two ways to slice might > easily be seen as one too many. I agree that Python should be kept easy to read and understand. However, it doesn't mean that there's only one way to do everything. An example (it's even from slices): the Numeric people asked for the "..." token and got it, even though you can live without it - it simply makes your life easier. > In addition, the rationale for this, your > favorite little addition, would admit perhaps 50 others like it. > > >>My idea is that the expression above might be expressed as l[12345:>10]. > > > Sorry, this strike me as ugly, too much like and easily confused with > l[12345:-10], and too much looking like a syntax error. Well, of course, it *is* a syntax error right now. As for what it looks like - I can't argue with what it looks like to you, but since '>' is generally perceived as having something to do with "go in the right direction", I think that l[12345:>10] can easily be read as "start from 12345, and take 10 steps to the right. Take all the items you passed over." > > Given that some other languages slice with (start,len) arguments (but not > then, that I remember or know of, also with a start,stop option), I am > *sure* that Guido thought carefully about the issue. A plus with his > choice is ability to offset (index) from the end *without* calling the len > function. > I think that the fact that other languages use (start, len) quite contradicts your assumption that only 50 other people would like it. I don't see what brings you to think that you represent 99.99 percent of Python users. I like Python's slicing very much, and I agree that given only one slicing method, (start, end) should be chosen, but what's wrong with adding another? > >>This change, as far as I can see, is quite small: it affects only the >>grammar and byte-compiling, and has no side effects. > > > Except the cognitive dissonance of two *almost* identical syntaxes and the > flood of other 'small', 'no side effect' change requests. > Why not judge each 'small, no side effect' change request for its own sake? Do you think that Python should only undergo big and complex changes? > >>Well, what do you think? I would like to hear your comments. > > > Your wish ... Yes, I do like to hear other opinions. Perhaps *you* could have been a bit more open to hear them... > > Terry J. Reedy > > Noam Raphael From grante at visi.com Sun May 16 13:21:41 2004 From: grante at visi.com (Grant Edwards) Date: 16 May 2004 17:21:41 GMT Subject: book on wxPython? References: <slrncab3p3.ou5.grante@grante.rivatek.com> <pan.2004.05.15.03.52.15.667940@sbcglobal.net> <40a5a851$0$8512$a18e6209@newsreader.visi.com> <js4hn1-mo7.ln1@home.rogerbinns.com> <40a651f4$0$17265$a1866201@newsreader.visi.com> <cfcjn1-6ue.ln1@home.rogerbinns.com> Message-ID: <40a7a324$0$8513$a18e6209@newsreader.visi.com> In article <cfcjn1-6ue.ln1 at home.rogerbinns.com>, Roger Binns wrote: > Then use whatever suits you best! Everything seems unsuitable in different ways. Life's like that. wxWindows is looking better. > It depends on what the future for your application is. My > main application (bitpim) runs on Windows, Linux and Mac. Cool app by the way. I used it to load my phone list into my brand-new LG VX4400 about a year ago. [Best damned cell phone I've ever used, and I've been using cellular phones for 20+ years.] >>> That is news to this programmer who has been doing wxPython >>> for 3 years! >> >> What are all the calls that look like parent.AddWindow(child,...)? > > Ah, that is to do with the layout hierarchy, which has nothing > to do with the containment hierarchy. I just figured that out. It's something that's it's taken me over two years to realize (well, I wasn't working with wxWindows for most of that two years). Basic stuff like that is what somebody needs to write down somewhere. > BTW the layout hierarchy is optional - you can use absolute > sizing and positioning of your controls if you want. (And > that is normal for Windows apps - note how few dialog boxes > you can resize! Yup, that's a source of never-ending frustration when I am occasionally forced to use MS-Windows. > Yes, but at some point controls, events and functions acting > on events have to be bound together, sometimes taking into > account the class, containment or layout hierarchies. I'll > admit that wxPython's isn't the most concise or most beautiful. > But they do work. They have never been a hindrance on my > productivity, and a suspect many other people's. But if you > have a better way of expressing that, after you understand > it all at a lower level then please propose it. (I can't > really think of any). Not realizing that the containment and layout trees are _separate_ is half of what made wxPython apps appear to be a mess. None of the tutorials I worked through ever mentioned that the containment tree and the layout tree are separate. Perhaps that fact was obvious to everybody else, but I missed it completely. I thought I was constructing a single tree, and it was taking twice as much code as I thought it should. [I still think the whole integer ID thing should be hidden from the programmer, but perhaps a light will come on one of these days and that will then make sense to me as well.] >>> Generally the problem is that people don't understand that >>> there are three seperate hierarchives when dealing with GUIs. >>> There is the classes of the various controls, there is the >>> instance hierarchy and there is the layout hierarchy. >> >> Thank you! >> >> Where do I find the documentation that explains things like >> that? Teasing it out of people on Usenet is obviously a waste >> of everybody's time. > > They are actually quite hard concepts to explain, Is this more or less right? In Tk and Trestle and ??? there is a single tree of widgets. Some widgets impliment behaviors, handle user input events (mouse clicks, keystrokes, etc.) and draw stuff on the screen. Some widgets just arrange and size their children. Some do both. By contrast, in wxWidgets there are two separate trees. One tree contains widgets that impliment behaviors by handling user input events and drawing stuff on the screen. That tree is constructed by passing the 'parent' pointer to widget classes as you create instances. [I'm still a bit foggy on the function of the parent-child relationship in wxWidgets.] The other tree contains sizers that control the layout (size and position) of things. That tree is constructed by calling a sizer's .Add() method to connect child sizers to a node. In TeX-speak, sizers are like hboxes and vboxes where the and widgets are like glyphs. The sizer tree defines what's contained in each box. In wxWindows, the glyphs are also connected in a tree structure. footnote: It's possible to write an application without using a sizer tree by manually setting the position/size constraint attributes of the nodes in the widget tree. Using these constraints, you can either hard-wire sizes and positions in pixel units, or try to impliment resizing the same way sizers do. The former is evil, Evil, EVIL, and will make people assume you're a MS Windows weenie. The latter won't work right and make you crazy. The two trees are connected to each other in two ways: 1) by calling widgetInstance.SetSizer(sizerInstance). For most simple cases, this is done just once to connect the top (root) nodes of the two trees together. 2) by calling sizerInstance.Add(widgetInstance). This is generally done for the sizer tree leaf nodes, but a node in the sizer tree may have both widgets and other sizers as children. ... > and various tutorials, the online documentation and wikis do > try to explain them. I don't think any of them do a > particularly good job. > > However do feel free to write your own explanation and > contribute it to the Wiki. Once I'm confident I understand things, I think I will try to write a Tk to WxWidgets perception adjustment guide. > I won't argue as to what is best, but do believe the wxWidgets > approach is reasonable. I think so as well. I just couldn't figure out what the wxWidgets approach _was_. >> I guess those warts must be from some of the "underneaths" I've >> never worked with. > > You should try the various native gui toolkits someday - stuff > like win32, MFC, Xlib, Motif. wxWidgets/wxPython is an absolute > joy compared to them. I've done both plain Xlib apps and Xt apps with custom widgets. Not fun, though I was pretty darned proud of my backgammon board widget for Xt. The move animation was pretty cool. Too bad it was controlled by the guts of the old brain-dead BSD backgammon program -- it played a really lousy game. Neither C nor Xlib/Xt is really suitable for modern end-user application development. I've heard all sorts of nasty things about Motif, so I never tried it. > I would recommend you give wxPython 6 months even if it is > hard. It is always better to more thoroughly understand > something before wrapping it, or taking a different approach. I'm definitely going to stick with it. I blundered my way though writing and shipping one small wxWindows app a while back. Now that I've figured out the two-tree thing, it should be easier. -- Grant Edwards grante Yow! How many retired at bricklayers from FLORIDA visi.com are out purchasing PENCIL SHARPENERS right NOW?? From Chris.Barker at noaa.gov Fri May 14 12:19:40 2004 From: Chris.Barker at noaa.gov (Christopher Barker) Date: Fri, 14 May 2004 09:19:40 -0700 Subject: PEP: import version In-Reply-To: <e838aa6e.0405140617.6b9a2f4f@posting.google.com> References: <ti96a05j0aodsn5t5uk93aqr2f8l4puqe5@4ax.com> <mailman.517.1084462055.25742.python-list@python.org> <c80bsk$q8m$1@news.nems.noaa.gov> <mailman.532.1084478808.25742.python-list@python.org> <c80v79$h2o$1@news.nems.noaa.gov> <e838aa6e.0405140617.6b9a2f4f@posting.google.com> Message-ID: <c82sjs$qvm$1@news.nems.noaa.gov> A. Lloyd Flanagan wrote: > Using multiple versions in one program sounds like a recipe for > disaster to me, even with some sort of language support. Also, we > shouldn't make the normal single-version case more complex or less > efficient to support a case that should be extremely rare. This is a tricky one. I was just suggesting that while it is clear that for wxPython, you'd NEVER be able to run more than one version, that possibility should be considered for other packages. I'm imagining a module that uses a given package and version for some internal purpose. A user of that module may have no idea what packages it is using, and may happen to want to use the same package, different version. Unless data types from that package are being passed between he two versions, this could certainly work. However, you may be right that this is a recipe for disaster, and the user of that module simply needs to test with the version they are using,a nd if it fails, get an updated version of the module, so that the whole program is using the same versions of everything. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From news at outbacklinux.com Tue May 18 07:20:12 2004 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 18 May 2004 20:50:12 +0930 Subject: pexpect module References: <mailman.17.1084557068.4157.python-list@python.org> <P9Lpc.5055$xg3.4383@news01.roc.ny> <mailman.14.1084810407.6949.python-list@python.org> <40a9eca3$1@duster.adelaide.on.net> Message-ID: <40a9f0f7@duster.adelaide.on.net> Ooops - forgot the search for the prompt :-( Change the expect line to -: i=child.expect(['--More--', PROMPT],pexpect.TIMEOUT) (Assumes PROMPT evaluates to a regular expression matching the cisco prompt). Adrian Casey wrote: > First of all, look up the manual for Cisco's 'show' command. See if there > is a way to turn off the paging. If not, try to fool cisco into thinking > you have a very large page size on your terminal (e.g. 10,000 lines). > > If this is not possible, you can loop in your python script -: > > while 1: > i=child.expect('--More--',pexpect.TIMEOUT) > if i==0: > child.sendline(' ') > else: > break > > Adrian. > > Gianluca Trombetta wrote: > >> hmmm, i'm not so stupid...:-). >> The command ls -l | more was an example...i'm not really need to run ls >> -l >> | more in an automate program. >> But I need to run some cisco commands like "show ip bgp summary", this >> command print a table and put a "More" by default, if the table is too >> big for a single terminal screen. >> So I need to remove this behavior because if I match the " --More-- " >> with expect module i can match only the first one "More", then this the >> program crash and receives a timeout. >> >> Hi >> Gianluca >> >> >> >> "Lee Harr" <missive at frontiernet.net> ha scritto nel messaggio >> news:P9Lpc.5055$xg3.4383 at news01.roc.ny... >>> On 2004-05-14, Gianluca Trombetta <gianluca.trombetta at tin.it> wrote: >>> > Someone know pexpect module? >>> > I've a problem working with it... >>> > >>> > I need to run some commands on remote hosts, like ls, df -k etc..All >> right. >>> > Although, when i launch a command that have a "more" inside, i don't >> know >>> > what i must expect! >>> > An example: >>> > >>> > if i want to run an "ls -l | more" on a remote host, it don't return >>> > me >> a >>> > prompt, but a "-------------More-------------"...thus i don't know how >> much >>> > this. >>> > >>> >>> >>> The only reason I can see for piping the command through more would >>> be if there were a person sitting there wanting to read the output >>> before going on to read the next page of output. That seems counter >>> to the idea of using pexpect to automate the process. Do you >>> really need to pipe through more? >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> From p at ulmcnett.com Mon May 17 19:14:10 2004 From: p at ulmcnett.com (Paul McNett) Date: Mon, 17 May 2004 16:14:10 -0700 Subject: GUI frontend for MySQL in wxPython In-Reply-To: <BAY2-F10M8d9FkZkRbT00016279@hotmail.com> References: <BAY2-F10M8d9FkZkRbT00016279@hotmail.com> Message-ID: <200405171614.10535.p@ulmcnett.com> David Stockwell writes: > I'm very new to python as well, but if you are looking to see > what someone did as an example, take a look at > http://www.tyomych-proj.narod.ru/readme.usage.htm PMFJI, but after reading that page I just had to mention Dabo again in an act of shameless self-promotion, as it has something that does what this Java program apparently does, yet persists the output to a GUI application that you can run over and over on the database, and customize to your needs. In the dabodemo, there is a script called wizMaintenanceApp.py, which asks you for connection information and location of output directory, and then it builds a 3-tier GUI app for you that lets you specify selection criteria, browse records, and edit records of each table in the database. You can click on the browse grid headers to sort each column, and you can resize and reposition each column. The resulting application is crude and definitely feels generated, and it isn't the best general learning tool because most of the code that does all the work is in the Dabo framework and not in the generated scripts - you'd be learning mostly the Dabo API, not how do do this stuff in Python in general. But it does let you maintain your MySQL databases and it is written in Python with the wxPython toolkit, so there should be plenty of example code there to get you going. Dabo requires Python 2.3 or higher, wxPython 2.5 or higher, and MySQLdb 0.93a or higher. You need the main dabo package manually installed to site-packages, and the wizMaintenanceApp.py is in the separate dabodemo package. You can get the Dabo packages from: http://dabodev.com/download -- Paul From chuck.amadi at ntlworld.com Mon May 3 20:49:50 2004 From: chuck.amadi at ntlworld.com (chuck amadi) Date: Tue, 04 May 2004 01:49:50 +0100 Subject: Processing Python and xml PyXml - Message-ID: <4096E8AE.806@ntlworld.com> Hi all Im new to Python but regularly write xml articles for my Organisation and a past Java Sys Programmer. I can write basic Python but seem to have trouble excuting the xml/python examples . Installed PyXml and have Python 2.1,2,2 and 2.3 running . I have used SAX and ANT for building html pages from xml but im missing something here. Please can someone point me in the right direction as I usally use vi > chmod the py file and run ./file.py Please help as I need to get to grips with PyXml and xml /python processing for a project coming in soon! I have the PyXml doc's Cheers Chuck From peter at engcorp.com Wed May 5 06:41:09 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 May 2004 06:41:09 -0400 Subject: python/pyGtk : How to generate a keyboard interrupt? In-Reply-To: <eb02dbae.0405042323.25d4e9eb@posting.google.com> References: <eb02dbae.0405010731.a251212@posting.google.com> <pan.2004.05.03.19.56.08.277219@cut.me.sideralis.net> <ddqdnZEjWf0VHwvdRVn-iQ@powergate.ca> <pan.2004.05.04.02.17.41.157034@cut.me.sideralis.net> <eb02dbae.0405042323.25d4e9eb@posting.google.com> Message-ID: <IrGdnVyrzqfWWQXdRVn-vg@powergate.ca> ahk wrote: > Yup.. > Sorry that I didnt phrase my query more clearly. Is it possible to > generate all those raw keystrokes w/o actually typing on the keyboard? > Perhaps write to some keyboard buffer or something??? TIA In many GUI frameworks there is some way to "post" or "pump" generated events into the event handling system. Then one can create event objects which are the same as the events used to represent keystrokes, and the framework and application may not be able to tell the difference. Not sure if PyGTK can do this or, if so, how. -Peter From anthony at interlink.com.au Sat May 15 06:21:47 2004 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 15 May 2004 20:21:47 +1000 Subject: RELEASED Python 2.3.4, release candidate 1 In-Reply-To: <3064b51d.0405140758.4c556d8e@posting.google.com> References: <mailman.513.1084456098.25742.python-list@python.org> <3064b51d.0405140758.4c556d8e@posting.google.com> Message-ID: <40A5EF3B.4060000@interlink.com.au> beliavsky at aol.com wrote: > I wonder why the Linux installation needs to be more tedious than the > Windows counterpart. The problem is of course not specific to Python. > There are many Linux distributions, running on different kernels, but > maybe binaries that have been tested on the "major" distributions like > Debian, Red Hat / Fedora, SUSE, and Mandrake could be created. Compare > the instructions: Please note that we usually do supply RPMs for released versions of Python. This takes work, though, and it's not generally done for these interim releases. In the case of a release candidate for a bug fix release, we're talking about a lifetime of about a week - hardly worth doing the work for that little a time. I certainly anticipate that RPMs will be available for 2.3.4 (and thanks again go to Sean R. for doing the work to make this happen). As to why we provide an installer on Windows by default - most windows users do not have access to a compiler. Most Linux and Unix users do. As far as providing packages in other formats - well, this is an open source effort. Unless someone steps forward and offers the packaging work, it won't get done. Aside from anything else, I certainly don't have the tools needed to make packages for Debian, Gentoo, or whatever. (And please, I do not want to hear anyone telling me that "obviously I should be running Debian/Gentoo/ some other distribution" -- I'm happy enough with the software I'm running.) Note also that most distributors of packaged Linux provide packaged versions of Python in their distributions. One of my goals with the way I do maintenance releases is to make them as simple and as safe an upgrade as possible - this then hopefully means that the vendors will update their packaged Python sooner rather than later. hope this information is helpful, Anthony -- Anthony Baxter <anthony at interlink.com.au> It's never too late to have a happy childhood.

%s%s%s